PackageManagerService.java revision b37e1cd82fcaa7058e9fdf34749fcd19a7e2b2b4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
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.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_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.appendElement;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
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.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.app.SuspendedAppActivity;
279import com.android.internal.content.NativeLibraryHelper;
280import com.android.internal.content.PackageHelper;
281import com.android.internal.logging.MetricsLogger;
282import com.android.internal.os.IParcelFileDescriptorFactory;
283import com.android.internal.os.SomeArgs;
284import com.android.internal.os.Zygote;
285import com.android.internal.telephony.CarrierAppUtils;
286import com.android.internal.util.ArrayUtils;
287import com.android.internal.util.ConcurrentUtils;
288import com.android.internal.util.DumpUtils;
289import com.android.internal.util.FastXmlSerializer;
290import com.android.internal.util.IndentingPrintWriter;
291import com.android.internal.util.Preconditions;
292import com.android.internal.util.XmlUtils;
293import com.android.server.AttributeCache;
294import com.android.server.DeviceIdleController;
295import com.android.server.EventLogTags;
296import com.android.server.FgThread;
297import com.android.server.IntentResolver;
298import com.android.server.LocalServices;
299import com.android.server.LockGuard;
300import com.android.server.ServiceThread;
301import com.android.server.SystemConfig;
302import com.android.server.SystemServerInitThreadPool;
303import com.android.server.Watchdog;
304import com.android.server.net.NetworkPolicyManagerInternal;
305import com.android.server.pm.Installer.InstallerException;
306import com.android.server.pm.Settings.DatabaseVersion;
307import com.android.server.pm.Settings.VersionInfo;
308import com.android.server.pm.dex.ArtManagerService;
309import com.android.server.pm.dex.DexLogger;
310import com.android.server.pm.dex.DexManager;
311import com.android.server.pm.dex.DexoptOptions;
312import com.android.server.pm.dex.PackageDexUsage;
313import com.android.server.pm.permission.BasePermission;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
315import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
316import com.android.server.pm.permission.PermissionManagerInternal;
317import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
318import com.android.server.pm.permission.PermissionManagerService;
319import com.android.server.pm.permission.PermissionsState;
320import com.android.server.pm.permission.PermissionsState.PermissionState;
321import com.android.server.security.VerityUtils;
322import com.android.server.storage.DeviceStorageMonitorInternal;
323
324import dalvik.system.CloseGuard;
325import dalvik.system.VMRuntime;
326
327import libcore.io.IoUtils;
328
329import org.xmlpull.v1.XmlPullParser;
330import org.xmlpull.v1.XmlPullParserException;
331import org.xmlpull.v1.XmlSerializer;
332
333import java.io.BufferedOutputStream;
334import java.io.ByteArrayInputStream;
335import java.io.ByteArrayOutputStream;
336import java.io.File;
337import java.io.FileDescriptor;
338import java.io.FileInputStream;
339import java.io.FileOutputStream;
340import java.io.FilenameFilter;
341import java.io.IOException;
342import java.io.PrintWriter;
343import java.lang.annotation.Retention;
344import java.lang.annotation.RetentionPolicy;
345import java.nio.charset.StandardCharsets;
346import java.security.DigestException;
347import java.security.DigestInputStream;
348import java.security.MessageDigest;
349import java.security.NoSuchAlgorithmException;
350import java.security.PublicKey;
351import java.security.SecureRandom;
352import java.security.cert.CertificateException;
353import java.util.ArrayList;
354import java.util.Arrays;
355import java.util.Collection;
356import java.util.Collections;
357import java.util.Comparator;
358import java.util.HashMap;
359import java.util.HashSet;
360import java.util.Iterator;
361import java.util.LinkedHashSet;
362import java.util.List;
363import java.util.Map;
364import java.util.Objects;
365import java.util.Set;
366import java.util.concurrent.CountDownLatch;
367import java.util.concurrent.Future;
368import java.util.concurrent.TimeUnit;
369import java.util.concurrent.atomic.AtomicBoolean;
370import java.util.concurrent.atomic.AtomicInteger;
371
372/**
373 * Keep track of all those APKs everywhere.
374 * <p>
375 * Internally there are two important locks:
376 * <ul>
377 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
378 * and other related state. It is a fine-grained lock that should only be held
379 * momentarily, as it's one of the most contended locks in the system.
380 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
381 * operations typically involve heavy lifting of application data on disk. Since
382 * {@code installd} is single-threaded, and it's operations can often be slow,
383 * this lock should never be acquired while already holding {@link #mPackages}.
384 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
385 * holding {@link #mInstallLock}.
386 * </ul>
387 * Many internal methods rely on the caller to hold the appropriate locks, and
388 * this contract is expressed through method name suffixes:
389 * <ul>
390 * <li>fooLI(): the caller must hold {@link #mInstallLock}
391 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
392 * being modified must be frozen
393 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
394 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
395 * </ul>
396 * <p>
397 * Because this class is very central to the platform's security; please run all
398 * CTS and unit tests whenever making modifications:
399 *
400 * <pre>
401 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
402 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
403 * </pre>
404 */
405public class PackageManagerService extends IPackageManager.Stub
406        implements PackageSender {
407    static final String TAG = "PackageManager";
408    public static final boolean DEBUG_SETTINGS = false;
409    static final boolean DEBUG_PREFERRED = false;
410    static final boolean DEBUG_UPGRADE = false;
411    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
412    private static final boolean DEBUG_BACKUP = false;
413    public static final boolean DEBUG_INSTALL = false;
414    public static final boolean DEBUG_REMOVE = true;
415    private static final boolean DEBUG_BROADCASTS = false;
416    private static final boolean DEBUG_SHOW_INFO = false;
417    private static final boolean DEBUG_PACKAGE_INFO = false;
418    private static final boolean DEBUG_INTENT_MATCHING = false;
419    public static final boolean DEBUG_PACKAGE_SCANNING = false;
420    private static final boolean DEBUG_VERIFY = false;
421    private static final boolean DEBUG_FILTERS = false;
422    public static final boolean DEBUG_PERMISSIONS = false;
423    private static final boolean DEBUG_SHARED_LIBRARIES = false;
424    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
425
426    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
427    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
428    // user, but by default initialize to this.
429    public static final boolean DEBUG_DEXOPT = false;
430
431    private static final boolean DEBUG_ABI_SELECTION = false;
432    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
433    private static final boolean DEBUG_TRIAGED_MISSING = false;
434    private static final boolean DEBUG_APP_DATA = false;
435
436    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
437    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
438
439    private static final boolean HIDE_EPHEMERAL_APIS = false;
440
441    private static final boolean ENABLE_FREE_CACHE_V2 =
442            SystemProperties.getBoolean("fw.free_cache_v2", true);
443
444    private static final int RADIO_UID = Process.PHONE_UID;
445    private static final int LOG_UID = Process.LOG_UID;
446    private static final int NFC_UID = Process.NFC_UID;
447    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
448    private static final int SHELL_UID = Process.SHELL_UID;
449    private static final int SE_UID = Process.SE_UID;
450
451    // Suffix used during package installation when copying/moving
452    // package apks to install directory.
453    private static final String INSTALL_PACKAGE_SUFFIX = "-";
454
455    static final int SCAN_NO_DEX = 1<<0;
456    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
457    static final int SCAN_NEW_INSTALL = 1<<2;
458    static final int SCAN_UPDATE_TIME = 1<<3;
459    static final int SCAN_BOOTING = 1<<4;
460    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
461    static final int SCAN_REQUIRE_KNOWN = 1<<7;
462    static final int SCAN_MOVE = 1<<8;
463    static final int SCAN_INITIAL = 1<<9;
464    static final int SCAN_CHECK_ONLY = 1<<10;
465    static final int SCAN_DONT_KILL_APP = 1<<11;
466    static final int SCAN_IGNORE_FROZEN = 1<<12;
467    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
468    static final int SCAN_AS_INSTANT_APP = 1<<14;
469    static final int SCAN_AS_FULL_APP = 1<<15;
470    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
471    static final int SCAN_AS_SYSTEM = 1<<17;
472    static final int SCAN_AS_PRIVILEGED = 1<<18;
473    static final int SCAN_AS_OEM = 1<<19;
474    static final int SCAN_AS_VENDOR = 1<<20;
475    static final int SCAN_AS_PRODUCT = 1<<21;
476
477    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
478            SCAN_NO_DEX,
479            SCAN_UPDATE_SIGNATURE,
480            SCAN_NEW_INSTALL,
481            SCAN_UPDATE_TIME,
482            SCAN_BOOTING,
483            SCAN_DELETE_DATA_ON_FAILURES,
484            SCAN_REQUIRE_KNOWN,
485            SCAN_MOVE,
486            SCAN_INITIAL,
487            SCAN_CHECK_ONLY,
488            SCAN_DONT_KILL_APP,
489            SCAN_IGNORE_FROZEN,
490            SCAN_FIRST_BOOT_OR_UPGRADE,
491            SCAN_AS_INSTANT_APP,
492            SCAN_AS_FULL_APP,
493            SCAN_AS_VIRTUAL_PRELOAD,
494    })
495    @Retention(RetentionPolicy.SOURCE)
496    public @interface ScanFlags {}
497
498    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
499    /** Extension of the compressed packages */
500    public final static String COMPRESSED_EXTENSION = ".gz";
501    /** Suffix of stub packages on the system partition */
502    public final static String STUB_SUFFIX = "-Stub";
503
504    private static final int[] EMPTY_INT_ARRAY = new int[0];
505
506    private static final int TYPE_UNKNOWN = 0;
507    private static final int TYPE_ACTIVITY = 1;
508    private static final int TYPE_RECEIVER = 2;
509    private static final int TYPE_SERVICE = 3;
510    private static final int TYPE_PROVIDER = 4;
511    @IntDef(prefix = { "TYPE_" }, value = {
512            TYPE_UNKNOWN,
513            TYPE_ACTIVITY,
514            TYPE_RECEIVER,
515            TYPE_SERVICE,
516            TYPE_PROVIDER,
517    })
518    @Retention(RetentionPolicy.SOURCE)
519    public @interface ComponentType {}
520
521    /**
522     * Timeout (in milliseconds) after which the watchdog should declare that
523     * our handler thread is wedged.  The usual default for such things is one
524     * minute but we sometimes do very lengthy I/O operations on this thread,
525     * such as installing multi-gigabyte applications, so ours needs to be longer.
526     */
527    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
528
529    /**
530     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
531     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
532     * settings entry if available, otherwise we use the hardcoded default.  If it's been
533     * more than this long since the last fstrim, we force one during the boot sequence.
534     *
535     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
536     * one gets run at the next available charging+idle time.  This final mandatory
537     * no-fstrim check kicks in only of the other scheduling criteria is never met.
538     */
539    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
540
541    /**
542     * Whether verification is enabled by default.
543     */
544    private static final boolean DEFAULT_VERIFY_ENABLE = true;
545
546    /**
547     * The default maximum time to wait for the verification agent to return in
548     * milliseconds.
549     */
550    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
551
552    /**
553     * The default response for package verification timeout.
554     *
555     * This can be either PackageManager.VERIFICATION_ALLOW or
556     * PackageManager.VERIFICATION_REJECT.
557     */
558    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
559
560    public static final String PLATFORM_PACKAGE_NAME = "android";
561
562    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
563
564    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
565            DEFAULT_CONTAINER_PACKAGE,
566            "com.android.defcontainer.DefaultContainerService");
567
568    private static final String KILL_APP_REASON_GIDS_CHANGED =
569            "permission grant or revoke changed gids";
570
571    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
572            "permissions revoked";
573
574    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
575
576    private static final String PACKAGE_SCHEME = "package";
577
578    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
579
580    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
581
582    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
583
584    /** Canonical intent used to identify what counts as a "web browser" app */
585    private static final Intent sBrowserIntent;
586    static {
587        sBrowserIntent = new Intent();
588        sBrowserIntent.setAction(Intent.ACTION_VIEW);
589        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
590        sBrowserIntent.setData(Uri.parse("http:"));
591        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
592    }
593
594    /**
595     * The set of all protected actions [i.e. those actions for which a high priority
596     * intent filter is disallowed].
597     */
598    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
599    static {
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
601        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
602        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
603        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
604    }
605
606    // Compilation reasons.
607    public static final int REASON_UNKNOWN = -1;
608    public static final int REASON_FIRST_BOOT = 0;
609    public static final int REASON_BOOT = 1;
610    public static final int REASON_INSTALL = 2;
611    public static final int REASON_BACKGROUND_DEXOPT = 3;
612    public static final int REASON_AB_OTA = 4;
613    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
614    public static final int REASON_SHARED = 6;
615
616    public static final int REASON_LAST = REASON_SHARED;
617
618    /**
619     * Version number for the package parser cache. Increment this whenever the format or
620     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
621     */
622    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
623
624    /**
625     * Whether the package parser cache is enabled.
626     */
627    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
628
629    /**
630     * Permissions required in order to receive instant application lifecycle broadcasts.
631     */
632    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
633            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
634
635    final ServiceThread mHandlerThread;
636
637    final PackageHandler mHandler;
638
639    private final ProcessLoggingHandler mProcessLoggingHandler;
640
641    /**
642     * Messages for {@link #mHandler} that need to wait for system ready before
643     * being dispatched.
644     */
645    private ArrayList<Message> mPostSystemReadyMessages;
646
647    final int mSdkVersion = Build.VERSION.SDK_INT;
648
649    final Context mContext;
650    final boolean mFactoryTest;
651    final boolean mOnlyCore;
652    final DisplayMetrics mMetrics;
653    final int mDefParseFlags;
654    final String[] mSeparateProcesses;
655    final boolean mIsUpgrade;
656    final boolean mIsPreNUpgrade;
657    final boolean mIsPreNMR1Upgrade;
658
659    // Have we told the Activity Manager to whitelist the default container service by uid yet?
660    @GuardedBy("mPackages")
661    boolean mDefaultContainerWhitelisted = false;
662
663    @GuardedBy("mPackages")
664    private boolean mDexOptDialogShown;
665
666    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
667    // LOCK HELD.  Can be called with mInstallLock held.
668    @GuardedBy("mInstallLock")
669    final Installer mInstaller;
670
671    /** Directory where installed applications are stored */
672    private static final File sAppInstallDir =
673            new File(Environment.getDataDirectory(), "app");
674    /** Directory where installed application's 32-bit native libraries are copied. */
675    private static final File sAppLib32InstallDir =
676            new File(Environment.getDataDirectory(), "app-lib");
677    /** Directory where code and non-resource assets of forward-locked applications are stored */
678    private static final File sDrmAppPrivateInstallDir =
679            new File(Environment.getDataDirectory(), "app-private");
680
681    // ----------------------------------------------------------------
682
683    // Lock for state used when installing and doing other long running
684    // operations.  Methods that must be called with this lock held have
685    // the suffix "LI".
686    final Object mInstallLock = new Object();
687
688    // ----------------------------------------------------------------
689
690    // Keys are String (package name), values are Package.  This also serves
691    // as the lock for the global state.  Methods that must be called with
692    // this lock held have the prefix "LP".
693    @GuardedBy("mPackages")
694    final ArrayMap<String, PackageParser.Package> mPackages =
695            new ArrayMap<String, PackageParser.Package>();
696
697    final ArrayMap<String, Set<String>> mKnownCodebase =
698            new ArrayMap<String, Set<String>>();
699
700    // Keys are isolated uids and values are the uid of the application
701    // that created the isolated proccess.
702    @GuardedBy("mPackages")
703    final SparseIntArray mIsolatedOwners = new SparseIntArray();
704
705    /**
706     * Tracks new system packages [received in an OTA] that we expect to
707     * find updated user-installed versions. Keys are package name, values
708     * are package location.
709     */
710    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
711    /**
712     * Tracks high priority intent filters for protected actions. During boot, certain
713     * filter actions are protected and should never be allowed to have a high priority
714     * intent filter for them. However, there is one, and only one exception -- the
715     * setup wizard. It must be able to define a high priority intent filter for these
716     * actions to ensure there are no escapes from the wizard. We need to delay processing
717     * of these during boot as we need to look at all of the system packages in order
718     * to know which component is the setup wizard.
719     */
720    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
721    /**
722     * Whether or not processing protected filters should be deferred.
723     */
724    private boolean mDeferProtectedFilters = true;
725
726    /**
727     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
728     */
729    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
730    /**
731     * Whether or not system app permissions should be promoted from install to runtime.
732     */
733    boolean mPromoteSystemApps;
734
735    @GuardedBy("mPackages")
736    final Settings mSettings;
737
738    /**
739     * Set of package names that are currently "frozen", which means active
740     * surgery is being done on the code/data for that package. The platform
741     * will refuse to launch frozen packages to avoid race conditions.
742     *
743     * @see PackageFreezer
744     */
745    @GuardedBy("mPackages")
746    final ArraySet<String> mFrozenPackages = new ArraySet<>();
747
748    final ProtectedPackages mProtectedPackages;
749
750    @GuardedBy("mLoadedVolumes")
751    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
752
753    boolean mFirstBoot;
754
755    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
756
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    @GuardedBy("mPackages")
778    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackages(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            if ("android".equals(targetPackageName)) {
788                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
789                // native AssetManager.
790                return null;
791            }
792
793            List<PackageParser.Package> overlayPackages = null;
794            for (PackageParser.Package p : allPackages) {
795                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
796                    if (overlayPackages == null) {
797                        overlayPackages = new ArrayList<PackageParser.Package>();
798                    }
799                    overlayPackages.add(p);
800                }
801            }
802            if (overlayPackages != null) {
803                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
804                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
805                        return p1.mOverlayPriority - p2.mOverlayPriority;
806                    }
807                };
808                Collections.sort(overlayPackages, cmp);
809            }
810            return overlayPackages;
811        }
812
813        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
814                String targetPath) {
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            List<PackageParser.Package> overlayPackages;
851            synchronized (mInstallLock) {
852                synchronized (mPackages) {
853                    overlayPackages = getStaticOverlayPackages(
854                            mPackages.values(), targetPackageName);
855                }
856                // It is safe to keep overlayPackages without holding mPackages because static overlay
857                // packages can't be uninstalled or disabled.
858                return getStaticOverlayPaths(overlayPackages, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    }
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mOverlayIsStatic) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
893            // because mInstallLock is held before running parallel parsing.
894            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
895            return mOverlayPackages == null ? null :
896                    getStaticOverlayPaths(
897                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
898                            targetPath);
899        }
900    }
901
902    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
903    final ParallelPackageParserCallback mParallelPackageParserCallback =
904            new ParallelPackageParserCallback();
905
906    public static final class SharedLibraryEntry {
907        public final @Nullable String path;
908        public final @Nullable String apk;
909        public final @NonNull SharedLibraryInfo info;
910
911        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
912                String declaringPackageName, long declaringPackageVersionCode) {
913            path = _path;
914            apk = _apk;
915            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
916                    declaringPackageName, declaringPackageVersionCode), null);
917        }
918    }
919
920    // Currently known shared libraries.
921    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
922    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
923            new ArrayMap<>();
924
925    // All available activities, for your resolving pleasure.
926    final ActivityIntentResolver mActivities =
927            new ActivityIntentResolver();
928
929    // All available receivers, for your resolving pleasure.
930    final ActivityIntentResolver mReceivers =
931            new ActivityIntentResolver();
932
933    // All available services, for your resolving pleasure.
934    final ServiceIntentResolver mServices = new ServiceIntentResolver();
935
936    // All available providers, for your resolving pleasure.
937    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
938
939    // Mapping from provider base names (first directory in content URI codePath)
940    // to the provider information.
941    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
942            new ArrayMap<String, PackageParser.Provider>();
943
944    // Mapping from instrumentation class names to info about them.
945    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
946            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    final PackageInstallerService mInstallerService;
961
962    final ArtManagerService mArtManagerService;
963
964    private final PackageDexOptimizer mPackageDexOptimizer;
965    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
966    // is used by other apps).
967    private final DexManager mDexManager;
968
969    private AtomicInteger mNextMoveId = new AtomicInteger();
970    private final MoveCallbacks mMoveCallbacks;
971
972    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
973
974    // Cache of users who need badging.
975    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
976
977    /** Token for keys in mPendingVerification. */
978    private int mPendingVerificationToken = 0;
979
980    volatile boolean mSystemReady;
981    volatile boolean mSafeMode;
982    volatile boolean mHasSystemUidErrors;
983    private volatile boolean mWebInstantAppsDisabled;
984
985    ApplicationInfo mAndroidApplication;
986    final ActivityInfo mResolveActivity = new ActivityInfo();
987    final ResolveInfo mResolveInfo = new ResolveInfo();
988    ComponentName mResolveComponentName;
989    PackageParser.Package mPlatformPackage;
990    ComponentName mCustomResolverComponentName;
991
992    boolean mResolverReplaced = false;
993
994    private final @Nullable ComponentName mIntentFilterVerifierComponent;
995    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
996
997    private int mIntentFilterVerificationToken = 0;
998
999    /** The service connection to the ephemeral resolver */
1000    final InstantAppResolverConnection mInstantAppResolverConnection;
1001    /** Component used to show resolver settings for Instant Apps */
1002    final ComponentName mInstantAppResolverSettingsComponent;
1003
1004    /** Activity used to install instant applications */
1005    ActivityInfo mInstantAppInstallerActivity;
1006    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1007
1008    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1009            = new SparseArray<IntentFilterVerificationState>();
1010
1011    // TODO remove this and go through mPermissonManager directly
1012    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1013    private final PermissionManagerInternal mPermissionManager;
1014
1015    // List of packages names to keep cached, even if they are uninstalled for all users
1016    private List<String> mKeepUninstalledPackages;
1017
1018    private UserManagerInternal mUserManagerInternal;
1019    private ActivityManagerInternal mActivityManagerInternal;
1020
1021    private DeviceIdleController.LocalService mDeviceIdleController;
1022
1023    private File mCacheDir;
1024
1025    private Future<?> mPrepareAppDataFuture;
1026
1027    private static class IFVerificationParams {
1028        PackageParser.Package pkg;
1029        boolean replacing;
1030        int userId;
1031        int verifierUid;
1032
1033        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1034                int _userId, int _verifierUid) {
1035            pkg = _pkg;
1036            replacing = _replacing;
1037            userId = _userId;
1038            replacing = _replacing;
1039            verifierUid = _verifierUid;
1040        }
1041    }
1042
1043    private interface IntentFilterVerifier<T extends IntentFilter> {
1044        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1045                                               T filter, String packageName);
1046        void startVerifications(int userId);
1047        void receiveVerificationResponse(int verificationId);
1048    }
1049
1050    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1051        private Context mContext;
1052        private ComponentName mIntentFilterVerifierComponent;
1053        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1054
1055        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1056            mContext = context;
1057            mIntentFilterVerifierComponent = verifierComponent;
1058        }
1059
1060        private String getDefaultScheme() {
1061            return IntentFilter.SCHEME_HTTPS;
1062        }
1063
1064        @Override
1065        public void startVerifications(int userId) {
1066            // Launch verifications requests
1067            int count = mCurrentIntentFilterVerifications.size();
1068            for (int n=0; n<count; n++) {
1069                int verificationId = mCurrentIntentFilterVerifications.get(n);
1070                final IntentFilterVerificationState ivs =
1071                        mIntentFilterVerificationStates.get(verificationId);
1072
1073                String packageName = ivs.getPackageName();
1074
1075                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1076                final int filterCount = filters.size();
1077                ArraySet<String> domainsSet = new ArraySet<>();
1078                for (int m=0; m<filterCount; m++) {
1079                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1080                    domainsSet.addAll(filter.getHostsList());
1081                }
1082                synchronized (mPackages) {
1083                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1084                            packageName, domainsSet) != null) {
1085                        scheduleWriteSettingsLocked();
1086                    }
1087                }
1088                sendVerificationRequest(verificationId, ivs);
1089            }
1090            mCurrentIntentFilterVerifications.clear();
1091        }
1092
1093        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1094            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1097                    verificationId);
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1100                    getDefaultScheme());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1103                    ivs.getHostsString());
1104            verificationIntent.putExtra(
1105                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1106                    ivs.getPackageName());
1107            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1108            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1109
1110            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1111            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1112                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1113                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1114
1115            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Sending IntentFilter verification broadcast");
1118        }
1119
1120        public void receiveVerificationResponse(int verificationId) {
1121            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1122
1123            final boolean verified = ivs.isVerified();
1124
1125            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1126            final int count = filters.size();
1127            if (DEBUG_DOMAIN_VERIFICATION) {
1128                Slog.i(TAG, "Received verification response " + verificationId
1129                        + " for " + count + " filters, verified=" + verified);
1130            }
1131            for (int n=0; n<count; n++) {
1132                PackageParser.ActivityIntentInfo filter = filters.get(n);
1133                filter.setVerified(verified);
1134
1135                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1136                        + " verified with result:" + verified + " and hosts:"
1137                        + ivs.getHostsString());
1138            }
1139
1140            mIntentFilterVerificationStates.remove(verificationId);
1141
1142            final String packageName = ivs.getPackageName();
1143            IntentFilterVerificationInfo ivi = null;
1144
1145            synchronized (mPackages) {
1146                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1147            }
1148            if (ivi == null) {
1149                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1150                        + verificationId + " packageName:" + packageName);
1151                return;
1152            }
1153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1154                    "Updating IntentFilterVerificationInfo for package " + packageName
1155                            +" verificationId:" + verificationId);
1156
1157            synchronized (mPackages) {
1158                if (verified) {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1160                } else {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1162                }
1163                scheduleWriteSettingsLocked();
1164
1165                final int userId = ivs.getUserId();
1166                if (userId != UserHandle.USER_ALL) {
1167                    final int userStatus =
1168                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1169
1170                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1171                    boolean needUpdate = false;
1172
1173                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1174                    // already been set by the User thru the Disambiguation dialog
1175                    switch (userStatus) {
1176                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1177                            if (verified) {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1179                            } else {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1181                            }
1182                            needUpdate = true;
1183                            break;
1184
1185                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1186                            if (verified) {
1187                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1188                                needUpdate = true;
1189                            }
1190                            break;
1191
1192                        default:
1193                            // Nothing to do
1194                    }
1195
1196                    if (needUpdate) {
1197                        mSettings.updateIntentFilterVerificationStatusLPw(
1198                                packageName, updatedStatus, userId);
1199                        scheduleWritePackageRestrictionsLocked(userId);
1200                    }
1201                }
1202            }
1203        }
1204
1205        @Override
1206        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1207                    ActivityIntentInfo filter, String packageName) {
1208            if (!hasValidDomains(filter)) {
1209                return false;
1210            }
1211            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1212            if (ivs == null) {
1213                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1214                        packageName);
1215            }
1216            if (DEBUG_DOMAIN_VERIFICATION) {
1217                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1218            }
1219            ivs.addFilter(filter);
1220            return true;
1221        }
1222
1223        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1224                int userId, int verificationId, String packageName) {
1225            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1226                    verifierUid, userId, packageName);
1227            ivs.setPendingState();
1228            synchronized (mPackages) {
1229                mIntentFilterVerificationStates.append(verificationId, ivs);
1230                mCurrentIntentFilterVerifications.add(verificationId);
1231            }
1232            return ivs;
1233        }
1234    }
1235
1236    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1237        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1238                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1239                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1240    }
1241
1242    // Set of pending broadcasts for aggregating enable/disable of components.
1243    static class PendingPackageBroadcasts {
1244        // for each user id, a map of <package name -> components within that package>
1245        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1246
1247        public PendingPackageBroadcasts() {
1248            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1249        }
1250
1251        public ArrayList<String> get(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            return packages.get(packageName);
1254        }
1255
1256        public void put(int userId, String packageName, ArrayList<String> components) {
1257            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1258            packages.put(packageName, components);
1259        }
1260
1261        public void remove(int userId, String packageName) {
1262            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1263            if (packages != null) {
1264                packages.remove(packageName);
1265            }
1266        }
1267
1268        public void remove(int userId) {
1269            mUidMap.remove(userId);
1270        }
1271
1272        public int userIdCount() {
1273            return mUidMap.size();
1274        }
1275
1276        public int userIdAt(int n) {
1277            return mUidMap.keyAt(n);
1278        }
1279
1280        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1281            return mUidMap.get(userId);
1282        }
1283
1284        public int size() {
1285            // total number of pending broadcast entries across all userIds
1286            int num = 0;
1287            for (int i = 0; i< mUidMap.size(); i++) {
1288                num += mUidMap.valueAt(i).size();
1289            }
1290            return num;
1291        }
1292
1293        public void clear() {
1294            mUidMap.clear();
1295        }
1296
1297        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1298            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1299            if (map == null) {
1300                map = new ArrayMap<String, ArrayList<String>>();
1301                mUidMap.put(userId, map);
1302            }
1303            return map;
1304        }
1305    }
1306    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1307
1308    // Service Connection to remote media container service to copy
1309    // package uri's from external media onto secure containers
1310    // or internal storage.
1311    private IMediaContainerService mContainerService = null;
1312
1313    static final int SEND_PENDING_BROADCAST = 1;
1314    static final int MCS_BOUND = 3;
1315    static final int END_COPY = 4;
1316    static final int INIT_COPY = 5;
1317    static final int MCS_UNBIND = 6;
1318    static final int START_CLEANING_PACKAGE = 7;
1319    static final int FIND_INSTALL_LOC = 8;
1320    static final int POST_INSTALL = 9;
1321    static final int MCS_RECONNECT = 10;
1322    static final int MCS_GIVE_UP = 11;
1323    static final int WRITE_SETTINGS = 13;
1324    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1325    static final int PACKAGE_VERIFIED = 15;
1326    static final int CHECK_PENDING_VERIFICATION = 16;
1327    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1328    static final int INTENT_FILTER_VERIFIED = 18;
1329    static final int WRITE_PACKAGE_LIST = 19;
1330    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1331    static final int DEF_CONTAINER_BIND = 21;
1332
1333    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1334
1335    // Delay time in millisecs
1336    static final int BROADCAST_DELAY = 10 * 1000;
1337
1338    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1339            2 * 60 * 60 * 1000L; /* two hours */
1340
1341    static UserManagerService sUserManager;
1342
1343    // Stores a list of users whose package restrictions file needs to be updated
1344    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1345
1346    final private DefaultContainerConnection mDefContainerConn =
1347            new DefaultContainerConnection();
1348    class DefaultContainerConnection implements ServiceConnection {
1349        public void onServiceConnected(ComponentName name, IBinder service) {
1350            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1351            final IMediaContainerService imcs = IMediaContainerService.Stub
1352                    .asInterface(Binder.allowBlocking(service));
1353            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1354        }
1355
1356        public void onServiceDisconnected(ComponentName name) {
1357            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1358        }
1359    }
1360
1361    // Recordkeeping of restore-after-install operations that are currently in flight
1362    // between the Package Manager and the Backup Manager
1363    static class PostInstallData {
1364        public InstallArgs args;
1365        public PackageInstalledInfo res;
1366
1367        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368            args = _a;
1369            res = _r;
1370        }
1371    }
1372
1373    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1374    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1375
1376    // XML tags for backup/restore of various bits of state
1377    private static final String TAG_PREFERRED_BACKUP = "pa";
1378    private static final String TAG_DEFAULT_APPS = "da";
1379    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1380
1381    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1382    private static final String TAG_ALL_GRANTS = "rt-grants";
1383    private static final String TAG_GRANT = "grant";
1384    private static final String ATTR_PACKAGE_NAME = "pkg";
1385
1386    private static final String TAG_PERMISSION = "perm";
1387    private static final String ATTR_PERMISSION_NAME = "name";
1388    private static final String ATTR_IS_GRANTED = "g";
1389    private static final String ATTR_USER_SET = "set";
1390    private static final String ATTR_USER_FIXED = "fixed";
1391    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1392
1393    // System/policy permission grants are not backed up
1394    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_POLICY_FIXED
1396            | FLAG_PERMISSION_SYSTEM_FIXED
1397            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1398
1399    // And we back up these user-adjusted states
1400    private static final int USER_RUNTIME_GRANT_MASK =
1401            FLAG_PERMISSION_USER_SET
1402            | FLAG_PERMISSION_USER_FIXED
1403            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1404
1405    final @Nullable String mRequiredVerifierPackage;
1406    final @NonNull String mRequiredInstallerPackage;
1407    final @NonNull String mRequiredUninstallerPackage;
1408    final @Nullable String mSetupWizardPackage;
1409    final @Nullable String mStorageManagerPackage;
1410    final @Nullable String mSystemTextClassifierPackage;
1411    final @NonNull String mServicesSystemSharedLibraryPackageName;
1412    final @NonNull String mSharedSystemSharedLibraryPackageName;
1413
1414    private final PackageUsage mPackageUsage = new PackageUsage();
1415    private final CompilerStats mCompilerStats = new CompilerStats();
1416
1417    class PackageHandler extends Handler {
1418        private boolean mBound = false;
1419        final ArrayList<HandlerParams> mPendingInstalls =
1420            new ArrayList<HandlerParams>();
1421
1422        private boolean connectToService() {
1423            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1424            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1427                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1428                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429                mBound = true;
1430                return true;
1431            }
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            return false;
1434        }
1435
1436        private void disconnectService() {
1437            mContainerService = null;
1438            mBound = false;
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1440            mContext.unbindService(mDefContainerConn);
1441            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1442        }
1443
1444        PackageHandler(Looper looper) {
1445            super(looper);
1446        }
1447
1448        public void handleMessage(Message msg) {
1449            try {
1450                doHandleMessage(msg);
1451            } finally {
1452                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1453            }
1454        }
1455
1456        void doHandleMessage(Message msg) {
1457            switch (msg.what) {
1458                case DEF_CONTAINER_BIND:
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                        }
1465                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1466                                System.identityHashCode(mHandler));
1467                    }
1468                    break;
1469                case INIT_COPY: {
1470                    HandlerParams params = (HandlerParams) msg.obj;
1471                    int idx = mPendingInstalls.size();
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1473                    // If a bind was already initiated we dont really
1474                    // need to do anything. The pending install
1475                    // will be processed later on.
1476                    if (!mBound) {
1477                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                System.identityHashCode(mHandler));
1479                        // If this is the only one pending we might
1480                        // have to bind to the service again.
1481                        if (!connectToService()) {
1482                            Slog.e(TAG, "Failed to bind to media container service");
1483                            params.serviceError();
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1485                                    System.identityHashCode(mHandler));
1486                            if (params.traceMethod != null) {
1487                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1488                                        params.traceCookie);
1489                            }
1490                            return;
1491                        } else {
1492                            // Once we bind to the service, the first
1493                            // pending request will be processed.
1494                            mPendingInstalls.add(idx, params);
1495                        }
1496                    } else {
1497                        mPendingInstalls.add(idx, params);
1498                        // Already bound to the service. Just make
1499                        // sure we trigger off processing the first request.
1500                        if (idx == 0) {
1501                            mHandler.sendEmptyMessage(MCS_BOUND);
1502                        }
1503                    }
1504                    break;
1505                }
1506                case MCS_BOUND: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1508                    if (msg.obj != null) {
1509                        mContainerService = (IMediaContainerService) msg.obj;
1510                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1511                                System.identityHashCode(mHandler));
1512                    }
1513                    if (mContainerService == null) {
1514                        if (!mBound) {
1515                            // Something seriously wrong since we are not bound and we are not
1516                            // waiting for connection. Bail out.
1517                            Slog.e(TAG, "Cannot bind to media container service");
1518                            for (HandlerParams params : mPendingInstalls) {
1519                                // Indicate service bind error
1520                                params.serviceError();
1521                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                        System.identityHashCode(params));
1523                                if (params.traceMethod != null) {
1524                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1525                                            params.traceMethod, params.traceCookie);
1526                                }
1527                            }
1528                            mPendingInstalls.clear();
1529                        } else {
1530                            Slog.w(TAG, "Waiting to connect to media container service");
1531                        }
1532                    } else if (mPendingInstalls.size() > 0) {
1533                        HandlerParams params = mPendingInstalls.get(0);
1534                        if (params != null) {
1535                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1536                                    System.identityHashCode(params));
1537                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1538                            if (params.startCopy()) {
1539                                // We are done...  look for more work or to
1540                                // go idle.
1541                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                        "Checking for more work or unbind...");
1543                                // Delete pending install
1544                                if (mPendingInstalls.size() > 0) {
1545                                    mPendingInstalls.remove(0);
1546                                }
1547                                if (mPendingInstalls.size() == 0) {
1548                                    if (mBound) {
1549                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                                "Posting delayed MCS_UNBIND");
1551                                        removeMessages(MCS_UNBIND);
1552                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1553                                        // Unbind after a little delay, to avoid
1554                                        // continual thrashing.
1555                                        sendMessageDelayed(ubmsg, 10000);
1556                                    }
1557                                } else {
1558                                    // There are more pending requests in queue.
1559                                    // Just post MCS_BOUND message to trigger processing
1560                                    // of next pending install.
1561                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1562                                            "Posting MCS_BOUND for next work");
1563                                    mHandler.sendEmptyMessage(MCS_BOUND);
1564                                }
1565                            }
1566                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1567                        }
1568                    } else {
1569                        // Should never happen ideally.
1570                        Slog.w(TAG, "Empty queue");
1571                    }
1572                    break;
1573                }
1574                case MCS_RECONNECT: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1576                    if (mPendingInstalls.size() > 0) {
1577                        if (mBound) {
1578                            disconnectService();
1579                        }
1580                        if (!connectToService()) {
1581                            Slog.e(TAG, "Failed to bind to media container service");
1582                            for (HandlerParams params : mPendingInstalls) {
1583                                // Indicate service bind error
1584                                params.serviceError();
1585                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                                        System.identityHashCode(params));
1587                            }
1588                            mPendingInstalls.clear();
1589                        }
1590                    }
1591                    break;
1592                }
1593                case MCS_UNBIND: {
1594                    // If there is no actual work left, then time to unbind.
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1596
1597                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1598                        if (mBound) {
1599                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1600
1601                            disconnectService();
1602                        }
1603                    } else if (mPendingInstalls.size() > 0) {
1604                        // There are more pending requests in queue.
1605                        // Just post MCS_BOUND message to trigger processing
1606                        // of next pending install.
1607                        mHandler.sendEmptyMessage(MCS_BOUND);
1608                    }
1609
1610                    break;
1611                }
1612                case MCS_GIVE_UP: {
1613                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1614                    HandlerParams params = mPendingInstalls.remove(0);
1615                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1616                            System.identityHashCode(params));
1617                    break;
1618                }
1619                case SEND_PENDING_BROADCAST: {
1620                    String packages[];
1621                    ArrayList<String> components[];
1622                    int size = 0;
1623                    int uids[];
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625                    synchronized (mPackages) {
1626                        if (mPendingBroadcasts == null) {
1627                            return;
1628                        }
1629                        size = mPendingBroadcasts.size();
1630                        if (size <= 0) {
1631                            // Nothing to be done. Just return
1632                            return;
1633                        }
1634                        packages = new String[size];
1635                        components = new ArrayList[size];
1636                        uids = new int[size];
1637                        int i = 0;  // filling out the above arrays
1638
1639                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1640                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1641                            Iterator<Map.Entry<String, ArrayList<String>>> it
1642                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1643                                            .entrySet().iterator();
1644                            while (it.hasNext() && i < size) {
1645                                Map.Entry<String, ArrayList<String>> ent = it.next();
1646                                packages[i] = ent.getKey();
1647                                components[i] = ent.getValue();
1648                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1649                                uids[i] = (ps != null)
1650                                        ? UserHandle.getUid(packageUserId, ps.appId)
1651                                        : -1;
1652                                i++;
1653                            }
1654                        }
1655                        size = i;
1656                        mPendingBroadcasts.clear();
1657                    }
1658                    // Send broadcasts
1659                    for (int i = 0; i < size; i++) {
1660                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    break;
1664                }
1665                case START_CLEANING_PACKAGE: {
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1667                    final String packageName = (String)msg.obj;
1668                    final int userId = msg.arg1;
1669                    final boolean andCode = msg.arg2 != 0;
1670                    synchronized (mPackages) {
1671                        if (userId == UserHandle.USER_ALL) {
1672                            int[] users = sUserManager.getUserIds();
1673                            for (int user : users) {
1674                                mSettings.addPackageToCleanLPw(
1675                                        new PackageCleanItem(user, packageName, andCode));
1676                            }
1677                        } else {
1678                            mSettings.addPackageToCleanLPw(
1679                                    new PackageCleanItem(userId, packageName, andCode));
1680                        }
1681                    }
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1683                    startCleaningPackages();
1684                } break;
1685                case POST_INSTALL: {
1686                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1687
1688                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1689                    final boolean didRestore = (msg.arg2 != 0);
1690                    mRunningInstalls.delete(msg.arg1);
1691
1692                    if (data != null) {
1693                        InstallArgs args = data.args;
1694                        PackageInstalledInfo parentRes = data.res;
1695
1696                        final boolean grantPermissions = (args.installFlags
1697                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1698                        final boolean killApp = (args.installFlags
1699                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1700                        final boolean virtualPreload = ((args.installFlags
1701                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1702                        final String[] grantedPermissions = args.installGrantPermissions;
1703
1704                        // Handle the parent package
1705                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1706                                virtualPreload, grantedPermissions, didRestore,
1707                                args.installerPackageName, args.observer);
1708
1709                        // Handle the child packages
1710                        final int childCount = (parentRes.addedChildPackages != null)
1711                                ? parentRes.addedChildPackages.size() : 0;
1712                        for (int i = 0; i < childCount; i++) {
1713                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1714                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1715                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1716                                    args.installerPackageName, args.observer);
1717                        }
1718
1719                        // Log tracing if needed
1720                        if (args.traceMethod != null) {
1721                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1722                                    args.traceCookie);
1723                        }
1724                    } else {
1725                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1726                    }
1727
1728                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1729                } break;
1730                case WRITE_SETTINGS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_SETTINGS);
1734                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1735                        mSettings.writeLPr();
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_RESTRICTIONS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1744                        for (int userId : mDirtyUsers) {
1745                            mSettings.writePackageRestrictionsLPr(userId);
1746                        }
1747                        mDirtyUsers.clear();
1748                    }
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1750                } break;
1751                case WRITE_PACKAGE_LIST: {
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1753                    synchronized (mPackages) {
1754                        removeMessages(WRITE_PACKAGE_LIST);
1755                        mSettings.writePackageListLPr(msg.arg1);
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case CHECK_PENDING_VERIFICATION: {
1760                    final int verificationId = msg.arg1;
1761                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1762
1763                    if ((state != null) && !state.timeoutExtended()) {
1764                        final InstallArgs args = state.getInstallArgs();
1765                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1766
1767                        Slog.i(TAG, "Verification timed out for " + originUri);
1768                        mPendingVerification.remove(verificationId);
1769
1770                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1771
1772                        final UserHandle user = args.getUser();
1773                        if (getDefaultVerificationResponse(user)
1774                                == PackageManager.VERIFICATION_ALLOW) {
1775                            Slog.i(TAG, "Continuing with installation of " + originUri);
1776                            state.setVerifierResponse(Binder.getCallingUid(),
1777                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1778                            broadcastPackageVerified(verificationId, originUri,
1779                                    PackageManager.VERIFICATION_ALLOW, user);
1780                            try {
1781                                ret = args.copyApk(mContainerService, true);
1782                            } catch (RemoteException e) {
1783                                Slog.e(TAG, "Could not contact the ContainerService");
1784                            }
1785                        } else {
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_REJECT, user);
1788                        }
1789
1790                        Trace.asyncTraceEnd(
1791                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1792
1793                        processPendingInstall(args, ret);
1794                        mHandler.sendEmptyMessage(MCS_UNBIND);
1795                    }
1796                    break;
1797                }
1798                case PACKAGE_VERIFIED: {
1799                    final int verificationId = msg.arg1;
1800
1801                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1802                    if (state == null) {
1803                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1804                        break;
1805                    }
1806
1807                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1808
1809                    state.setVerifierResponse(response.callerUid, response.code);
1810
1811                    if (state.isVerificationComplete()) {
1812                        mPendingVerification.remove(verificationId);
1813
1814                        final InstallArgs args = state.getInstallArgs();
1815                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1816
1817                        int ret;
1818                        if (state.isInstallAllowed()) {
1819                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1820                            broadcastPackageVerified(verificationId, originUri,
1821                                    response.code, state.getInstallArgs().getUser());
1822                            try {
1823                                ret = args.copyApk(mContainerService, true);
1824                            } catch (RemoteException e) {
1825                                Slog.e(TAG, "Could not contact the ContainerService");
1826                            }
1827                        } else {
1828                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1829                        }
1830
1831                        Trace.asyncTraceEnd(
1832                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1833
1834                        processPendingInstall(args, ret);
1835                        mHandler.sendEmptyMessage(MCS_UNBIND);
1836                    }
1837
1838                    break;
1839                }
1840                case START_INTENT_FILTER_VERIFICATIONS: {
1841                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1842                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1843                            params.replacing, params.pkg);
1844                    break;
1845                }
1846                case INTENT_FILTER_VERIFIED: {
1847                    final int verificationId = msg.arg1;
1848
1849                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1850                            verificationId);
1851                    if (state == null) {
1852                        Slog.w(TAG, "Invalid IntentFilter verification token "
1853                                + verificationId + " received");
1854                        break;
1855                    }
1856
1857                    final int userId = state.getUserId();
1858
1859                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                            "Processing IntentFilter verification with token:"
1861                            + verificationId + " and userId:" + userId);
1862
1863                    final IntentFilterVerificationResponse response =
1864                            (IntentFilterVerificationResponse) msg.obj;
1865
1866                    state.setVerifierResponse(response.callerUid, response.code);
1867
1868                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                            "IntentFilter verification with token:" + verificationId
1870                            + " and userId:" + userId
1871                            + " is settings verifier response with response code:"
1872                            + response.code);
1873
1874                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1876                                + response.getFailedDomainsString());
1877                    }
1878
1879                    if (state.isVerificationComplete()) {
1880                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1881                    } else {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                                "IntentFilter verification with token:" + verificationId
1884                                + " was not said to be complete");
1885                    }
1886
1887                    break;
1888                }
1889                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1890                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1891                            mInstantAppResolverConnection,
1892                            (InstantAppRequest) msg.obj,
1893                            mInstantAppInstallerActivity,
1894                            mHandler);
1895                }
1896            }
1897        }
1898    }
1899
1900    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1901        @Override
1902        public void onGidsChanged(int appId, int userId) {
1903            mHandler.post(new Runnable() {
1904                @Override
1905                public void run() {
1906                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1907                }
1908            });
1909        }
1910        @Override
1911        public void onPermissionGranted(int uid, int userId) {
1912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1913
1914            // Not critical; if this is lost, the application has to request again.
1915            synchronized (mPackages) {
1916                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1917            }
1918        }
1919        @Override
1920        public void onInstallPermissionGranted() {
1921            synchronized (mPackages) {
1922                scheduleWriteSettingsLocked();
1923            }
1924        }
1925        @Override
1926        public void onPermissionRevoked(int uid, int userId) {
1927            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1928
1929            synchronized (mPackages) {
1930                // Critical; after this call the application should never have the permission
1931                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1932            }
1933
1934            final int appId = UserHandle.getAppId(uid);
1935            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1936        }
1937        @Override
1938        public void onInstallPermissionRevoked() {
1939            synchronized (mPackages) {
1940                scheduleWriteSettingsLocked();
1941            }
1942        }
1943        @Override
1944        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1945            synchronized (mPackages) {
1946                for (int userId : updatedUserIds) {
1947                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1948                }
1949            }
1950        }
1951        @Override
1952        public void onInstallPermissionUpdated() {
1953            synchronized (mPackages) {
1954                scheduleWriteSettingsLocked();
1955            }
1956        }
1957        @Override
1958        public void onPermissionRemoved() {
1959            synchronized (mPackages) {
1960                mSettings.writeLPr();
1961            }
1962        }
1963    };
1964
1965    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1966            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1967            boolean launchedForRestore, String installerPackage,
1968            IPackageInstallObserver2 installObserver) {
1969        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1970            // Send the removed broadcasts
1971            if (res.removedInfo != null) {
1972                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1973            }
1974
1975            // Now that we successfully installed the package, grant runtime
1976            // permissions if requested before broadcasting the install. Also
1977            // for legacy apps in permission review mode we clear the permission
1978            // review flag which is used to emulate runtime permissions for
1979            // legacy apps.
1980            if (grantPermissions) {
1981                final int callingUid = Binder.getCallingUid();
1982                mPermissionManager.grantRequestedRuntimePermissions(
1983                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1984                        mPermissionCallback);
1985            }
1986
1987            final boolean update = res.removedInfo != null
1988                    && res.removedInfo.removedPackage != null;
1989            final String installerPackageName =
1990                    res.installerPackageName != null
1991                            ? res.installerPackageName
1992                            : res.removedInfo != null
1993                                    ? res.removedInfo.installerPackageName
1994                                    : null;
1995
1996            // If this is the first time we have child packages for a disabled privileged
1997            // app that had no children, we grant requested runtime permissions to the new
1998            // children if the parent on the system image had them already granted.
1999            if (res.pkg.parentPackage != null) {
2000                final int callingUid = Binder.getCallingUid();
2001                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2002                        res.pkg, callingUid, mPermissionCallback);
2003            }
2004
2005            synchronized (mPackages) {
2006                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2007            }
2008
2009            final String packageName = res.pkg.applicationInfo.packageName;
2010
2011            // Determine the set of users who are adding this package for
2012            // the first time vs. those who are seeing an update.
2013            int[] firstUserIds = EMPTY_INT_ARRAY;
2014            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2015            int[] updateUserIds = EMPTY_INT_ARRAY;
2016            int[] instantUserIds = EMPTY_INT_ARRAY;
2017            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2018            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2019            for (int newUser : res.newUsers) {
2020                final boolean isInstantApp = ps.getInstantApp(newUser);
2021                if (allNewUsers) {
2022                    if (isInstantApp) {
2023                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2024                    } else {
2025                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2026                    }
2027                    continue;
2028                }
2029                boolean isNew = true;
2030                for (int origUser : res.origUsers) {
2031                    if (origUser == newUser) {
2032                        isNew = false;
2033                        break;
2034                    }
2035                }
2036                if (isNew) {
2037                    if (isInstantApp) {
2038                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2039                    } else {
2040                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2041                    }
2042                } else {
2043                    if (isInstantApp) {
2044                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2045                    } else {
2046                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2047                    }
2048                }
2049            }
2050
2051            // Send installed broadcasts if the package is not a static shared lib.
2052            if (res.pkg.staticSharedLibName == null) {
2053                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2054
2055                // Send added for users that see the package for the first time
2056                // sendPackageAddedForNewUsers also deals with system apps
2057                int appId = UserHandle.getAppId(res.uid);
2058                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2059                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2060                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2061
2062                // Send added for users that don't see the package for the first time
2063                Bundle extras = new Bundle(1);
2064                extras.putInt(Intent.EXTRA_UID, res.uid);
2065                if (update) {
2066                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2067                }
2068                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2069                        extras, 0 /*flags*/,
2070                        null /*targetPackage*/, null /*finishedReceiver*/,
2071                        updateUserIds, instantUserIds);
2072                if (installerPackageName != null) {
2073                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2074                            extras, 0 /*flags*/,
2075                            installerPackageName, null /*finishedReceiver*/,
2076                            updateUserIds, instantUserIds);
2077                }
2078
2079                // Send replaced for users that don't see the package for the first time
2080                if (update) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2082                            packageName, extras, 0 /*flags*/,
2083                            null /*targetPackage*/, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                    if (installerPackageName != null) {
2086                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2087                                extras, 0 /*flags*/,
2088                                installerPackageName, null /*finishedReceiver*/,
2089                                updateUserIds, instantUserIds);
2090                    }
2091                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2092                            null /*package*/, null /*extras*/, 0 /*flags*/,
2093                            packageName /*targetPackage*/,
2094                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2095                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2096                    // First-install and we did a restore, so we're responsible for the
2097                    // first-launch broadcast.
2098                    if (DEBUG_BACKUP) {
2099                        Slog.i(TAG, "Post-restore of " + packageName
2100                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2101                    }
2102                    sendFirstLaunchBroadcast(packageName, installerPackage,
2103                            firstUserIds, firstInstantUserIds);
2104                }
2105
2106                // Send broadcast package appeared if forward locked/external for all users
2107                // treat asec-hosted packages like removable media on upgrade
2108                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2109                    if (DEBUG_INSTALL) {
2110                        Slog.i(TAG, "upgrading pkg " + res.pkg
2111                                + " is ASEC-hosted -> AVAILABLE");
2112                    }
2113                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2114                    ArrayList<String> pkgList = new ArrayList<>(1);
2115                    pkgList.add(packageName);
2116                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2117                }
2118            }
2119
2120            // Work that needs to happen on first install within each user
2121            if (firstUserIds != null && firstUserIds.length > 0) {
2122                synchronized (mPackages) {
2123                    for (int userId : firstUserIds) {
2124                        // If this app is a browser and it's newly-installed for some
2125                        // users, clear any default-browser state in those users. The
2126                        // app's nature doesn't depend on the user, so we can just check
2127                        // its browser nature in any user and generalize.
2128                        if (packageIsBrowser(packageName, userId)) {
2129                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2130                        }
2131
2132                        // We may also need to apply pending (restored) runtime
2133                        // permission grants within these users.
2134                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2135                    }
2136                }
2137            }
2138
2139            if (allNewUsers && !update) {
2140                notifyPackageAdded(packageName);
2141            }
2142
2143            // Log current value of "unknown sources" setting
2144            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2145                    getUnknownSourcesSettings());
2146
2147            // Remove the replaced package's older resources safely now
2148            // We delete after a gc for applications  on sdcard.
2149            if (res.removedInfo != null && res.removedInfo.args != null) {
2150                Runtime.getRuntime().gc();
2151                synchronized (mInstallLock) {
2152                    res.removedInfo.args.doPostDeleteLI(true);
2153                }
2154            } else {
2155                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2156                // and not block here.
2157                VMRuntime.getRuntime().requestConcurrentGC();
2158            }
2159
2160            // Notify DexManager that the package was installed for new users.
2161            // The updated users should already be indexed and the package code paths
2162            // should not change.
2163            // Don't notify the manager for ephemeral apps as they are not expected to
2164            // survive long enough to benefit of background optimizations.
2165            for (int userId : firstUserIds) {
2166                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2167                // There's a race currently where some install events may interleave with an uninstall.
2168                // This can lead to package info being null (b/36642664).
2169                if (info != null) {
2170                    mDexManager.notifyPackageInstalled(info, userId);
2171                }
2172            }
2173        }
2174
2175        // If someone is watching installs - notify them
2176        if (installObserver != null) {
2177            try {
2178                Bundle extras = extrasForInstallResult(res);
2179                installObserver.onPackageInstalled(res.name, res.returnCode,
2180                        res.returnMsg, extras);
2181            } catch (RemoteException e) {
2182                Slog.i(TAG, "Observer no longer exists.");
2183            }
2184        }
2185    }
2186
2187    private StorageEventListener mStorageListener = new StorageEventListener() {
2188        @Override
2189        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2190            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2191                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2192                    final String volumeUuid = vol.getFsUuid();
2193
2194                    // Clean up any users or apps that were removed or recreated
2195                    // while this volume was missing
2196                    sUserManager.reconcileUsers(volumeUuid);
2197                    reconcileApps(volumeUuid);
2198
2199                    // Clean up any install sessions that expired or were
2200                    // cancelled while this volume was missing
2201                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2202
2203                    loadPrivatePackages(vol);
2204
2205                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2206                    unloadPrivatePackages(vol);
2207                }
2208            }
2209        }
2210
2211        @Override
2212        public void onVolumeForgotten(String fsUuid) {
2213            if (TextUtils.isEmpty(fsUuid)) {
2214                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2215                return;
2216            }
2217
2218            // Remove any apps installed on the forgotten volume
2219            synchronized (mPackages) {
2220                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2221                for (PackageSetting ps : packages) {
2222                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2223                    deletePackageVersioned(new VersionedPackage(ps.name,
2224                            PackageManager.VERSION_CODE_HIGHEST),
2225                            new LegacyPackageDeleteObserver(null).getBinder(),
2226                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2227                    // Try very hard to release any references to this package
2228                    // so we don't risk the system server being killed due to
2229                    // open FDs
2230                    AttributeCache.instance().removePackage(ps.name);
2231                }
2232
2233                mSettings.onVolumeForgotten(fsUuid);
2234                mSettings.writeLPr();
2235            }
2236        }
2237    };
2238
2239    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2240        Bundle extras = null;
2241        switch (res.returnCode) {
2242            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2243                extras = new Bundle();
2244                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2245                        res.origPermission);
2246                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2247                        res.origPackage);
2248                break;
2249            }
2250            case PackageManager.INSTALL_SUCCEEDED: {
2251                extras = new Bundle();
2252                extras.putBoolean(Intent.EXTRA_REPLACING,
2253                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2254                break;
2255            }
2256        }
2257        return extras;
2258    }
2259
2260    void scheduleWriteSettingsLocked() {
2261        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2262            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2263        }
2264    }
2265
2266    void scheduleWritePackageListLocked(int userId) {
2267        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2268            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2269            msg.arg1 = userId;
2270            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2275        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2276        scheduleWritePackageRestrictionsLocked(userId);
2277    }
2278
2279    void scheduleWritePackageRestrictionsLocked(int userId) {
2280        final int[] userIds = (userId == UserHandle.USER_ALL)
2281                ? sUserManager.getUserIds() : new int[]{userId};
2282        for (int nextUserId : userIds) {
2283            if (!sUserManager.exists(nextUserId)) return;
2284            mDirtyUsers.add(nextUserId);
2285            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2286                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2287            }
2288        }
2289    }
2290
2291    public static PackageManagerService main(Context context, Installer installer,
2292            boolean factoryTest, boolean onlyCore) {
2293        // Self-check for initial settings.
2294        PackageManagerServiceCompilerMapping.checkProperties();
2295
2296        PackageManagerService m = new PackageManagerService(context, installer,
2297                factoryTest, onlyCore);
2298        m.enableSystemUserPackages();
2299        ServiceManager.addService("package", m);
2300        final PackageManagerNative pmn = m.new PackageManagerNative();
2301        ServiceManager.addService("package_native", pmn);
2302        return m;
2303    }
2304
2305    private void enableSystemUserPackages() {
2306        if (!UserManager.isSplitSystemUser()) {
2307            return;
2308        }
2309        // For system user, enable apps based on the following conditions:
2310        // - app is whitelisted or belong to one of these groups:
2311        //   -- system app which has no launcher icons
2312        //   -- system app which has INTERACT_ACROSS_USERS permission
2313        //   -- system IME app
2314        // - app is not in the blacklist
2315        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2316        Set<String> enableApps = new ArraySet<>();
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2318                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2319                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2320        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2321        enableApps.addAll(wlApps);
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2323                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2324        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2325        enableApps.removeAll(blApps);
2326        Log.i(TAG, "Applications installed for system user: " + enableApps);
2327        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2328                UserHandle.SYSTEM);
2329        final int allAppsSize = allAps.size();
2330        synchronized (mPackages) {
2331            for (int i = 0; i < allAppsSize; i++) {
2332                String pName = allAps.get(i);
2333                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2334                // Should not happen, but we shouldn't be failing if it does
2335                if (pkgSetting == null) {
2336                    continue;
2337                }
2338                boolean install = enableApps.contains(pName);
2339                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2340                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2341                            + " for system user");
2342                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2343                }
2344            }
2345            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2346        }
2347    }
2348
2349    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2350        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2351                Context.DISPLAY_SERVICE);
2352        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2353    }
2354
2355    /**
2356     * Requests that files preopted on a secondary system partition be copied to the data partition
2357     * if possible.  Note that the actual copying of the files is accomplished by init for security
2358     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2359     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2360     */
2361    private static void requestCopyPreoptedFiles() {
2362        final int WAIT_TIME_MS = 100;
2363        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2364        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2365            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2366            // We will wait for up to 100 seconds.
2367            final long timeStart = SystemClock.uptimeMillis();
2368            final long timeEnd = timeStart + 100 * 1000;
2369            long timeNow = timeStart;
2370            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2371                try {
2372                    Thread.sleep(WAIT_TIME_MS);
2373                } catch (InterruptedException e) {
2374                    // Do nothing
2375                }
2376                timeNow = SystemClock.uptimeMillis();
2377                if (timeNow > timeEnd) {
2378                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2379                    Slog.wtf(TAG, "cppreopt did not finish!");
2380                    break;
2381                }
2382            }
2383
2384            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2385        }
2386    }
2387
2388    public PackageManagerService(Context context, Installer installer,
2389            boolean factoryTest, boolean onlyCore) {
2390        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2392        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2393                SystemClock.uptimeMillis());
2394
2395        if (mSdkVersion <= 0) {
2396            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2397        }
2398
2399        mContext = context;
2400
2401        mFactoryTest = factoryTest;
2402        mOnlyCore = onlyCore;
2403        mMetrics = new DisplayMetrics();
2404        mInstaller = installer;
2405
2406        // Create sub-components that provide services / data. Order here is important.
2407        synchronized (mInstallLock) {
2408        synchronized (mPackages) {
2409            // Expose private service for system components to use.
2410            LocalServices.addService(
2411                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2412            sUserManager = new UserManagerService(context, this,
2413                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2414            mPermissionManager = PermissionManagerService.create(context,
2415                    new DefaultPermissionGrantedCallback() {
2416                        @Override
2417                        public void onDefaultRuntimePermissionsGranted(int userId) {
2418                            synchronized(mPackages) {
2419                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2420                            }
2421                        }
2422                    }, mPackages /*externalLock*/);
2423            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2424            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2425        }
2426        }
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441
2442        String separateProcesses = SystemProperties.get("debug.separate_processes");
2443        if (separateProcesses != null && separateProcesses.length() > 0) {
2444            if ("*".equals(separateProcesses)) {
2445                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2446                mSeparateProcesses = null;
2447                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2448            } else {
2449                mDefParseFlags = 0;
2450                mSeparateProcesses = separateProcesses.split(",");
2451                Slog.w(TAG, "Running with debug.separate_processes: "
2452                        + separateProcesses);
2453            }
2454        } else {
2455            mDefParseFlags = 0;
2456            mSeparateProcesses = null;
2457        }
2458
2459        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2460                "*dexopt*");
2461        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2462                installer, mInstallLock);
2463        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2464                dexManagerListener);
2465        mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2466        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2467
2468        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2469                FgThread.get().getLooper());
2470
2471        getDefaultDisplayMetrics(context, mMetrics);
2472
2473        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        mAvailableFeatures = systemConfig.getAvailableFeatures();
2476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478        mProtectedPackages = new ProtectedPackages(mContext);
2479
2480        synchronized (mInstallLock) {
2481        // writer
2482        synchronized (mPackages) {
2483            mHandlerThread = new ServiceThread(TAG,
2484                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2485            mHandlerThread.start();
2486            mHandler = new PackageHandler(mHandlerThread.getLooper());
2487            mProcessLoggingHandler = new ProcessLoggingHandler();
2488            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2489            mInstantAppRegistry = new InstantAppRegistry(this);
2490
2491            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2492            final int builtInLibCount = libConfig.size();
2493            for (int i = 0; i < builtInLibCount; i++) {
2494                String name = libConfig.keyAt(i);
2495                String path = libConfig.valueAt(i);
2496                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2497                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2498            }
2499
2500            SELinuxMMAC.readInstallPolicy();
2501
2502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2503            FallbackCategoryProvider.loadFallbacks();
2504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2505
2506            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2507            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2509
2510            // Clean up orphaned packages for which the code path doesn't exist
2511            // and they are an update to a system app - caused by bug/32321269
2512            final int packageSettingCount = mSettings.mPackages.size();
2513            for (int i = packageSettingCount - 1; i >= 0; i--) {
2514                PackageSetting ps = mSettings.mPackages.valueAt(i);
2515                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2516                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2517                    mSettings.mPackages.removeAt(i);
2518                    mSettings.enableSystemPackageLPw(ps.name);
2519                }
2520            }
2521
2522            if (mFirstBoot) {
2523                requestCopyPreoptedFiles();
2524            }
2525
2526            String customResolverActivity = Resources.getSystem().getString(
2527                    R.string.config_customResolverActivity);
2528            if (TextUtils.isEmpty(customResolverActivity)) {
2529                customResolverActivity = null;
2530            } else {
2531                mCustomResolverComponentName = ComponentName.unflattenFromString(
2532                        customResolverActivity);
2533            }
2534
2535            long startTime = SystemClock.uptimeMillis();
2536
2537            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2538                    startTime);
2539
2540            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2541            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2542
2543            if (bootClassPath == null) {
2544                Slog.w(TAG, "No BOOTCLASSPATH found!");
2545            }
2546
2547            if (systemServerClassPath == null) {
2548                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2549            }
2550
2551            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2552
2553            final VersionInfo ver = mSettings.getInternalVersion();
2554            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2555            if (mIsUpgrade) {
2556                logCriticalInfo(Log.INFO,
2557                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2558            }
2559
2560            // when upgrading from pre-M, promote system app permissions from install to runtime
2561            mPromoteSystemApps =
2562                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2563
2564            // When upgrading from pre-N, we need to handle package extraction like first boot,
2565            // as there is no profiling data available.
2566            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2567
2568            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2569
2570            // save off the names of pre-existing system packages prior to scanning; we don't
2571            // want to automatically grant runtime permissions for new system apps
2572            if (mPromoteSystemApps) {
2573                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2574                while (pkgSettingIter.hasNext()) {
2575                    PackageSetting ps = pkgSettingIter.next();
2576                    if (isSystemApp(ps)) {
2577                        mExistingSystemPackages.add(ps.name);
2578                    }
2579                }
2580            }
2581
2582            mCacheDir = preparePackageParserCache(mIsUpgrade);
2583
2584            // Set flag to monitor and not change apk file paths when
2585            // scanning install directories.
2586            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2587
2588            if (mIsUpgrade || mFirstBoot) {
2589                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2590            }
2591
2592            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2593            // For security and version matching reason, only consider
2594            // overlay packages if they reside in the right directory.
2595            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2596                    mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2598                    scanFlags
2599                    | SCAN_AS_SYSTEM
2600                    | SCAN_AS_VENDOR,
2601                    0);
2602            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2603                    mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2605                    scanFlags
2606                    | SCAN_AS_SYSTEM
2607                    | SCAN_AS_PRODUCT,
2608                    0);
2609
2610            mParallelPackageParserCallback.findStaticOverlayPackages();
2611
2612            // Find base frameworks (resource packages without code).
2613            scanDirTracedLI(frameworkDir,
2614                    mDefParseFlags
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2616                    scanFlags
2617                    | SCAN_NO_DEX
2618                    | SCAN_AS_SYSTEM
2619                    | SCAN_AS_PRIVILEGED,
2620                    0);
2621
2622            // Collect privileged system packages.
2623            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2624            scanDirTracedLI(privilegedAppDir,
2625                    mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2627                    scanFlags
2628                    | SCAN_AS_SYSTEM
2629                    | SCAN_AS_PRIVILEGED,
2630                    0);
2631
2632            // Collect ordinary system packages.
2633            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2634            scanDirTracedLI(systemAppDir,
2635                    mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2637                    scanFlags
2638                    | SCAN_AS_SYSTEM,
2639                    0);
2640
2641            // Collect privileged vendor packages.
2642            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2643            try {
2644                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2645            } catch (IOException e) {
2646                // failed to look up canonical path, continue with original one
2647            }
2648            scanDirTracedLI(privilegedVendorAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM
2653                    | SCAN_AS_VENDOR
2654                    | SCAN_AS_PRIVILEGED,
2655                    0);
2656
2657            // Collect ordinary vendor packages.
2658            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2659            try {
2660                vendorAppDir = vendorAppDir.getCanonicalFile();
2661            } catch (IOException e) {
2662                // failed to look up canonical path, continue with original one
2663            }
2664            scanDirTracedLI(vendorAppDir,
2665                    mDefParseFlags
2666                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2667                    scanFlags
2668                    | SCAN_AS_SYSTEM
2669                    | SCAN_AS_VENDOR,
2670                    0);
2671
2672            // Collect privileged odm packages. /odm is another vendor partition
2673            // other than /vendor.
2674            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2675                        "priv-app");
2676            try {
2677                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2678            } catch (IOException e) {
2679                // failed to look up canonical path, continue with original one
2680            }
2681            scanDirTracedLI(privilegedOdmAppDir,
2682                    mDefParseFlags
2683                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2684                    scanFlags
2685                    | SCAN_AS_SYSTEM
2686                    | SCAN_AS_VENDOR
2687                    | SCAN_AS_PRIVILEGED,
2688                    0);
2689
2690            // Collect ordinary odm packages. /odm is another vendor partition
2691            // other than /vendor.
2692            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2693            try {
2694                odmAppDir = odmAppDir.getCanonicalFile();
2695            } catch (IOException e) {
2696                // failed to look up canonical path, continue with original one
2697            }
2698            scanDirTracedLI(odmAppDir,
2699                    mDefParseFlags
2700                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2701                    scanFlags
2702                    | SCAN_AS_SYSTEM
2703                    | SCAN_AS_VENDOR,
2704                    0);
2705
2706            // Collect all OEM packages.
2707            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2708            scanDirTracedLI(oemAppDir,
2709                    mDefParseFlags
2710                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2711                    scanFlags
2712                    | SCAN_AS_SYSTEM
2713                    | SCAN_AS_OEM,
2714                    0);
2715
2716            // Collected privileged product packages.
2717            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2718            try {
2719                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2720            } catch (IOException e) {
2721                // failed to look up canonical path, continue with original one
2722            }
2723            scanDirTracedLI(privilegedProductAppDir,
2724                    mDefParseFlags
2725                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2726                    scanFlags
2727                    | SCAN_AS_SYSTEM
2728                    | SCAN_AS_PRODUCT
2729                    | SCAN_AS_PRIVILEGED,
2730                    0);
2731
2732            // Collect ordinary product packages.
2733            File productAppDir = new File(Environment.getProductDirectory(), "app");
2734            try {
2735                productAppDir = productAppDir.getCanonicalFile();
2736            } catch (IOException e) {
2737                // failed to look up canonical path, continue with original one
2738            }
2739            scanDirTracedLI(productAppDir,
2740                    mDefParseFlags
2741                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2742                    scanFlags
2743                    | SCAN_AS_SYSTEM
2744                    | SCAN_AS_PRODUCT,
2745                    0);
2746
2747            // Prune any system packages that no longer exist.
2748            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2749            // Stub packages must either be replaced with full versions in the /data
2750            // partition or be disabled.
2751            final List<String> stubSystemApps = new ArrayList<>();
2752            if (!mOnlyCore) {
2753                // do this first before mucking with mPackages for the "expecting better" case
2754                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2755                while (pkgIterator.hasNext()) {
2756                    final PackageParser.Package pkg = pkgIterator.next();
2757                    if (pkg.isStub) {
2758                        stubSystemApps.add(pkg.packageName);
2759                    }
2760                }
2761
2762                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2763                while (psit.hasNext()) {
2764                    PackageSetting ps = psit.next();
2765
2766                    /*
2767                     * If this is not a system app, it can't be a
2768                     * disable system app.
2769                     */
2770                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2771                        continue;
2772                    }
2773
2774                    /*
2775                     * If the package is scanned, it's not erased.
2776                     */
2777                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2778                    if (scannedPkg != null) {
2779                        /*
2780                         * If the system app is both scanned and in the
2781                         * disabled packages list, then it must have been
2782                         * added via OTA. Remove it from the currently
2783                         * scanned package so the previously user-installed
2784                         * application can be scanned.
2785                         */
2786                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2787                            logCriticalInfo(Log.WARN,
2788                                    "Expecting better updated system app for " + ps.name
2789                                    + "; removing system app.  Last known"
2790                                    + " codePath=" + ps.codePathString
2791                                    + ", versionCode=" + ps.versionCode
2792                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2793                            removePackageLI(scannedPkg, true);
2794                            mExpectingBetter.put(ps.name, ps.codePath);
2795                        }
2796
2797                        continue;
2798                    }
2799
2800                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2801                        psit.remove();
2802                        logCriticalInfo(Log.WARN, "System package " + ps.name
2803                                + " no longer exists; it's data will be wiped");
2804                        // Actual deletion of code and data will be handled by later
2805                        // reconciliation step
2806                    } else {
2807                        // we still have a disabled system package, but, it still might have
2808                        // been removed. check the code path still exists and check there's
2809                        // still a package. the latter can happen if an OTA keeps the same
2810                        // code path, but, changes the package name.
2811                        final PackageSetting disabledPs =
2812                                mSettings.getDisabledSystemPkgLPr(ps.name);
2813                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2814                                || disabledPs.pkg == null) {
2815                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2816                        }
2817                    }
2818                }
2819            }
2820
2821            //delete tmp files
2822            deleteTempPackageFiles();
2823
2824            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2825
2826            // Remove any shared userIDs that have no associated packages
2827            mSettings.pruneSharedUsersLPw();
2828            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2829            final int systemPackagesCount = mPackages.size();
2830            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2831                    + " ms, packageCount: " + systemPackagesCount
2832                    + " , timePerPackage: "
2833                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2834                    + " , cached: " + cachedSystemApps);
2835            if (mIsUpgrade && systemPackagesCount > 0) {
2836                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2837                        ((int) systemScanTime) / systemPackagesCount);
2838            }
2839            if (!mOnlyCore) {
2840                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2841                        SystemClock.uptimeMillis());
2842                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2843
2844                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2845                        | PackageParser.PARSE_FORWARD_LOCK,
2846                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2847
2848                // Remove disable package settings for updated system apps that were
2849                // removed via an OTA. If the update is no longer present, remove the
2850                // app completely. Otherwise, revoke their system privileges.
2851                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2852                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2853                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2854                    final String msg;
2855                    if (deletedPkg == null) {
2856                        // should have found an update, but, we didn't; remove everything
2857                        msg = "Updated system package " + deletedAppName
2858                                + " no longer exists; removing its data";
2859                        // Actual deletion of code and data will be handled by later
2860                        // reconciliation step
2861                    } else {
2862                        // found an update; revoke system privileges
2863                        msg = "Updated system package + " + deletedAppName
2864                                + " no longer exists; revoking system privileges";
2865
2866                        // Don't do anything if a stub is removed from the system image. If
2867                        // we were to remove the uncompressed version from the /data partition,
2868                        // this is where it'd be done.
2869
2870                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2871                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2872                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2873                    }
2874                    logCriticalInfo(Log.WARN, msg);
2875                }
2876
2877                /*
2878                 * Make sure all system apps that we expected to appear on
2879                 * the userdata partition actually showed up. If they never
2880                 * appeared, crawl back and revive the system version.
2881                 */
2882                for (int i = 0; i < mExpectingBetter.size(); i++) {
2883                    final String packageName = mExpectingBetter.keyAt(i);
2884                    if (!mPackages.containsKey(packageName)) {
2885                        final File scanFile = mExpectingBetter.valueAt(i);
2886
2887                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2888                                + " but never showed up; reverting to system");
2889
2890                        final @ParseFlags int reparseFlags;
2891                        final @ScanFlags int rescanFlags;
2892                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2893                            reparseFlags =
2894                                    mDefParseFlags |
2895                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2896                            rescanFlags =
2897                                    scanFlags
2898                                    | SCAN_AS_SYSTEM
2899                                    | SCAN_AS_PRIVILEGED;
2900                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2901                            reparseFlags =
2902                                    mDefParseFlags |
2903                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2904                            rescanFlags =
2905                                    scanFlags
2906                                    | SCAN_AS_SYSTEM;
2907                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2908                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2909                            reparseFlags =
2910                                    mDefParseFlags |
2911                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2912                            rescanFlags =
2913                                    scanFlags
2914                                    | SCAN_AS_SYSTEM
2915                                    | SCAN_AS_VENDOR
2916                                    | SCAN_AS_PRIVILEGED;
2917                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2918                                || FileUtils.contains(odmAppDir, scanFile)) {
2919                            reparseFlags =
2920                                    mDefParseFlags |
2921                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2922                            rescanFlags =
2923                                    scanFlags
2924                                    | SCAN_AS_SYSTEM
2925                                    | SCAN_AS_VENDOR;
2926                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2927                            reparseFlags =
2928                                    mDefParseFlags |
2929                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2930                            rescanFlags =
2931                                    scanFlags
2932                                    | SCAN_AS_SYSTEM
2933                                    | SCAN_AS_OEM;
2934                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2935                            reparseFlags =
2936                                    mDefParseFlags |
2937                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2938                            rescanFlags =
2939                                    scanFlags
2940                                    | SCAN_AS_SYSTEM
2941                                    | SCAN_AS_PRODUCT
2942                                    | SCAN_AS_PRIVILEGED;
2943                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2944                            reparseFlags =
2945                                    mDefParseFlags |
2946                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2947                            rescanFlags =
2948                                    scanFlags
2949                                    | SCAN_AS_SYSTEM
2950                                    | SCAN_AS_PRODUCT;
2951                        } else {
2952                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2953                            continue;
2954                        }
2955
2956                        mSettings.enableSystemPackageLPw(packageName);
2957
2958                        try {
2959                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2960                        } catch (PackageManagerException e) {
2961                            Slog.e(TAG, "Failed to parse original system package: "
2962                                    + e.getMessage());
2963                        }
2964                    }
2965                }
2966
2967                // Uncompress and install any stubbed system applications.
2968                // This must be done last to ensure all stubs are replaced or disabled.
2969                decompressSystemApplications(stubSystemApps, scanFlags);
2970
2971                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2972                                - cachedSystemApps;
2973
2974                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2975                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2976                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2977                        + " ms, packageCount: " + dataPackagesCount
2978                        + " , timePerPackage: "
2979                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2980                        + " , cached: " + cachedNonSystemApps);
2981                if (mIsUpgrade && dataPackagesCount > 0) {
2982                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2983                            ((int) dataScanTime) / dataPackagesCount);
2984                }
2985            }
2986            mExpectingBetter.clear();
2987
2988            // Resolve the storage manager.
2989            mStorageManagerPackage = getStorageManagerPackageName();
2990
2991            // Resolve protected action filters. Only the setup wizard is allowed to
2992            // have a high priority filter for these actions.
2993            mSetupWizardPackage = getSetupWizardPackageName();
2994            if (mProtectedFilters.size() > 0) {
2995                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2996                    Slog.i(TAG, "No setup wizard;"
2997                        + " All protected intents capped to priority 0");
2998                }
2999                for (ActivityIntentInfo filter : mProtectedFilters) {
3000                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3001                        if (DEBUG_FILTERS) {
3002                            Slog.i(TAG, "Found setup wizard;"
3003                                + " allow priority " + filter.getPriority() + ";"
3004                                + " package: " + filter.activity.info.packageName
3005                                + " activity: " + filter.activity.className
3006                                + " priority: " + filter.getPriority());
3007                        }
3008                        // skip setup wizard; allow it to keep the high priority filter
3009                        continue;
3010                    }
3011                    if (DEBUG_FILTERS) {
3012                        Slog.i(TAG, "Protected action; cap priority to 0;"
3013                                + " package: " + filter.activity.info.packageName
3014                                + " activity: " + filter.activity.className
3015                                + " origPrio: " + filter.getPriority());
3016                    }
3017                    filter.setPriority(0);
3018                }
3019            }
3020
3021            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3022
3023            mDeferProtectedFilters = false;
3024            mProtectedFilters.clear();
3025
3026            // Now that we know all of the shared libraries, update all clients to have
3027            // the correct library paths.
3028            updateAllSharedLibrariesLPw(null);
3029
3030            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3031                // NOTE: We ignore potential failures here during a system scan (like
3032                // the rest of the commands above) because there's precious little we
3033                // can do about it. A settings error is reported, though.
3034                final List<String> changedAbiCodePath =
3035                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3036                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3037                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3038                        final String codePathString = changedAbiCodePath.get(i);
3039                        try {
3040                            mInstaller.rmdex(codePathString,
3041                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3042                        } catch (InstallerException ignored) {
3043                        }
3044                    }
3045                }
3046                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3047                // SELinux domain.
3048                setting.fixSeInfoLocked();
3049            }
3050
3051            // Now that we know all the packages we are keeping,
3052            // read and update their last usage times.
3053            mPackageUsage.read(mPackages);
3054            mCompilerStats.read();
3055
3056            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3057                    SystemClock.uptimeMillis());
3058            Slog.i(TAG, "Time to scan packages: "
3059                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3060                    + " seconds");
3061
3062            // If the platform SDK has changed since the last time we booted,
3063            // we need to re-grant app permission to catch any new ones that
3064            // appear.  This is really a hack, and means that apps can in some
3065            // cases get permissions that the user didn't initially explicitly
3066            // allow...  it would be nice to have some better way to handle
3067            // this situation.
3068            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3069            if (sdkUpdated) {
3070                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3071                        + mSdkVersion + "; regranting permissions for internal storage");
3072            }
3073            mPermissionManager.updateAllPermissions(
3074                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3075                    mPermissionCallback);
3076            ver.sdkVersion = mSdkVersion;
3077
3078            // If this is the first boot or an update from pre-M, and it is a normal
3079            // boot, then we need to initialize the default preferred apps across
3080            // all defined users.
3081            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3082                for (UserInfo user : sUserManager.getUsers(true)) {
3083                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3084                    applyFactoryDefaultBrowserLPw(user.id);
3085                    primeDomainVerificationsLPw(user.id);
3086                }
3087            }
3088
3089            // Prepare storage for system user really early during boot,
3090            // since core system apps like SettingsProvider and SystemUI
3091            // can't wait for user to start
3092            final int storageFlags;
3093            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3094                storageFlags = StorageManager.FLAG_STORAGE_DE;
3095            } else {
3096                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3097            }
3098            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3099                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3100                    true /* onlyCoreApps */);
3101            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3102                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3103                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3104                traceLog.traceBegin("AppDataFixup");
3105                try {
3106                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3107                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3108                } catch (InstallerException e) {
3109                    Slog.w(TAG, "Trouble fixing GIDs", e);
3110                }
3111                traceLog.traceEnd();
3112
3113                traceLog.traceBegin("AppDataPrepare");
3114                if (deferPackages == null || deferPackages.isEmpty()) {
3115                    return;
3116                }
3117                int count = 0;
3118                for (String pkgName : deferPackages) {
3119                    PackageParser.Package pkg = null;
3120                    synchronized (mPackages) {
3121                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3122                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3123                            pkg = ps.pkg;
3124                        }
3125                    }
3126                    if (pkg != null) {
3127                        synchronized (mInstallLock) {
3128                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3129                                    true /* maybeMigrateAppData */);
3130                        }
3131                        count++;
3132                    }
3133                }
3134                traceLog.traceEnd();
3135                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3136            }, "prepareAppData");
3137
3138            // If this is first boot after an OTA, and a normal boot, then
3139            // we need to clear code cache directories.
3140            // Note that we do *not* clear the application profiles. These remain valid
3141            // across OTAs and are used to drive profile verification (post OTA) and
3142            // profile compilation (without waiting to collect a fresh set of profiles).
3143            if (mIsUpgrade && !onlyCore) {
3144                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3145                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3146                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3147                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3148                        // No apps are running this early, so no need to freeze
3149                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3150                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3151                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3152                    }
3153                }
3154                ver.fingerprint = Build.FINGERPRINT;
3155            }
3156
3157            checkDefaultBrowser();
3158
3159            // clear only after permissions and other defaults have been updated
3160            mExistingSystemPackages.clear();
3161            mPromoteSystemApps = false;
3162
3163            // All the changes are done during package scanning.
3164            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3165
3166            // can downgrade to reader
3167            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3168            mSettings.writeLPr();
3169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3170            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3171                    SystemClock.uptimeMillis());
3172
3173            if (!mOnlyCore) {
3174                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3175                mRequiredInstallerPackage = getRequiredInstallerLPr();
3176                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3177                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3178                if (mIntentFilterVerifierComponent != null) {
3179                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3180                            mIntentFilterVerifierComponent);
3181                } else {
3182                    mIntentFilterVerifier = null;
3183                }
3184                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3185                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3186                        SharedLibraryInfo.VERSION_UNDEFINED);
3187                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3188                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3189                        SharedLibraryInfo.VERSION_UNDEFINED);
3190            } else {
3191                mRequiredVerifierPackage = null;
3192                mRequiredInstallerPackage = null;
3193                mRequiredUninstallerPackage = null;
3194                mIntentFilterVerifierComponent = null;
3195                mIntentFilterVerifier = null;
3196                mServicesSystemSharedLibraryPackageName = null;
3197                mSharedSystemSharedLibraryPackageName = null;
3198            }
3199
3200            mInstallerService = new PackageInstallerService(context, this);
3201            final Pair<ComponentName, String> instantAppResolverComponent =
3202                    getInstantAppResolverLPr();
3203            if (instantAppResolverComponent != null) {
3204                if (DEBUG_INSTANT) {
3205                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3206                }
3207                mInstantAppResolverConnection = new InstantAppResolverConnection(
3208                        mContext, instantAppResolverComponent.first,
3209                        instantAppResolverComponent.second);
3210                mInstantAppResolverSettingsComponent =
3211                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3212            } else {
3213                mInstantAppResolverConnection = null;
3214                mInstantAppResolverSettingsComponent = null;
3215            }
3216            updateInstantAppInstallerLocked(null);
3217
3218            // Read and update the usage of dex files.
3219            // Do this at the end of PM init so that all the packages have their
3220            // data directory reconciled.
3221            // At this point we know the code paths of the packages, so we can validate
3222            // the disk file and build the internal cache.
3223            // The usage file is expected to be small so loading and verifying it
3224            // should take a fairly small time compare to the other activities (e.g. package
3225            // scanning).
3226            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3227            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3228            for (int userId : currentUserIds) {
3229                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3230            }
3231            mDexManager.load(userPackages);
3232            if (mIsUpgrade) {
3233                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3234                        (int) (SystemClock.uptimeMillis() - startTime));
3235            }
3236        } // synchronized (mPackages)
3237        } // synchronized (mInstallLock)
3238
3239        // Now after opening every single application zip, make sure they
3240        // are all flushed.  Not really needed, but keeps things nice and
3241        // tidy.
3242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3243        Runtime.getRuntime().gc();
3244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3245
3246        // The initial scanning above does many calls into installd while
3247        // holding the mPackages lock, but we're mostly interested in yelling
3248        // once we have a booted system.
3249        mInstaller.setWarnIfHeld(mPackages);
3250
3251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3252    }
3253
3254    /**
3255     * Uncompress and install stub applications.
3256     * <p>In order to save space on the system partition, some applications are shipped in a
3257     * compressed form. In addition the compressed bits for the full application, the
3258     * system image contains a tiny stub comprised of only the Android manifest.
3259     * <p>During the first boot, attempt to uncompress and install the full application. If
3260     * the application can't be installed for any reason, disable the stub and prevent
3261     * uncompressing the full application during future boots.
3262     * <p>In order to forcefully attempt an installation of a full application, go to app
3263     * settings and enable the application.
3264     */
3265    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3266        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3267            final String pkgName = stubSystemApps.get(i);
3268            // skip if the system package is already disabled
3269            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3270                stubSystemApps.remove(i);
3271                continue;
3272            }
3273            // skip if the package isn't installed (?!); this should never happen
3274            final PackageParser.Package pkg = mPackages.get(pkgName);
3275            if (pkg == null) {
3276                stubSystemApps.remove(i);
3277                continue;
3278            }
3279            // skip if the package has been disabled by the user
3280            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3281            if (ps != null) {
3282                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3283                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3284                    stubSystemApps.remove(i);
3285                    continue;
3286                }
3287            }
3288
3289            if (DEBUG_COMPRESSION) {
3290                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3291            }
3292
3293            // uncompress the binary to its eventual destination on /data
3294            final File scanFile = decompressPackage(pkg);
3295            if (scanFile == null) {
3296                continue;
3297            }
3298
3299            // install the package to replace the stub on /system
3300            try {
3301                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3302                removePackageLI(pkg, true /*chatty*/);
3303                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3304                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3305                        UserHandle.USER_SYSTEM, "android");
3306                stubSystemApps.remove(i);
3307                continue;
3308            } catch (PackageManagerException e) {
3309                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3310            }
3311
3312            // any failed attempt to install the package will be cleaned up later
3313        }
3314
3315        // disable any stub still left; these failed to install the full application
3316        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3317            final String pkgName = stubSystemApps.get(i);
3318            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3319            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3320                    UserHandle.USER_SYSTEM, "android");
3321            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3322        }
3323    }
3324
3325    /**
3326     * Decompresses the given package on the system image onto
3327     * the /data partition.
3328     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3329     */
3330    private File decompressPackage(PackageParser.Package pkg) {
3331        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3332        if (compressedFiles == null || compressedFiles.length == 0) {
3333            if (DEBUG_COMPRESSION) {
3334                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3335            }
3336            return null;
3337        }
3338        final File dstCodePath =
3339                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3340        int ret = PackageManager.INSTALL_SUCCEEDED;
3341        try {
3342            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3343            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3344            for (File srcFile : compressedFiles) {
3345                final String srcFileName = srcFile.getName();
3346                final String dstFileName = srcFileName.substring(
3347                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3348                final File dstFile = new File(dstCodePath, dstFileName);
3349                ret = decompressFile(srcFile, dstFile);
3350                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3351                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3352                            + "; pkg: " + pkg.packageName
3353                            + ", file: " + dstFileName);
3354                    break;
3355                }
3356            }
3357        } catch (ErrnoException e) {
3358            logCriticalInfo(Log.ERROR, "Failed to decompress"
3359                    + "; pkg: " + pkg.packageName
3360                    + ", err: " + e.errno);
3361        }
3362        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3363            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3364            NativeLibraryHelper.Handle handle = null;
3365            try {
3366                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3367                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3368                        null /*abiOverride*/);
3369            } catch (IOException e) {
3370                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3371                        + "; pkg: " + pkg.packageName);
3372                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3373            } finally {
3374                IoUtils.closeQuietly(handle);
3375            }
3376        }
3377        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3378            if (dstCodePath == null || !dstCodePath.exists()) {
3379                return null;
3380            }
3381            removeCodePathLI(dstCodePath);
3382            return null;
3383        }
3384
3385        return dstCodePath;
3386    }
3387
3388    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3389        // we're only interested in updating the installer appliction when 1) it's not
3390        // already set or 2) the modified package is the installer
3391        if (mInstantAppInstallerActivity != null
3392                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3393                        .equals(modifiedPackage)) {
3394            return;
3395        }
3396        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3397    }
3398
3399    private static File preparePackageParserCache(boolean isUpgrade) {
3400        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3401            return null;
3402        }
3403
3404        // Disable package parsing on eng builds to allow for faster incremental development.
3405        if (Build.IS_ENG) {
3406            return null;
3407        }
3408
3409        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3410            Slog.i(TAG, "Disabling package parser cache due to system property.");
3411            return null;
3412        }
3413
3414        // The base directory for the package parser cache lives under /data/system/.
3415        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3416                "package_cache");
3417        if (cacheBaseDir == null) {
3418            return null;
3419        }
3420
3421        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3422        // This also serves to "GC" unused entries when the package cache version changes (which
3423        // can only happen during upgrades).
3424        if (isUpgrade) {
3425            FileUtils.deleteContents(cacheBaseDir);
3426        }
3427
3428
3429        // Return the versioned package cache directory. This is something like
3430        // "/data/system/package_cache/1"
3431        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3432
3433        if (cacheDir == null) {
3434            // Something went wrong. Attempt to delete everything and return.
3435            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3436            FileUtils.deleteContentsAndDir(cacheBaseDir);
3437            return null;
3438        }
3439
3440        // The following is a workaround to aid development on non-numbered userdebug
3441        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3442        // the system partition is newer.
3443        //
3444        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3445        // that starts with "eng." to signify that this is an engineering build and not
3446        // destined for release.
3447        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3448            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3449
3450            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3451            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3452            // in general and should not be used for production changes. In this specific case,
3453            // we know that they will work.
3454            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3455            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3456                FileUtils.deleteContents(cacheBaseDir);
3457                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3458            }
3459        }
3460
3461        return cacheDir;
3462    }
3463
3464    @Override
3465    public boolean isFirstBoot() {
3466        // allow instant applications
3467        return mFirstBoot;
3468    }
3469
3470    @Override
3471    public boolean isOnlyCoreApps() {
3472        // allow instant applications
3473        return mOnlyCore;
3474    }
3475
3476    @Override
3477    public boolean isUpgrade() {
3478        // allow instant applications
3479        // The system property allows testing ota flow when upgraded to the same image.
3480        return mIsUpgrade || SystemProperties.getBoolean(
3481                "persist.pm.mock-upgrade", false /* default */);
3482    }
3483
3484    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3485        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3486
3487        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3488                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3489                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3490        if (matches.size() == 1) {
3491            return matches.get(0).getComponentInfo().packageName;
3492        } else if (matches.size() == 0) {
3493            Log.e(TAG, "There should probably be a verifier, but, none were found");
3494            return null;
3495        }
3496        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3497    }
3498
3499    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3500        synchronized (mPackages) {
3501            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3502            if (libraryEntry == null) {
3503                throw new IllegalStateException("Missing required shared library:" + name);
3504            }
3505            return libraryEntry.apk;
3506        }
3507    }
3508
3509    private @NonNull String getRequiredInstallerLPr() {
3510        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3511        intent.addCategory(Intent.CATEGORY_DEFAULT);
3512        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3513
3514        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3515                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3516                UserHandle.USER_SYSTEM);
3517        if (matches.size() == 1) {
3518            ResolveInfo resolveInfo = matches.get(0);
3519            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3520                throw new RuntimeException("The installer must be a privileged app");
3521            }
3522            return matches.get(0).getComponentInfo().packageName;
3523        } else {
3524            throw new RuntimeException("There must be exactly one installer; found " + matches);
3525        }
3526    }
3527
3528    private @NonNull String getRequiredUninstallerLPr() {
3529        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3530        intent.addCategory(Intent.CATEGORY_DEFAULT);
3531        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3532
3533        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3534                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3535                UserHandle.USER_SYSTEM);
3536        if (resolveInfo == null ||
3537                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3538            throw new RuntimeException("There must be exactly one uninstaller; found "
3539                    + resolveInfo);
3540        }
3541        return resolveInfo.getComponentInfo().packageName;
3542    }
3543
3544    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3545        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3546
3547        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3550        ResolveInfo best = null;
3551        final int N = matches.size();
3552        for (int i = 0; i < N; i++) {
3553            final ResolveInfo cur = matches.get(i);
3554            final String packageName = cur.getComponentInfo().packageName;
3555            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3556                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3557                continue;
3558            }
3559
3560            if (best == null || cur.priority > best.priority) {
3561                best = cur;
3562            }
3563        }
3564
3565        if (best != null) {
3566            return best.getComponentInfo().getComponentName();
3567        }
3568        Slog.w(TAG, "Intent filter verifier not found");
3569        return null;
3570    }
3571
3572    @Override
3573    public @Nullable ComponentName getInstantAppResolverComponent() {
3574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3575            return null;
3576        }
3577        synchronized (mPackages) {
3578            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3579            if (instantAppResolver == null) {
3580                return null;
3581            }
3582            return instantAppResolver.first;
3583        }
3584    }
3585
3586    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3587        final String[] packageArray =
3588                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3589        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3590            if (DEBUG_INSTANT) {
3591                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3592            }
3593            return null;
3594        }
3595
3596        final int callingUid = Binder.getCallingUid();
3597        final int resolveFlags =
3598                MATCH_DIRECT_BOOT_AWARE
3599                | MATCH_DIRECT_BOOT_UNAWARE
3600                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3601        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3602        final Intent resolverIntent = new Intent(actionName);
3603        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3604                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3605        final int N = resolvers.size();
3606        if (N == 0) {
3607            if (DEBUG_INSTANT) {
3608                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3609            }
3610            return null;
3611        }
3612
3613        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3614        for (int i = 0; i < N; i++) {
3615            final ResolveInfo info = resolvers.get(i);
3616
3617            if (info.serviceInfo == null) {
3618                continue;
3619            }
3620
3621            final String packageName = info.serviceInfo.packageName;
3622            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3623                if (DEBUG_INSTANT) {
3624                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3625                            + " pkg: " + packageName + ", info:" + info);
3626                }
3627                continue;
3628            }
3629
3630            if (DEBUG_INSTANT) {
3631                Slog.v(TAG, "Ephemeral resolver found;"
3632                        + " pkg: " + packageName + ", info:" + info);
3633            }
3634            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3635        }
3636        if (DEBUG_INSTANT) {
3637            Slog.v(TAG, "Ephemeral resolver NOT found");
3638        }
3639        return null;
3640    }
3641
3642    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3643        String[] orderedActions = Build.IS_ENG
3644                ? new String[]{
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3646                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3647                : new String[]{
3648                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3649
3650        final int resolveFlags =
3651                MATCH_DIRECT_BOOT_AWARE
3652                        | MATCH_DIRECT_BOOT_UNAWARE
3653                        | Intent.FLAG_IGNORE_EPHEMERAL
3654                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3655        final Intent intent = new Intent();
3656        intent.addCategory(Intent.CATEGORY_DEFAULT);
3657        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3658        List<ResolveInfo> matches = null;
3659        for (String action : orderedActions) {
3660            intent.setAction(action);
3661            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3662                    resolveFlags, UserHandle.USER_SYSTEM);
3663            if (matches.isEmpty()) {
3664                if (DEBUG_INSTANT) {
3665                    Slog.d(TAG, "Instant App installer not found with " + action);
3666                }
3667            } else {
3668                break;
3669            }
3670        }
3671        Iterator<ResolveInfo> iter = matches.iterator();
3672        while (iter.hasNext()) {
3673            final ResolveInfo rInfo = iter.next();
3674            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3675            if (ps != null) {
3676                final PermissionsState permissionsState = ps.getPermissionsState();
3677                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3678                        || Build.IS_ENG) {
3679                    continue;
3680                }
3681            }
3682            iter.remove();
3683        }
3684        if (matches.size() == 0) {
3685            return null;
3686        } else if (matches.size() == 1) {
3687            return (ActivityInfo) matches.get(0).getComponentInfo();
3688        } else {
3689            throw new RuntimeException(
3690                    "There must be at most one ephemeral installer; found " + matches);
3691        }
3692    }
3693
3694    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3695            @NonNull ComponentName resolver) {
3696        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3697                .addCategory(Intent.CATEGORY_DEFAULT)
3698                .setPackage(resolver.getPackageName());
3699        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3700        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3701                UserHandle.USER_SYSTEM);
3702        if (matches.isEmpty()) {
3703            return null;
3704        }
3705        return matches.get(0).getComponentInfo().getComponentName();
3706    }
3707
3708    private void primeDomainVerificationsLPw(int userId) {
3709        if (DEBUG_DOMAIN_VERIFICATION) {
3710            Slog.d(TAG, "Priming domain verifications in user " + userId);
3711        }
3712
3713        SystemConfig systemConfig = SystemConfig.getInstance();
3714        ArraySet<String> packages = systemConfig.getLinkedApps();
3715
3716        for (String packageName : packages) {
3717            PackageParser.Package pkg = mPackages.get(packageName);
3718            if (pkg != null) {
3719                if (!pkg.isSystem()) {
3720                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3721                    continue;
3722                }
3723
3724                ArraySet<String> domains = null;
3725                for (PackageParser.Activity a : pkg.activities) {
3726                    for (ActivityIntentInfo filter : a.intents) {
3727                        if (hasValidDomains(filter)) {
3728                            if (domains == null) {
3729                                domains = new ArraySet<String>();
3730                            }
3731                            domains.addAll(filter.getHostsList());
3732                        }
3733                    }
3734                }
3735
3736                if (domains != null && domains.size() > 0) {
3737                    if (DEBUG_DOMAIN_VERIFICATION) {
3738                        Slog.v(TAG, "      + " + packageName);
3739                    }
3740                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3741                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3742                    // and then 'always' in the per-user state actually used for intent resolution.
3743                    final IntentFilterVerificationInfo ivi;
3744                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3745                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3746                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3747                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3748                } else {
3749                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3750                            + "' does not handle web links");
3751                }
3752            } else {
3753                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3754            }
3755        }
3756
3757        scheduleWritePackageRestrictionsLocked(userId);
3758        scheduleWriteSettingsLocked();
3759    }
3760
3761    private void applyFactoryDefaultBrowserLPw(int userId) {
3762        // The default browser app's package name is stored in a string resource,
3763        // with a product-specific overlay used for vendor customization.
3764        String browserPkg = mContext.getResources().getString(
3765                com.android.internal.R.string.default_browser);
3766        if (!TextUtils.isEmpty(browserPkg)) {
3767            // non-empty string => required to be a known package
3768            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3769            if (ps == null) {
3770                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3771                browserPkg = null;
3772            } else {
3773                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3774            }
3775        }
3776
3777        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3778        // default.  If there's more than one, just leave everything alone.
3779        if (browserPkg == null) {
3780            calculateDefaultBrowserLPw(userId);
3781        }
3782    }
3783
3784    private void calculateDefaultBrowserLPw(int userId) {
3785        List<String> allBrowsers = resolveAllBrowserApps(userId);
3786        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3787        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788    }
3789
3790    private List<String> resolveAllBrowserApps(int userId) {
3791        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3792        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3793                PackageManager.MATCH_ALL, userId);
3794
3795        final int count = list.size();
3796        List<String> result = new ArrayList<String>(count);
3797        for (int i=0; i<count; i++) {
3798            ResolveInfo info = list.get(i);
3799            if (info.activityInfo == null
3800                    || !info.handleAllWebDataURI
3801                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3802                    || result.contains(info.activityInfo.packageName)) {
3803                continue;
3804            }
3805            result.add(info.activityInfo.packageName);
3806        }
3807
3808        return result;
3809    }
3810
3811    private boolean packageIsBrowser(String packageName, int userId) {
3812        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3813                PackageManager.MATCH_ALL, userId);
3814        final int N = list.size();
3815        for (int i = 0; i < N; i++) {
3816            ResolveInfo info = list.get(i);
3817            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3818                return true;
3819            }
3820        }
3821        return false;
3822    }
3823
3824    private void checkDefaultBrowser() {
3825        final int myUserId = UserHandle.myUserId();
3826        final String packageName = getDefaultBrowserPackageName(myUserId);
3827        if (packageName != null) {
3828            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3829            if (info == null) {
3830                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3831                synchronized (mPackages) {
3832                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3833                }
3834            }
3835        }
3836    }
3837
3838    @Override
3839    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3840            throws RemoteException {
3841        try {
3842            return super.onTransact(code, data, reply, flags);
3843        } catch (RuntimeException e) {
3844            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3845                Slog.wtf(TAG, "Package Manager Crash", e);
3846            }
3847            throw e;
3848        }
3849    }
3850
3851    static int[] appendInts(int[] cur, int[] add) {
3852        if (add == null) return cur;
3853        if (cur == null) return add;
3854        final int N = add.length;
3855        for (int i=0; i<N; i++) {
3856            cur = appendInt(cur, add[i]);
3857        }
3858        return cur;
3859    }
3860
3861    /**
3862     * Returns whether or not a full application can see an instant application.
3863     * <p>
3864     * Currently, there are three cases in which this can occur:
3865     * <ol>
3866     * <li>The calling application is a "special" process. Special processes
3867     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3868     * <li>The calling application has the permission
3869     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3870     * <li>The calling application is the default launcher on the
3871     *     system partition.</li>
3872     * </ol>
3873     */
3874    private boolean canViewInstantApps(int callingUid, int userId) {
3875        if (callingUid < Process.FIRST_APPLICATION_UID) {
3876            return true;
3877        }
3878        if (mContext.checkCallingOrSelfPermission(
3879                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3880            return true;
3881        }
3882        if (mContext.checkCallingOrSelfPermission(
3883                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3884            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3885            if (homeComponent != null
3886                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3887                return true;
3888            }
3889        }
3890        return false;
3891    }
3892
3893    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return null;
3895        if (ps == null) {
3896            return null;
3897        }
3898        final int callingUid = Binder.getCallingUid();
3899        // Filter out ephemeral app metadata:
3900        //   * The system/shell/root can see metadata for any app
3901        //   * An installed app can see metadata for 1) other installed apps
3902        //     and 2) ephemeral apps that have explicitly interacted with it
3903        //   * Ephemeral apps can only see their own data and exposed installed apps
3904        //   * Holding a signature permission allows seeing instant apps
3905        if (filterAppAccessLPr(ps, callingUid, userId)) {
3906            return null;
3907        }
3908
3909        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3910                && ps.isSystem()) {
3911            flags |= MATCH_ANY_USER;
3912        }
3913
3914        final PackageUserState state = ps.readUserState(userId);
3915        PackageParser.Package p = ps.pkg;
3916        if (p != null) {
3917            final PermissionsState permissionsState = ps.getPermissionsState();
3918
3919            // Compute GIDs only if requested
3920            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3921                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3922            // Compute granted permissions only if package has requested permissions
3923            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3924                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3925
3926            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3927                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3928
3929            if (packageInfo == null) {
3930                return null;
3931            }
3932
3933            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3934                    resolveExternalPackageNameLPr(p);
3935
3936            return packageInfo;
3937        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3938            PackageInfo pi = new PackageInfo();
3939            pi.packageName = ps.name;
3940            pi.setLongVersionCode(ps.versionCode);
3941            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3942            pi.firstInstallTime = ps.firstInstallTime;
3943            pi.lastUpdateTime = ps.lastUpdateTime;
3944
3945            ApplicationInfo ai = new ApplicationInfo();
3946            ai.packageName = ps.name;
3947            ai.uid = UserHandle.getUid(userId, ps.appId);
3948            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3949            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3950            ai.setVersionCode(ps.versionCode);
3951            ai.flags = ps.pkgFlags;
3952            ai.privateFlags = ps.pkgPrivateFlags;
3953            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3954
3955            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3956                    + ps.name + "]. Provides a minimum info.");
3957            return pi;
3958        } else {
3959            return null;
3960        }
3961    }
3962
3963    @Override
3964    public void checkPackageStartable(String packageName, int userId) {
3965        final int callingUid = Binder.getCallingUid();
3966        if (getInstantAppPackageName(callingUid) != null) {
3967            throw new SecurityException("Instant applications don't have access to this method");
3968        }
3969        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3970        synchronized (mPackages) {
3971            final PackageSetting ps = mSettings.mPackages.get(packageName);
3972            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3973                throw new SecurityException("Package " + packageName + " was not found!");
3974            }
3975
3976            if (!ps.getInstalled(userId)) {
3977                throw new SecurityException(
3978                        "Package " + packageName + " was not installed for user " + userId + "!");
3979            }
3980
3981            if (mSafeMode && !ps.isSystem()) {
3982                throw new SecurityException("Package " + packageName + " not a system app!");
3983            }
3984
3985            if (mFrozenPackages.contains(packageName)) {
3986                throw new SecurityException("Package " + packageName + " is currently frozen!");
3987            }
3988
3989            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3990                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3991            }
3992        }
3993    }
3994
3995    @Override
3996    public boolean isPackageAvailable(String packageName, int userId) {
3997        if (!sUserManager.exists(userId)) return false;
3998        final int callingUid = Binder.getCallingUid();
3999        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4000                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4001        synchronized (mPackages) {
4002            PackageParser.Package p = mPackages.get(packageName);
4003            if (p != null) {
4004                final PackageSetting ps = (PackageSetting) p.mExtras;
4005                if (filterAppAccessLPr(ps, callingUid, userId)) {
4006                    return false;
4007                }
4008                if (ps != null) {
4009                    final PackageUserState state = ps.readUserState(userId);
4010                    if (state != null) {
4011                        return PackageParser.isAvailable(state);
4012                    }
4013                }
4014            }
4015        }
4016        return false;
4017    }
4018
4019    @Override
4020    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4021        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4022                flags, Binder.getCallingUid(), userId);
4023    }
4024
4025    @Override
4026    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4027            int flags, int userId) {
4028        return getPackageInfoInternal(versionedPackage.getPackageName(),
4029                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4030    }
4031
4032    /**
4033     * Important: The provided filterCallingUid is used exclusively to filter out packages
4034     * that can be seen based on user state. It's typically the original caller uid prior
4035     * to clearing. Because it can only be provided by trusted code, it's value can be
4036     * trusted and will be used as-is; unlike userId which will be validated by this method.
4037     */
4038    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4039            int flags, int filterCallingUid, int userId) {
4040        if (!sUserManager.exists(userId)) return null;
4041        flags = updateFlagsForPackage(flags, userId, packageName);
4042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4043                false /* requireFullPermission */, false /* checkShell */, "get package info");
4044
4045        // reader
4046        synchronized (mPackages) {
4047            // Normalize package name to handle renamed packages and static libs
4048            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4049
4050            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4051            if (matchFactoryOnly) {
4052                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4053                if (ps != null) {
4054                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4055                        return null;
4056                    }
4057                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4058                        return null;
4059                    }
4060                    return generatePackageInfo(ps, flags, userId);
4061                }
4062            }
4063
4064            PackageParser.Package p = mPackages.get(packageName);
4065            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4066                return null;
4067            }
4068            if (DEBUG_PACKAGE_INFO)
4069                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4070            if (p != null) {
4071                final PackageSetting ps = (PackageSetting) p.mExtras;
4072                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4073                    return null;
4074                }
4075                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4076                    return null;
4077                }
4078                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4079            }
4080            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4081                final PackageSetting ps = mSettings.mPackages.get(packageName);
4082                if (ps == null) return null;
4083                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4084                    return null;
4085                }
4086                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4087                    return null;
4088                }
4089                return generatePackageInfo(ps, flags, userId);
4090            }
4091        }
4092        return null;
4093    }
4094
4095    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4096        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4097            return true;
4098        }
4099        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4100            return true;
4101        }
4102        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4103            return true;
4104        }
4105        return false;
4106    }
4107
4108    private boolean isComponentVisibleToInstantApp(
4109            @Nullable ComponentName component, @ComponentType int type) {
4110        if (type == TYPE_ACTIVITY) {
4111            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4112            if (activity == null) {
4113                return false;
4114            }
4115            final boolean visibleToInstantApp =
4116                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4117            final boolean explicitlyVisibleToInstantApp =
4118                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4119            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4120        } else if (type == TYPE_RECEIVER) {
4121            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4122            if (activity == null) {
4123                return false;
4124            }
4125            final boolean visibleToInstantApp =
4126                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4127            final boolean explicitlyVisibleToInstantApp =
4128                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4129            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4130        } else if (type == TYPE_SERVICE) {
4131            final PackageParser.Service service = mServices.mServices.get(component);
4132            return service != null
4133                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4134                    : false;
4135        } else if (type == TYPE_PROVIDER) {
4136            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4137            return provider != null
4138                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4139                    : false;
4140        } else if (type == TYPE_UNKNOWN) {
4141            return isComponentVisibleToInstantApp(component);
4142        }
4143        return false;
4144    }
4145
4146    /**
4147     * Returns whether or not access to the application should be filtered.
4148     * <p>
4149     * Access may be limited based upon whether the calling or target applications
4150     * are instant applications.
4151     *
4152     * @see #canAccessInstantApps(int)
4153     */
4154    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4155            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4156        // if we're in an isolated process, get the real calling UID
4157        if (Process.isIsolated(callingUid)) {
4158            callingUid = mIsolatedOwners.get(callingUid);
4159        }
4160        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4161        final boolean callerIsInstantApp = instantAppPkgName != null;
4162        if (ps == null) {
4163            if (callerIsInstantApp) {
4164                // pretend the application exists, but, needs to be filtered
4165                return true;
4166            }
4167            return false;
4168        }
4169        // if the target and caller are the same application, don't filter
4170        if (isCallerSameApp(ps.name, callingUid)) {
4171            return false;
4172        }
4173        if (callerIsInstantApp) {
4174            // both caller and target are both instant, but, different applications, filter
4175            if (ps.getInstantApp(userId)) {
4176                return true;
4177            }
4178            // request for a specific component; if it hasn't been explicitly exposed through
4179            // property or instrumentation target, filter
4180            if (component != null) {
4181                final PackageParser.Instrumentation instrumentation =
4182                        mInstrumentation.get(component);
4183                if (instrumentation != null
4184                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4185                    return false;
4186                }
4187                return !isComponentVisibleToInstantApp(component, componentType);
4188            }
4189            // request for application; if no components have been explicitly exposed, filter
4190            return !ps.pkg.visibleToInstantApps;
4191        }
4192        if (ps.getInstantApp(userId)) {
4193            // caller can see all components of all instant applications, don't filter
4194            if (canViewInstantApps(callingUid, userId)) {
4195                return false;
4196            }
4197            // request for a specific instant application component, filter
4198            if (component != null) {
4199                return true;
4200            }
4201            // request for an instant application; if the caller hasn't been granted access, filter
4202            return !mInstantAppRegistry.isInstantAccessGranted(
4203                    userId, UserHandle.getAppId(callingUid), ps.appId);
4204        }
4205        return false;
4206    }
4207
4208    /**
4209     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4210     */
4211    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4212        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4213    }
4214
4215    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4216            int flags) {
4217        // Callers can access only the libs they depend on, otherwise they need to explicitly
4218        // ask for the shared libraries given the caller is allowed to access all static libs.
4219        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4220            // System/shell/root get to see all static libs
4221            final int appId = UserHandle.getAppId(uid);
4222            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4223                    || appId == Process.ROOT_UID) {
4224                return false;
4225            }
4226            // Installer gets to see all static libs.
4227            if (PackageManager.PERMISSION_GRANTED
4228                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4229                return false;
4230            }
4231        }
4232
4233        // No package means no static lib as it is always on internal storage
4234        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4235            return false;
4236        }
4237
4238        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4239                ps.pkg.staticSharedLibVersion);
4240        if (libEntry == null) {
4241            return false;
4242        }
4243
4244        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4245        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4246        if (uidPackageNames == null) {
4247            return true;
4248        }
4249
4250        for (String uidPackageName : uidPackageNames) {
4251            if (ps.name.equals(uidPackageName)) {
4252                return false;
4253            }
4254            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4255            if (uidPs != null) {
4256                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4257                        libEntry.info.getName());
4258                if (index < 0) {
4259                    continue;
4260                }
4261                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4262                    return false;
4263                }
4264            }
4265        }
4266        return true;
4267    }
4268
4269    @Override
4270    public String[] currentToCanonicalPackageNames(String[] names) {
4271        final int callingUid = Binder.getCallingUid();
4272        if (getInstantAppPackageName(callingUid) != null) {
4273            return names;
4274        }
4275        final String[] out = new String[names.length];
4276        // reader
4277        synchronized (mPackages) {
4278            final int callingUserId = UserHandle.getUserId(callingUid);
4279            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4280            for (int i=names.length-1; i>=0; i--) {
4281                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4282                boolean translateName = false;
4283                if (ps != null && ps.realName != null) {
4284                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4285                    translateName = !targetIsInstantApp
4286                            || canViewInstantApps
4287                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4288                                    UserHandle.getAppId(callingUid), ps.appId);
4289                }
4290                out[i] = translateName ? ps.realName : names[i];
4291            }
4292        }
4293        return out;
4294    }
4295
4296    @Override
4297    public String[] canonicalToCurrentPackageNames(String[] names) {
4298        final int callingUid = Binder.getCallingUid();
4299        if (getInstantAppPackageName(callingUid) != null) {
4300            return names;
4301        }
4302        final String[] out = new String[names.length];
4303        // reader
4304        synchronized (mPackages) {
4305            final int callingUserId = UserHandle.getUserId(callingUid);
4306            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4307            for (int i=names.length-1; i>=0; i--) {
4308                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4309                boolean translateName = false;
4310                if (cur != null) {
4311                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4312                    final boolean targetIsInstantApp =
4313                            ps != null && ps.getInstantApp(callingUserId);
4314                    translateName = !targetIsInstantApp
4315                            || canViewInstantApps
4316                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4317                                    UserHandle.getAppId(callingUid), ps.appId);
4318                }
4319                out[i] = translateName ? cur : names[i];
4320            }
4321        }
4322        return out;
4323    }
4324
4325    @Override
4326    public int getPackageUid(String packageName, int flags, int userId) {
4327        if (!sUserManager.exists(userId)) return -1;
4328        final int callingUid = Binder.getCallingUid();
4329        flags = updateFlagsForPackage(flags, userId, packageName);
4330        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4331                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4332
4333        // reader
4334        synchronized (mPackages) {
4335            final PackageParser.Package p = mPackages.get(packageName);
4336            if (p != null && p.isMatch(flags)) {
4337                PackageSetting ps = (PackageSetting) p.mExtras;
4338                if (filterAppAccessLPr(ps, callingUid, userId)) {
4339                    return -1;
4340                }
4341                return UserHandle.getUid(userId, p.applicationInfo.uid);
4342            }
4343            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4344                final PackageSetting ps = mSettings.mPackages.get(packageName);
4345                if (ps != null && ps.isMatch(flags)
4346                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4347                    return UserHandle.getUid(userId, ps.appId);
4348                }
4349            }
4350        }
4351
4352        return -1;
4353    }
4354
4355    @Override
4356    public int[] getPackageGids(String packageName, int flags, int userId) {
4357        if (!sUserManager.exists(userId)) return null;
4358        final int callingUid = Binder.getCallingUid();
4359        flags = updateFlagsForPackage(flags, userId, packageName);
4360        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4361                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4362
4363        // reader
4364        synchronized (mPackages) {
4365            final PackageParser.Package p = mPackages.get(packageName);
4366            if (p != null && p.isMatch(flags)) {
4367                PackageSetting ps = (PackageSetting) p.mExtras;
4368                if (filterAppAccessLPr(ps, callingUid, userId)) {
4369                    return null;
4370                }
4371                // TODO: Shouldn't this be checking for package installed state for userId and
4372                // return null?
4373                return ps.getPermissionsState().computeGids(userId);
4374            }
4375            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4376                final PackageSetting ps = mSettings.mPackages.get(packageName);
4377                if (ps != null && ps.isMatch(flags)
4378                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4379                    return ps.getPermissionsState().computeGids(userId);
4380                }
4381            }
4382        }
4383
4384        return null;
4385    }
4386
4387    @Override
4388    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4389        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4390    }
4391
4392    @Override
4393    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4394            int flags) {
4395        final List<PermissionInfo> permissionList =
4396                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4397        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4398    }
4399
4400    @Override
4401    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4402        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4403    }
4404
4405    @Override
4406    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4407        final List<PermissionGroupInfo> permissionList =
4408                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4409        return (permissionList == null)
4410                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4411    }
4412
4413    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4414            int filterCallingUid, int userId) {
4415        if (!sUserManager.exists(userId)) return null;
4416        PackageSetting ps = mSettings.mPackages.get(packageName);
4417        if (ps != null) {
4418            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4419                return null;
4420            }
4421            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4422                return null;
4423            }
4424            if (ps.pkg == null) {
4425                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4426                if (pInfo != null) {
4427                    return pInfo.applicationInfo;
4428                }
4429                return null;
4430            }
4431            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4432                    ps.readUserState(userId), userId);
4433            if (ai != null) {
4434                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4435            }
4436            return ai;
4437        }
4438        return null;
4439    }
4440
4441    @Override
4442    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4443        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4444    }
4445
4446    /**
4447     * Important: The provided filterCallingUid is used exclusively to filter out applications
4448     * that can be seen based on user state. It's typically the original caller uid prior
4449     * to clearing. Because it can only be provided by trusted code, it's value can be
4450     * trusted and will be used as-is; unlike userId which will be validated by this method.
4451     */
4452    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4453            int filterCallingUid, int userId) {
4454        if (!sUserManager.exists(userId)) return null;
4455        flags = updateFlagsForApplication(flags, userId, packageName);
4456        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4457                false /* requireFullPermission */, false /* checkShell */, "get application info");
4458
4459        // writer
4460        synchronized (mPackages) {
4461            // Normalize package name to handle renamed packages and static libs
4462            packageName = resolveInternalPackageNameLPr(packageName,
4463                    PackageManager.VERSION_CODE_HIGHEST);
4464
4465            PackageParser.Package p = mPackages.get(packageName);
4466            if (DEBUG_PACKAGE_INFO) Log.v(
4467                    TAG, "getApplicationInfo " + packageName
4468                    + ": " + p);
4469            if (p != null) {
4470                PackageSetting ps = mSettings.mPackages.get(packageName);
4471                if (ps == null) return null;
4472                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4473                    return null;
4474                }
4475                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4476                    return null;
4477                }
4478                // Note: isEnabledLP() does not apply here - always return info
4479                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4480                        p, flags, ps.readUserState(userId), userId);
4481                if (ai != null) {
4482                    ai.packageName = resolveExternalPackageNameLPr(p);
4483                }
4484                return ai;
4485            }
4486            if ("android".equals(packageName)||"system".equals(packageName)) {
4487                return mAndroidApplication;
4488            }
4489            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4490                // Already generates the external package name
4491                return generateApplicationInfoFromSettingsLPw(packageName,
4492                        flags, filterCallingUid, userId);
4493            }
4494        }
4495        return null;
4496    }
4497
4498    private String normalizePackageNameLPr(String packageName) {
4499        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4500        return normalizedPackageName != null ? normalizedPackageName : packageName;
4501    }
4502
4503    @Override
4504    public void deletePreloadsFileCache() {
4505        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4506            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4507        }
4508        File dir = Environment.getDataPreloadsFileCacheDirectory();
4509        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4510        FileUtils.deleteContents(dir);
4511    }
4512
4513    @Override
4514    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4515            final int storageFlags, final IPackageDataObserver observer) {
4516        mContext.enforceCallingOrSelfPermission(
4517                android.Manifest.permission.CLEAR_APP_CACHE, null);
4518        mHandler.post(() -> {
4519            boolean success = false;
4520            try {
4521                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4522                success = true;
4523            } catch (IOException e) {
4524                Slog.w(TAG, e);
4525            }
4526            if (observer != null) {
4527                try {
4528                    observer.onRemoveCompleted(null, success);
4529                } catch (RemoteException e) {
4530                    Slog.w(TAG, e);
4531                }
4532            }
4533        });
4534    }
4535
4536    @Override
4537    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4538            final int storageFlags, final IntentSender pi) {
4539        mContext.enforceCallingOrSelfPermission(
4540                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4541        mHandler.post(() -> {
4542            boolean success = false;
4543            try {
4544                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4545                success = true;
4546            } catch (IOException e) {
4547                Slog.w(TAG, e);
4548            }
4549            if (pi != null) {
4550                try {
4551                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4552                } catch (SendIntentException e) {
4553                    Slog.w(TAG, e);
4554                }
4555            }
4556        });
4557    }
4558
4559    /**
4560     * Blocking call to clear various types of cached data across the system
4561     * until the requested bytes are available.
4562     */
4563    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4564        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4565        final File file = storage.findPathForUuid(volumeUuid);
4566        if (file.getUsableSpace() >= bytes) return;
4567
4568        if (ENABLE_FREE_CACHE_V2) {
4569            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4570                    volumeUuid);
4571            final boolean aggressive = (storageFlags
4572                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4573            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4574
4575            // 1. Pre-flight to determine if we have any chance to succeed
4576            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4577            if (internalVolume && (aggressive || SystemProperties
4578                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4579                deletePreloadsFileCache();
4580                if (file.getUsableSpace() >= bytes) return;
4581            }
4582
4583            // 3. Consider parsed APK data (aggressive only)
4584            if (internalVolume && aggressive) {
4585                FileUtils.deleteContents(mCacheDir);
4586                if (file.getUsableSpace() >= bytes) return;
4587            }
4588
4589            // 4. Consider cached app data (above quotas)
4590            try {
4591                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4592                        Installer.FLAG_FREE_CACHE_V2);
4593            } catch (InstallerException ignored) {
4594            }
4595            if (file.getUsableSpace() >= bytes) return;
4596
4597            // 5. Consider shared libraries with refcount=0 and age>min cache period
4598            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4599                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4600                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4601                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4602                return;
4603            }
4604
4605            // 6. Consider dexopt output (aggressive only)
4606            // TODO: Implement
4607
4608            // 7. Consider installed instant apps unused longer than min cache period
4609            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4610                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4611                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4612                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4613                return;
4614            }
4615
4616            // 8. Consider cached app data (below quotas)
4617            try {
4618                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4619                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4620            } catch (InstallerException ignored) {
4621            }
4622            if (file.getUsableSpace() >= bytes) return;
4623
4624            // 9. Consider DropBox entries
4625            // TODO: Implement
4626
4627            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4628            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4629                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4630                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4631                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4632                return;
4633            }
4634        } else {
4635            try {
4636                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4637            } catch (InstallerException ignored) {
4638            }
4639            if (file.getUsableSpace() >= bytes) return;
4640        }
4641
4642        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4643    }
4644
4645    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4646            throws IOException {
4647        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4648        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4649
4650        List<VersionedPackage> packagesToDelete = null;
4651        final long now = System.currentTimeMillis();
4652
4653        synchronized (mPackages) {
4654            final int[] allUsers = sUserManager.getUserIds();
4655            final int libCount = mSharedLibraries.size();
4656            for (int i = 0; i < libCount; i++) {
4657                final LongSparseArray<SharedLibraryEntry> versionedLib
4658                        = mSharedLibraries.valueAt(i);
4659                if (versionedLib == null) {
4660                    continue;
4661                }
4662                final int versionCount = versionedLib.size();
4663                for (int j = 0; j < versionCount; j++) {
4664                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4665                    // Skip packages that are not static shared libs.
4666                    if (!libInfo.isStatic()) {
4667                        break;
4668                    }
4669                    // Important: We skip static shared libs used for some user since
4670                    // in such a case we need to keep the APK on the device. The check for
4671                    // a lib being used for any user is performed by the uninstall call.
4672                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4673                    // Resolve the package name - we use synthetic package names internally
4674                    final String internalPackageName = resolveInternalPackageNameLPr(
4675                            declaringPackage.getPackageName(),
4676                            declaringPackage.getLongVersionCode());
4677                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4678                    // Skip unused static shared libs cached less than the min period
4679                    // to prevent pruning a lib needed by a subsequently installed package.
4680                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4681                        continue;
4682                    }
4683                    if (packagesToDelete == null) {
4684                        packagesToDelete = new ArrayList<>();
4685                    }
4686                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4687                            declaringPackage.getLongVersionCode()));
4688                }
4689            }
4690        }
4691
4692        if (packagesToDelete != null) {
4693            final int packageCount = packagesToDelete.size();
4694            for (int i = 0; i < packageCount; i++) {
4695                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4696                // Delete the package synchronously (will fail of the lib used for any user).
4697                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4698                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4699                                == PackageManager.DELETE_SUCCEEDED) {
4700                    if (volume.getUsableSpace() >= neededSpace) {
4701                        return true;
4702                    }
4703                }
4704            }
4705        }
4706
4707        return false;
4708    }
4709
4710    /**
4711     * Update given flags based on encryption status of current user.
4712     */
4713    private int updateFlags(int flags, int userId) {
4714        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4715                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4716            // Caller expressed an explicit opinion about what encryption
4717            // aware/unaware components they want to see, so fall through and
4718            // give them what they want
4719        } else {
4720            // Caller expressed no opinion, so match based on user state
4721            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4722                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4723            } else {
4724                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4725            }
4726        }
4727        return flags;
4728    }
4729
4730    private UserManagerInternal getUserManagerInternal() {
4731        if (mUserManagerInternal == null) {
4732            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4733        }
4734        return mUserManagerInternal;
4735    }
4736
4737    private ActivityManagerInternal getActivityManagerInternal() {
4738        if (mActivityManagerInternal == null) {
4739            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4740        }
4741        return mActivityManagerInternal;
4742    }
4743
4744
4745    private DeviceIdleController.LocalService getDeviceIdleController() {
4746        if (mDeviceIdleController == null) {
4747            mDeviceIdleController =
4748                    LocalServices.getService(DeviceIdleController.LocalService.class);
4749        }
4750        return mDeviceIdleController;
4751    }
4752
4753    /**
4754     * Update given flags when being used to request {@link PackageInfo}.
4755     */
4756    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4757        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4758        boolean triaged = true;
4759        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4760                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4761            // Caller is asking for component details, so they'd better be
4762            // asking for specific encryption matching behavior, or be triaged
4763            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4764                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4765                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4766                triaged = false;
4767            }
4768        }
4769        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4770                | PackageManager.MATCH_SYSTEM_ONLY
4771                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4772            triaged = false;
4773        }
4774        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4775            mPermissionManager.enforceCrossUserPermission(
4776                    Binder.getCallingUid(), userId, false, false,
4777                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4778                    + Debug.getCallers(5));
4779        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4780                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4781            // If the caller wants all packages and has a restricted profile associated with it,
4782            // then match all users. This is to make sure that launchers that need to access work
4783            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4784            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4785            flags |= PackageManager.MATCH_ANY_USER;
4786        }
4787        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4788            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4789                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4790        }
4791        return updateFlags(flags, userId);
4792    }
4793
4794    /**
4795     * Update given flags when being used to request {@link ApplicationInfo}.
4796     */
4797    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4798        return updateFlagsForPackage(flags, userId, cookie);
4799    }
4800
4801    /**
4802     * Update given flags when being used to request {@link ComponentInfo}.
4803     */
4804    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4805        if (cookie instanceof Intent) {
4806            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4807                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4808            }
4809        }
4810
4811        boolean triaged = true;
4812        // Caller is asking for component details, so they'd better be
4813        // asking for specific encryption matching behavior, or be triaged
4814        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4815                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4816                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4817            triaged = false;
4818        }
4819        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4820            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4821                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4822        }
4823
4824        return updateFlags(flags, userId);
4825    }
4826
4827    /**
4828     * Update given intent when being used to request {@link ResolveInfo}.
4829     */
4830    private Intent updateIntentForResolve(Intent intent) {
4831        if (intent.getSelector() != null) {
4832            intent = intent.getSelector();
4833        }
4834        if (DEBUG_PREFERRED) {
4835            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4836        }
4837        return intent;
4838    }
4839
4840    /**
4841     * Update given flags when being used to request {@link ResolveInfo}.
4842     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4843     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4844     * flag set. However, this flag is only honoured in three circumstances:
4845     * <ul>
4846     * <li>when called from a system process</li>
4847     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4848     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4849     * action and a {@code android.intent.category.BROWSABLE} category</li>
4850     * </ul>
4851     */
4852    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4853        return updateFlagsForResolve(flags, userId, intent, callingUid,
4854                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4855    }
4856    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4857            boolean wantInstantApps) {
4858        return updateFlagsForResolve(flags, userId, intent, callingUid,
4859                wantInstantApps, false /*onlyExposedExplicitly*/);
4860    }
4861    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4862            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4863        // Safe mode means we shouldn't match any third-party components
4864        if (mSafeMode) {
4865            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4866        }
4867        if (getInstantAppPackageName(callingUid) != null) {
4868            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4869            if (onlyExposedExplicitly) {
4870                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4871            }
4872            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4873            flags |= PackageManager.MATCH_INSTANT;
4874        } else {
4875            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4876            final boolean allowMatchInstant = wantInstantApps
4877                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4878            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4879                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4880            if (!allowMatchInstant) {
4881                flags &= ~PackageManager.MATCH_INSTANT;
4882            }
4883        }
4884        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4885    }
4886
4887    @Override
4888    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4889        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4890    }
4891
4892    /**
4893     * Important: The provided filterCallingUid is used exclusively to filter out activities
4894     * that can be seen based on user state. It's typically the original caller uid prior
4895     * to clearing. Because it can only be provided by trusted code, it's value can be
4896     * trusted and will be used as-is; unlike userId which will be validated by this method.
4897     */
4898    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4899            int filterCallingUid, int userId) {
4900        if (!sUserManager.exists(userId)) return null;
4901        flags = updateFlagsForComponent(flags, userId, component);
4902
4903        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4904            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4905                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4906        }
4907
4908        synchronized (mPackages) {
4909            PackageParser.Activity a = mActivities.mActivities.get(component);
4910
4911            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4912            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4913                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4914                if (ps == null) return null;
4915                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4916                    return null;
4917                }
4918                return PackageParser.generateActivityInfo(
4919                        a, flags, ps.readUserState(userId), userId);
4920            }
4921            if (mResolveComponentName.equals(component)) {
4922                return PackageParser.generateActivityInfo(
4923                        mResolveActivity, flags, new PackageUserState(), userId);
4924            }
4925        }
4926        return null;
4927    }
4928
4929    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4930        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4931            return false;
4932        }
4933        final long token = Binder.clearCallingIdentity();
4934        try {
4935            final int callingUserId = UserHandle.getUserId(callingUid);
4936            if (ActivityManager.getCurrentUser() != callingUserId) {
4937                return false;
4938            }
4939            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4940        } finally {
4941            Binder.restoreCallingIdentity(token);
4942        }
4943    }
4944
4945    @Override
4946    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4947            String resolvedType) {
4948        synchronized (mPackages) {
4949            if (component.equals(mResolveComponentName)) {
4950                // The resolver supports EVERYTHING!
4951                return true;
4952            }
4953            final int callingUid = Binder.getCallingUid();
4954            final int callingUserId = UserHandle.getUserId(callingUid);
4955            PackageParser.Activity a = mActivities.mActivities.get(component);
4956            if (a == null) {
4957                return false;
4958            }
4959            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4960            if (ps == null) {
4961                return false;
4962            }
4963            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4964                return false;
4965            }
4966            for (int i=0; i<a.intents.size(); i++) {
4967                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4968                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4969                    return true;
4970                }
4971            }
4972            return false;
4973        }
4974    }
4975
4976    @Override
4977    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4978        if (!sUserManager.exists(userId)) return null;
4979        final int callingUid = Binder.getCallingUid();
4980        flags = updateFlagsForComponent(flags, userId, component);
4981        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4982                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4983        synchronized (mPackages) {
4984            PackageParser.Activity a = mReceivers.mActivities.get(component);
4985            if (DEBUG_PACKAGE_INFO) Log.v(
4986                TAG, "getReceiverInfo " + component + ": " + a);
4987            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4988                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4989                if (ps == null) return null;
4990                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4991                    return null;
4992                }
4993                return PackageParser.generateActivityInfo(
4994                        a, flags, ps.readUserState(userId), userId);
4995            }
4996        }
4997        return null;
4998    }
4999
5000    @Override
5001    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5002            int flags, int userId) {
5003        if (!sUserManager.exists(userId)) return null;
5004        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5006            return null;
5007        }
5008
5009        flags = updateFlagsForPackage(flags, userId, null);
5010
5011        final boolean canSeeStaticLibraries =
5012                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5013                        == PERMISSION_GRANTED
5014                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5015                        == PERMISSION_GRANTED
5016                || canRequestPackageInstallsInternal(packageName,
5017                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5018                        false  /* throwIfPermNotDeclared*/)
5019                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5020                        == PERMISSION_GRANTED;
5021
5022        synchronized (mPackages) {
5023            List<SharedLibraryInfo> result = null;
5024
5025            final int libCount = mSharedLibraries.size();
5026            for (int i = 0; i < libCount; i++) {
5027                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5028                if (versionedLib == null) {
5029                    continue;
5030                }
5031
5032                final int versionCount = versionedLib.size();
5033                for (int j = 0; j < versionCount; j++) {
5034                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5035                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5036                        break;
5037                    }
5038                    final long identity = Binder.clearCallingIdentity();
5039                    try {
5040                        PackageInfo packageInfo = getPackageInfoVersioned(
5041                                libInfo.getDeclaringPackage(), flags
5042                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5043                        if (packageInfo == null) {
5044                            continue;
5045                        }
5046                    } finally {
5047                        Binder.restoreCallingIdentity(identity);
5048                    }
5049
5050                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5051                            libInfo.getLongVersion(), libInfo.getType(),
5052                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5053                            flags, userId));
5054
5055                    if (result == null) {
5056                        result = new ArrayList<>();
5057                    }
5058                    result.add(resLibInfo);
5059                }
5060            }
5061
5062            return result != null ? new ParceledListSlice<>(result) : null;
5063        }
5064    }
5065
5066    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5067            SharedLibraryInfo libInfo, int flags, int userId) {
5068        List<VersionedPackage> versionedPackages = null;
5069        final int packageCount = mSettings.mPackages.size();
5070        for (int i = 0; i < packageCount; i++) {
5071            PackageSetting ps = mSettings.mPackages.valueAt(i);
5072
5073            if (ps == null) {
5074                continue;
5075            }
5076
5077            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5078                continue;
5079            }
5080
5081            final String libName = libInfo.getName();
5082            if (libInfo.isStatic()) {
5083                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5084                if (libIdx < 0) {
5085                    continue;
5086                }
5087                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5088                    continue;
5089                }
5090                if (versionedPackages == null) {
5091                    versionedPackages = new ArrayList<>();
5092                }
5093                // If the dependent is a static shared lib, use the public package name
5094                String dependentPackageName = ps.name;
5095                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5096                    dependentPackageName = ps.pkg.manifestPackageName;
5097                }
5098                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5099            } else if (ps.pkg != null) {
5100                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5101                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5102                    if (versionedPackages == null) {
5103                        versionedPackages = new ArrayList<>();
5104                    }
5105                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5106                }
5107            }
5108        }
5109
5110        return versionedPackages;
5111    }
5112
5113    @Override
5114    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5115        if (!sUserManager.exists(userId)) return null;
5116        final int callingUid = Binder.getCallingUid();
5117        flags = updateFlagsForComponent(flags, userId, component);
5118        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5119                false /* requireFullPermission */, false /* checkShell */, "get service info");
5120        synchronized (mPackages) {
5121            PackageParser.Service s = mServices.mServices.get(component);
5122            if (DEBUG_PACKAGE_INFO) Log.v(
5123                TAG, "getServiceInfo " + component + ": " + s);
5124            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5125                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5126                if (ps == null) return null;
5127                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5128                    return null;
5129                }
5130                return PackageParser.generateServiceInfo(
5131                        s, flags, ps.readUserState(userId), userId);
5132            }
5133        }
5134        return null;
5135    }
5136
5137    @Override
5138    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5139        if (!sUserManager.exists(userId)) return null;
5140        final int callingUid = Binder.getCallingUid();
5141        flags = updateFlagsForComponent(flags, userId, component);
5142        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5143                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5144        synchronized (mPackages) {
5145            PackageParser.Provider p = mProviders.mProviders.get(component);
5146            if (DEBUG_PACKAGE_INFO) Log.v(
5147                TAG, "getProviderInfo " + component + ": " + p);
5148            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5149                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5150                if (ps == null) return null;
5151                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5152                    return null;
5153                }
5154                return PackageParser.generateProviderInfo(
5155                        p, flags, ps.readUserState(userId), userId);
5156            }
5157        }
5158        return null;
5159    }
5160
5161    @Override
5162    public String[] getSystemSharedLibraryNames() {
5163        // allow instant applications
5164        synchronized (mPackages) {
5165            Set<String> libs = null;
5166            final int libCount = mSharedLibraries.size();
5167            for (int i = 0; i < libCount; i++) {
5168                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5169                if (versionedLib == null) {
5170                    continue;
5171                }
5172                final int versionCount = versionedLib.size();
5173                for (int j = 0; j < versionCount; j++) {
5174                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5175                    if (!libEntry.info.isStatic()) {
5176                        if (libs == null) {
5177                            libs = new ArraySet<>();
5178                        }
5179                        libs.add(libEntry.info.getName());
5180                        break;
5181                    }
5182                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5183                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5184                            UserHandle.getUserId(Binder.getCallingUid()),
5185                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5186                        if (libs == null) {
5187                            libs = new ArraySet<>();
5188                        }
5189                        libs.add(libEntry.info.getName());
5190                        break;
5191                    }
5192                }
5193            }
5194
5195            if (libs != null) {
5196                String[] libsArray = new String[libs.size()];
5197                libs.toArray(libsArray);
5198                return libsArray;
5199            }
5200
5201            return null;
5202        }
5203    }
5204
5205    @Override
5206    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5207        // allow instant applications
5208        synchronized (mPackages) {
5209            return mServicesSystemSharedLibraryPackageName;
5210        }
5211    }
5212
5213    @Override
5214    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5215        // allow instant applications
5216        synchronized (mPackages) {
5217            return mSharedSystemSharedLibraryPackageName;
5218        }
5219    }
5220
5221    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5222        for (int i = userList.length - 1; i >= 0; --i) {
5223            final int userId = userList[i];
5224            // don't add instant app to the list of updates
5225            if (pkgSetting.getInstantApp(userId)) {
5226                continue;
5227            }
5228            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5229            if (changedPackages == null) {
5230                changedPackages = new SparseArray<>();
5231                mChangedPackages.put(userId, changedPackages);
5232            }
5233            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5234            if (sequenceNumbers == null) {
5235                sequenceNumbers = new HashMap<>();
5236                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5237            }
5238            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5239            if (sequenceNumber != null) {
5240                changedPackages.remove(sequenceNumber);
5241            }
5242            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5243            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5244        }
5245        mChangedPackagesSequenceNumber++;
5246    }
5247
5248    @Override
5249    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5250        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5251            return null;
5252        }
5253        synchronized (mPackages) {
5254            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5255                return null;
5256            }
5257            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5258            if (changedPackages == null) {
5259                return null;
5260            }
5261            final List<String> packageNames =
5262                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5263            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5264                final String packageName = changedPackages.get(i);
5265                if (packageName != null) {
5266                    packageNames.add(packageName);
5267                }
5268            }
5269            return packageNames.isEmpty()
5270                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5271        }
5272    }
5273
5274    @Override
5275    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5276        // allow instant applications
5277        ArrayList<FeatureInfo> res;
5278        synchronized (mAvailableFeatures) {
5279            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5280            res.addAll(mAvailableFeatures.values());
5281        }
5282        final FeatureInfo fi = new FeatureInfo();
5283        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5284                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5285        res.add(fi);
5286
5287        return new ParceledListSlice<>(res);
5288    }
5289
5290    @Override
5291    public boolean hasSystemFeature(String name, int version) {
5292        // allow instant applications
5293        synchronized (mAvailableFeatures) {
5294            final FeatureInfo feat = mAvailableFeatures.get(name);
5295            if (feat == null) {
5296                return false;
5297            } else {
5298                return feat.version >= version;
5299            }
5300        }
5301    }
5302
5303    @Override
5304    public int checkPermission(String permName, String pkgName, int userId) {
5305        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5306    }
5307
5308    @Override
5309    public int checkUidPermission(String permName, int uid) {
5310        synchronized (mPackages) {
5311            final String[] packageNames = getPackagesForUid(uid);
5312            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5313                    ? mPackages.get(packageNames[0])
5314                    : null;
5315            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5316        }
5317    }
5318
5319    @Override
5320    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5321        if (UserHandle.getCallingUserId() != userId) {
5322            mContext.enforceCallingPermission(
5323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5324                    "isPermissionRevokedByPolicy for user " + userId);
5325        }
5326
5327        if (checkPermission(permission, packageName, userId)
5328                == PackageManager.PERMISSION_GRANTED) {
5329            return false;
5330        }
5331
5332        final int callingUid = Binder.getCallingUid();
5333        if (getInstantAppPackageName(callingUid) != null) {
5334            if (!isCallerSameApp(packageName, callingUid)) {
5335                return false;
5336            }
5337        } else {
5338            if (isInstantApp(packageName, userId)) {
5339                return false;
5340            }
5341        }
5342
5343        final long identity = Binder.clearCallingIdentity();
5344        try {
5345            final int flags = getPermissionFlags(permission, packageName, userId);
5346            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5347        } finally {
5348            Binder.restoreCallingIdentity(identity);
5349        }
5350    }
5351
5352    @Override
5353    public String getPermissionControllerPackageName() {
5354        synchronized (mPackages) {
5355            return mRequiredInstallerPackage;
5356        }
5357    }
5358
5359    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5360        return mPermissionManager.addDynamicPermission(
5361                info, async, getCallingUid(), new PermissionCallback() {
5362                    @Override
5363                    public void onPermissionChanged() {
5364                        if (!async) {
5365                            mSettings.writeLPr();
5366                        } else {
5367                            scheduleWriteSettingsLocked();
5368                        }
5369                    }
5370                });
5371    }
5372
5373    @Override
5374    public boolean addPermission(PermissionInfo info) {
5375        synchronized (mPackages) {
5376            return addDynamicPermission(info, false);
5377        }
5378    }
5379
5380    @Override
5381    public boolean addPermissionAsync(PermissionInfo info) {
5382        synchronized (mPackages) {
5383            return addDynamicPermission(info, true);
5384        }
5385    }
5386
5387    @Override
5388    public void removePermission(String permName) {
5389        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5390    }
5391
5392    @Override
5393    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5394        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5395                getCallingUid(), userId, mPermissionCallback);
5396    }
5397
5398    @Override
5399    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5400        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5401                getCallingUid(), userId, mPermissionCallback);
5402    }
5403
5404    @Override
5405    public void resetRuntimePermissions() {
5406        mContext.enforceCallingOrSelfPermission(
5407                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5408                "revokeRuntimePermission");
5409
5410        int callingUid = Binder.getCallingUid();
5411        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5412            mContext.enforceCallingOrSelfPermission(
5413                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5414                    "resetRuntimePermissions");
5415        }
5416
5417        synchronized (mPackages) {
5418            mPermissionManager.updateAllPermissions(
5419                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5420                    mPermissionCallback);
5421            for (int userId : UserManagerService.getInstance().getUserIds()) {
5422                final int packageCount = mPackages.size();
5423                for (int i = 0; i < packageCount; i++) {
5424                    PackageParser.Package pkg = mPackages.valueAt(i);
5425                    if (!(pkg.mExtras instanceof PackageSetting)) {
5426                        continue;
5427                    }
5428                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5429                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5430                }
5431            }
5432        }
5433    }
5434
5435    @Override
5436    public int getPermissionFlags(String permName, String packageName, int userId) {
5437        return mPermissionManager.getPermissionFlags(
5438                permName, packageName, getCallingUid(), userId);
5439    }
5440
5441    @Override
5442    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5443            int flagValues, int userId) {
5444        mPermissionManager.updatePermissionFlags(
5445                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5446                mPermissionCallback);
5447    }
5448
5449    /**
5450     * Update the permission flags for all packages and runtime permissions of a user in order
5451     * to allow device or profile owner to remove POLICY_FIXED.
5452     */
5453    @Override
5454    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5455        synchronized (mPackages) {
5456            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5457                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5458                    mPermissionCallback);
5459            if (changed) {
5460                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5461            }
5462        }
5463    }
5464
5465    @Override
5466    public boolean shouldShowRequestPermissionRationale(String permissionName,
5467            String packageName, int userId) {
5468        if (UserHandle.getCallingUserId() != userId) {
5469            mContext.enforceCallingPermission(
5470                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5471                    "canShowRequestPermissionRationale for user " + userId);
5472        }
5473
5474        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5475        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5476            return false;
5477        }
5478
5479        if (checkPermission(permissionName, packageName, userId)
5480                == PackageManager.PERMISSION_GRANTED) {
5481            return false;
5482        }
5483
5484        final int flags;
5485
5486        final long identity = Binder.clearCallingIdentity();
5487        try {
5488            flags = getPermissionFlags(permissionName,
5489                    packageName, userId);
5490        } finally {
5491            Binder.restoreCallingIdentity(identity);
5492        }
5493
5494        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5495                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5496                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5497
5498        if ((flags & fixedFlags) != 0) {
5499            return false;
5500        }
5501
5502        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5503    }
5504
5505    @Override
5506    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5507        mContext.enforceCallingOrSelfPermission(
5508                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5509                "addOnPermissionsChangeListener");
5510
5511        synchronized (mPackages) {
5512            mOnPermissionChangeListeners.addListenerLocked(listener);
5513        }
5514    }
5515
5516    @Override
5517    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5518        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5519            throw new SecurityException("Instant applications don't have access to this method");
5520        }
5521        synchronized (mPackages) {
5522            mOnPermissionChangeListeners.removeListenerLocked(listener);
5523        }
5524    }
5525
5526    @Override
5527    public boolean isProtectedBroadcast(String actionName) {
5528        // allow instant applications
5529        synchronized (mProtectedBroadcasts) {
5530            if (mProtectedBroadcasts.contains(actionName)) {
5531                return true;
5532            } else if (actionName != null) {
5533                // TODO: remove these terrible hacks
5534                if (actionName.startsWith("android.net.netmon.lingerExpired")
5535                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5536                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5537                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5538                    return true;
5539                }
5540            }
5541        }
5542        return false;
5543    }
5544
5545    @Override
5546    public int checkSignatures(String pkg1, String pkg2) {
5547        synchronized (mPackages) {
5548            final PackageParser.Package p1 = mPackages.get(pkg1);
5549            final PackageParser.Package p2 = mPackages.get(pkg2);
5550            if (p1 == null || p1.mExtras == null
5551                    || p2 == null || p2.mExtras == null) {
5552                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5553            }
5554            final int callingUid = Binder.getCallingUid();
5555            final int callingUserId = UserHandle.getUserId(callingUid);
5556            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5557            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5558            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5559                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5560                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5561            }
5562            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5563        }
5564    }
5565
5566    @Override
5567    public int checkUidSignatures(int uid1, int uid2) {
5568        final int callingUid = Binder.getCallingUid();
5569        final int callingUserId = UserHandle.getUserId(callingUid);
5570        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5571        // Map to base uids.
5572        uid1 = UserHandle.getAppId(uid1);
5573        uid2 = UserHandle.getAppId(uid2);
5574        // reader
5575        synchronized (mPackages) {
5576            Signature[] s1;
5577            Signature[] s2;
5578            Object obj = mSettings.getUserIdLPr(uid1);
5579            if (obj != null) {
5580                if (obj instanceof SharedUserSetting) {
5581                    if (isCallerInstantApp) {
5582                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5583                    }
5584                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5585                } else if (obj instanceof PackageSetting) {
5586                    final PackageSetting ps = (PackageSetting) obj;
5587                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5588                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5589                    }
5590                    s1 = ps.signatures.mSigningDetails.signatures;
5591                } else {
5592                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5593                }
5594            } else {
5595                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5596            }
5597            obj = mSettings.getUserIdLPr(uid2);
5598            if (obj != null) {
5599                if (obj instanceof SharedUserSetting) {
5600                    if (isCallerInstantApp) {
5601                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5602                    }
5603                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5604                } else if (obj instanceof PackageSetting) {
5605                    final PackageSetting ps = (PackageSetting) obj;
5606                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5607                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5608                    }
5609                    s2 = ps.signatures.mSigningDetails.signatures;
5610                } else {
5611                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5612                }
5613            } else {
5614                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5615            }
5616            return compareSignatures(s1, s2);
5617        }
5618    }
5619
5620    @Override
5621    public boolean hasSigningCertificate(
5622            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5623
5624        synchronized (mPackages) {
5625            final PackageParser.Package p = mPackages.get(packageName);
5626            if (p == null || p.mExtras == null) {
5627                return false;
5628            }
5629            final int callingUid = Binder.getCallingUid();
5630            final int callingUserId = UserHandle.getUserId(callingUid);
5631            final PackageSetting ps = (PackageSetting) p.mExtras;
5632            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5633                return false;
5634            }
5635            switch (type) {
5636                case CERT_INPUT_RAW_X509:
5637                    return p.mSigningDetails.hasCertificate(certificate);
5638                case CERT_INPUT_SHA256:
5639                    return p.mSigningDetails.hasSha256Certificate(certificate);
5640                default:
5641                    return false;
5642            }
5643        }
5644    }
5645
5646    @Override
5647    public boolean hasUidSigningCertificate(
5648            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5649        final int callingUid = Binder.getCallingUid();
5650        final int callingUserId = UserHandle.getUserId(callingUid);
5651        // Map to base uids.
5652        uid = UserHandle.getAppId(uid);
5653        // reader
5654        synchronized (mPackages) {
5655            final PackageParser.SigningDetails signingDetails;
5656            final Object obj = mSettings.getUserIdLPr(uid);
5657            if (obj != null) {
5658                if (obj instanceof SharedUserSetting) {
5659                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5660                    if (isCallerInstantApp) {
5661                        return false;
5662                    }
5663                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5664                } else if (obj instanceof PackageSetting) {
5665                    final PackageSetting ps = (PackageSetting) obj;
5666                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5667                        return false;
5668                    }
5669                    signingDetails = ps.signatures.mSigningDetails;
5670                } else {
5671                    return false;
5672                }
5673            } else {
5674                return false;
5675            }
5676            switch (type) {
5677                case CERT_INPUT_RAW_X509:
5678                    return signingDetails.hasCertificate(certificate);
5679                case CERT_INPUT_SHA256:
5680                    return signingDetails.hasSha256Certificate(certificate);
5681                default:
5682                    return false;
5683            }
5684        }
5685    }
5686
5687    /**
5688     * This method should typically only be used when granting or revoking
5689     * permissions, since the app may immediately restart after this call.
5690     * <p>
5691     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5692     * guard your work against the app being relaunched.
5693     */
5694    private void killUid(int appId, int userId, String reason) {
5695        final long identity = Binder.clearCallingIdentity();
5696        try {
5697            IActivityManager am = ActivityManager.getService();
5698            if (am != null) {
5699                try {
5700                    am.killUid(appId, userId, reason);
5701                } catch (RemoteException e) {
5702                    /* ignore - same process */
5703                }
5704            }
5705        } finally {
5706            Binder.restoreCallingIdentity(identity);
5707        }
5708    }
5709
5710    /**
5711     * If the database version for this type of package (internal storage or
5712     * external storage) is less than the version where package signatures
5713     * were updated, return true.
5714     */
5715    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5718    }
5719
5720    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5721        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5722        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5723    }
5724
5725    @Override
5726    public List<String> getAllPackages() {
5727        final int callingUid = Binder.getCallingUid();
5728        final int callingUserId = UserHandle.getUserId(callingUid);
5729        synchronized (mPackages) {
5730            if (canViewInstantApps(callingUid, callingUserId)) {
5731                return new ArrayList<String>(mPackages.keySet());
5732            }
5733            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5734            final List<String> result = new ArrayList<>();
5735            if (instantAppPkgName != null) {
5736                // caller is an instant application; filter unexposed applications
5737                for (PackageParser.Package pkg : mPackages.values()) {
5738                    if (!pkg.visibleToInstantApps) {
5739                        continue;
5740                    }
5741                    result.add(pkg.packageName);
5742                }
5743            } else {
5744                // caller is a normal application; filter instant applications
5745                for (PackageParser.Package pkg : mPackages.values()) {
5746                    final PackageSetting ps =
5747                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5748                    if (ps != null
5749                            && ps.getInstantApp(callingUserId)
5750                            && !mInstantAppRegistry.isInstantAccessGranted(
5751                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5752                        continue;
5753                    }
5754                    result.add(pkg.packageName);
5755                }
5756            }
5757            return result;
5758        }
5759    }
5760
5761    @Override
5762    public String[] getPackagesForUid(int uid) {
5763        final int callingUid = Binder.getCallingUid();
5764        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5765        final int userId = UserHandle.getUserId(uid);
5766        uid = UserHandle.getAppId(uid);
5767        // reader
5768        synchronized (mPackages) {
5769            Object obj = mSettings.getUserIdLPr(uid);
5770            if (obj instanceof SharedUserSetting) {
5771                if (isCallerInstantApp) {
5772                    return null;
5773                }
5774                final SharedUserSetting sus = (SharedUserSetting) obj;
5775                final int N = sus.packages.size();
5776                String[] res = new String[N];
5777                final Iterator<PackageSetting> it = sus.packages.iterator();
5778                int i = 0;
5779                while (it.hasNext()) {
5780                    PackageSetting ps = it.next();
5781                    if (ps.getInstalled(userId)) {
5782                        res[i++] = ps.name;
5783                    } else {
5784                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5785                    }
5786                }
5787                return res;
5788            } else if (obj instanceof PackageSetting) {
5789                final PackageSetting ps = (PackageSetting) obj;
5790                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5791                    return new String[]{ps.name};
5792                }
5793            }
5794        }
5795        return null;
5796    }
5797
5798    @Override
5799    public String getNameForUid(int uid) {
5800        final int callingUid = Binder.getCallingUid();
5801        if (getInstantAppPackageName(callingUid) != null) {
5802            return null;
5803        }
5804        synchronized (mPackages) {
5805            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5806            if (obj instanceof SharedUserSetting) {
5807                final SharedUserSetting sus = (SharedUserSetting) obj;
5808                return sus.name + ":" + sus.userId;
5809            } else if (obj instanceof PackageSetting) {
5810                final PackageSetting ps = (PackageSetting) obj;
5811                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5812                    return null;
5813                }
5814                return ps.name;
5815            }
5816            return null;
5817        }
5818    }
5819
5820    @Override
5821    public String[] getNamesForUids(int[] uids) {
5822        if (uids == null || uids.length == 0) {
5823            return null;
5824        }
5825        final int callingUid = Binder.getCallingUid();
5826        if (getInstantAppPackageName(callingUid) != null) {
5827            return null;
5828        }
5829        final String[] names = new String[uids.length];
5830        synchronized (mPackages) {
5831            for (int i = uids.length - 1; i >= 0; i--) {
5832                final int uid = uids[i];
5833                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5834                if (obj instanceof SharedUserSetting) {
5835                    final SharedUserSetting sus = (SharedUserSetting) obj;
5836                    names[i] = "shared:" + sus.name;
5837                } else if (obj instanceof PackageSetting) {
5838                    final PackageSetting ps = (PackageSetting) obj;
5839                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5840                        names[i] = null;
5841                    } else {
5842                        names[i] = ps.name;
5843                    }
5844                } else {
5845                    names[i] = null;
5846                }
5847            }
5848        }
5849        return names;
5850    }
5851
5852    @Override
5853    public int getUidForSharedUser(String sharedUserName) {
5854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5855            return -1;
5856        }
5857        if (sharedUserName == null) {
5858            return -1;
5859        }
5860        // reader
5861        synchronized (mPackages) {
5862            SharedUserSetting suid;
5863            try {
5864                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5865                if (suid != null) {
5866                    return suid.userId;
5867                }
5868            } catch (PackageManagerException ignore) {
5869                // can't happen, but, still need to catch it
5870            }
5871            return -1;
5872        }
5873    }
5874
5875    @Override
5876    public int getFlagsForUid(int uid) {
5877        final int callingUid = Binder.getCallingUid();
5878        if (getInstantAppPackageName(callingUid) != null) {
5879            return 0;
5880        }
5881        synchronized (mPackages) {
5882            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5883            if (obj instanceof SharedUserSetting) {
5884                final SharedUserSetting sus = (SharedUserSetting) obj;
5885                return sus.pkgFlags;
5886            } else if (obj instanceof PackageSetting) {
5887                final PackageSetting ps = (PackageSetting) obj;
5888                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5889                    return 0;
5890                }
5891                return ps.pkgFlags;
5892            }
5893        }
5894        return 0;
5895    }
5896
5897    @Override
5898    public int getPrivateFlagsForUid(int uid) {
5899        final int callingUid = Binder.getCallingUid();
5900        if (getInstantAppPackageName(callingUid) != null) {
5901            return 0;
5902        }
5903        synchronized (mPackages) {
5904            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5905            if (obj instanceof SharedUserSetting) {
5906                final SharedUserSetting sus = (SharedUserSetting) obj;
5907                return sus.pkgPrivateFlags;
5908            } else if (obj instanceof PackageSetting) {
5909                final PackageSetting ps = (PackageSetting) obj;
5910                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5911                    return 0;
5912                }
5913                return ps.pkgPrivateFlags;
5914            }
5915        }
5916        return 0;
5917    }
5918
5919    @Override
5920    public boolean isUidPrivileged(int uid) {
5921        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5922            return false;
5923        }
5924        uid = UserHandle.getAppId(uid);
5925        // reader
5926        synchronized (mPackages) {
5927            Object obj = mSettings.getUserIdLPr(uid);
5928            if (obj instanceof SharedUserSetting) {
5929                final SharedUserSetting sus = (SharedUserSetting) obj;
5930                final Iterator<PackageSetting> it = sus.packages.iterator();
5931                while (it.hasNext()) {
5932                    if (it.next().isPrivileged()) {
5933                        return true;
5934                    }
5935                }
5936            } else if (obj instanceof PackageSetting) {
5937                final PackageSetting ps = (PackageSetting) obj;
5938                return ps.isPrivileged();
5939            }
5940        }
5941        return false;
5942    }
5943
5944    @Override
5945    public String[] getAppOpPermissionPackages(String permName) {
5946        return mPermissionManager.getAppOpPermissionPackages(permName);
5947    }
5948
5949    @Override
5950    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5951            int flags, int userId) {
5952        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5953                Binder.getCallingUid());
5954    }
5955
5956    /**
5957     * Normally instant apps can only be resolved when they're visible to the caller.
5958     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5959     * since we need to allow the system to start any installed application.
5960     */
5961    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5962            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5963        try {
5964            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5965
5966            if (!sUserManager.exists(userId)) return null;
5967            final int callingUid = Binder.getCallingUid();
5968            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5969            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5970                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5971
5972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5973            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5974                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5976
5977            final ResolveInfo bestChoice =
5978                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5979            return bestChoice;
5980        } finally {
5981            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5982        }
5983    }
5984
5985    @Override
5986    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5987        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5988            throw new SecurityException(
5989                    "findPersistentPreferredActivity can only be run by the system");
5990        }
5991        if (!sUserManager.exists(userId)) {
5992            return null;
5993        }
5994        final int callingUid = Binder.getCallingUid();
5995        intent = updateIntentForResolve(intent);
5996        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5997        final int flags = updateFlagsForResolve(
5998                0, userId, intent, callingUid, false /*includeInstantApps*/);
5999        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6000                userId);
6001        synchronized (mPackages) {
6002            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6003                    userId);
6004        }
6005    }
6006
6007    @Override
6008    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6009            IntentFilter filter, int match, ComponentName activity) {
6010        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6011            return;
6012        }
6013        final int userId = UserHandle.getCallingUserId();
6014        if (DEBUG_PREFERRED) {
6015            Log.v(TAG, "setLastChosenActivity intent=" + intent
6016                + " resolvedType=" + resolvedType
6017                + " flags=" + flags
6018                + " filter=" + filter
6019                + " match=" + match
6020                + " activity=" + activity);
6021            filter.dump(new PrintStreamPrinter(System.out), "    ");
6022        }
6023        intent.setComponent(null);
6024        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6025                userId);
6026        // Find any earlier preferred or last chosen entries and nuke them
6027        findPreferredActivity(intent, resolvedType,
6028                flags, query, 0, false, true, false, userId);
6029        // Add the new activity as the last chosen for this filter
6030        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6031                "Setting last chosen");
6032    }
6033
6034    @Override
6035    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6036        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6037            return null;
6038        }
6039        final int userId = UserHandle.getCallingUserId();
6040        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6041        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6042                userId);
6043        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6044                false, false, false, userId);
6045    }
6046
6047    /**
6048     * Returns whether or not instant apps have been disabled remotely.
6049     */
6050    private boolean areWebInstantAppsDisabled() {
6051        return mWebInstantAppsDisabled;
6052    }
6053
6054    private boolean isInstantAppResolutionAllowed(
6055            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6056            boolean skipPackageCheck) {
6057        if (mInstantAppResolverConnection == null) {
6058            return false;
6059        }
6060        if (mInstantAppInstallerActivity == null) {
6061            return false;
6062        }
6063        if (intent.getComponent() != null) {
6064            return false;
6065        }
6066        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6067            return false;
6068        }
6069        if (!skipPackageCheck && intent.getPackage() != null) {
6070            return false;
6071        }
6072        if (!intent.isWebIntent()) {
6073            // for non web intents, we should not resolve externally if an app already exists to
6074            // handle it or if the caller didn't explicitly request it.
6075            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6076                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6077                return false;
6078            }
6079        } else {
6080            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6081                return false;
6082            } else if (areWebInstantAppsDisabled()) {
6083                return false;
6084            }
6085        }
6086        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6087        // Or if there's already an ephemeral app installed that handles the action
6088        synchronized (mPackages) {
6089            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6090            for (int n = 0; n < count; n++) {
6091                final ResolveInfo info = resolvedActivities.get(n);
6092                final String packageName = info.activityInfo.packageName;
6093                final PackageSetting ps = mSettings.mPackages.get(packageName);
6094                if (ps != null) {
6095                    // only check domain verification status if the app is not a browser
6096                    if (!info.handleAllWebDataURI) {
6097                        // Try to get the status from User settings first
6098                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6099                        final int status = (int) (packedStatus >> 32);
6100                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6101                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6102                            if (DEBUG_INSTANT) {
6103                                Slog.v(TAG, "DENY instant app;"
6104                                    + " pkg: " + packageName + ", status: " + status);
6105                            }
6106                            return false;
6107                        }
6108                    }
6109                    if (ps.getInstantApp(userId)) {
6110                        if (DEBUG_INSTANT) {
6111                            Slog.v(TAG, "DENY instant app installed;"
6112                                    + " pkg: " + packageName);
6113                        }
6114                        return false;
6115                    }
6116                }
6117            }
6118        }
6119        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6120        return true;
6121    }
6122
6123    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6124            Intent origIntent, String resolvedType, String callingPackage,
6125            Bundle verificationBundle, int userId) {
6126        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6127                new InstantAppRequest(responseObj, origIntent, resolvedType,
6128                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6129        mHandler.sendMessage(msg);
6130    }
6131
6132    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6133            int flags, List<ResolveInfo> query, int userId) {
6134        if (query != null) {
6135            final int N = query.size();
6136            if (N == 1) {
6137                return query.get(0);
6138            } else if (N > 1) {
6139                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6140                // If there is more than one activity with the same priority,
6141                // then let the user decide between them.
6142                ResolveInfo r0 = query.get(0);
6143                ResolveInfo r1 = query.get(1);
6144                if (DEBUG_INTENT_MATCHING || debug) {
6145                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6146                            + r1.activityInfo.name + "=" + r1.priority);
6147                }
6148                // If the first activity has a higher priority, or a different
6149                // default, then it is always desirable to pick it.
6150                if (r0.priority != r1.priority
6151                        || r0.preferredOrder != r1.preferredOrder
6152                        || r0.isDefault != r1.isDefault) {
6153                    return query.get(0);
6154                }
6155                // If we have saved a preference for a preferred activity for
6156                // this Intent, use that.
6157                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6158                        flags, query, r0.priority, true, false, debug, userId);
6159                if (ri != null) {
6160                    return ri;
6161                }
6162                // If we have an ephemeral app, use it
6163                for (int i = 0; i < N; i++) {
6164                    ri = query.get(i);
6165                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6166                        final String packageName = ri.activityInfo.packageName;
6167                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6168                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6169                        final int status = (int)(packedStatus >> 32);
6170                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6171                            return ri;
6172                        }
6173                    }
6174                }
6175                ri = new ResolveInfo(mResolveInfo);
6176                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6177                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6178                // If all of the options come from the same package, show the application's
6179                // label and icon instead of the generic resolver's.
6180                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6181                // and then throw away the ResolveInfo itself, meaning that the caller loses
6182                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6183                // a fallback for this case; we only set the target package's resources on
6184                // the ResolveInfo, not the ActivityInfo.
6185                final String intentPackage = intent.getPackage();
6186                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6187                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6188                    ri.resolvePackageName = intentPackage;
6189                    if (userNeedsBadging(userId)) {
6190                        ri.noResourceId = true;
6191                    } else {
6192                        ri.icon = appi.icon;
6193                    }
6194                    ri.iconResourceId = appi.icon;
6195                    ri.labelRes = appi.labelRes;
6196                }
6197                ri.activityInfo.applicationInfo = new ApplicationInfo(
6198                        ri.activityInfo.applicationInfo);
6199                if (userId != 0) {
6200                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6201                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6202                }
6203                // Make sure that the resolver is displayable in car mode
6204                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6205                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6206                return ri;
6207            }
6208        }
6209        return null;
6210    }
6211
6212    /**
6213     * Return true if the given list is not empty and all of its contents have
6214     * an activityInfo with the given package name.
6215     */
6216    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6217        if (ArrayUtils.isEmpty(list)) {
6218            return false;
6219        }
6220        for (int i = 0, N = list.size(); i < N; i++) {
6221            final ResolveInfo ri = list.get(i);
6222            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6223            if (ai == null || !packageName.equals(ai.packageName)) {
6224                return false;
6225            }
6226        }
6227        return true;
6228    }
6229
6230    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6231            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6232        final int N = query.size();
6233        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6234                .get(userId);
6235        // Get the list of persistent preferred activities that handle the intent
6236        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6237        List<PersistentPreferredActivity> pprefs = ppir != null
6238                ? ppir.queryIntent(intent, resolvedType,
6239                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6240                        userId)
6241                : null;
6242        if (pprefs != null && pprefs.size() > 0) {
6243            final int M = pprefs.size();
6244            for (int i=0; i<M; i++) {
6245                final PersistentPreferredActivity ppa = pprefs.get(i);
6246                if (DEBUG_PREFERRED || debug) {
6247                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6248                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6249                            + "\n  component=" + ppa.mComponent);
6250                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6251                }
6252                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6253                        flags | MATCH_DISABLED_COMPONENTS, userId);
6254                if (DEBUG_PREFERRED || debug) {
6255                    Slog.v(TAG, "Found persistent preferred activity:");
6256                    if (ai != null) {
6257                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6258                    } else {
6259                        Slog.v(TAG, "  null");
6260                    }
6261                }
6262                if (ai == null) {
6263                    // This previously registered persistent preferred activity
6264                    // component is no longer known. Ignore it and do NOT remove it.
6265                    continue;
6266                }
6267                for (int j=0; j<N; j++) {
6268                    final ResolveInfo ri = query.get(j);
6269                    if (!ri.activityInfo.applicationInfo.packageName
6270                            .equals(ai.applicationInfo.packageName)) {
6271                        continue;
6272                    }
6273                    if (!ri.activityInfo.name.equals(ai.name)) {
6274                        continue;
6275                    }
6276                    //  Found a persistent preference that can handle the intent.
6277                    if (DEBUG_PREFERRED || debug) {
6278                        Slog.v(TAG, "Returning persistent preferred activity: " +
6279                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6280                    }
6281                    return ri;
6282                }
6283            }
6284        }
6285        return null;
6286    }
6287
6288    // TODO: handle preferred activities missing while user has amnesia
6289    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6290            List<ResolveInfo> query, int priority, boolean always,
6291            boolean removeMatches, boolean debug, int userId) {
6292        if (!sUserManager.exists(userId)) return null;
6293        final int callingUid = Binder.getCallingUid();
6294        flags = updateFlagsForResolve(
6295                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6296        intent = updateIntentForResolve(intent);
6297        // writer
6298        synchronized (mPackages) {
6299            // Try to find a matching persistent preferred activity.
6300            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6301                    debug, userId);
6302
6303            // If a persistent preferred activity matched, use it.
6304            if (pri != null) {
6305                return pri;
6306            }
6307
6308            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6309            // Get the list of preferred activities that handle the intent
6310            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6311            List<PreferredActivity> prefs = pir != null
6312                    ? pir.queryIntent(intent, resolvedType,
6313                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6314                            userId)
6315                    : null;
6316            if (prefs != null && prefs.size() > 0) {
6317                boolean changed = false;
6318                try {
6319                    // First figure out how good the original match set is.
6320                    // We will only allow preferred activities that came
6321                    // from the same match quality.
6322                    int match = 0;
6323
6324                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6325
6326                    final int N = query.size();
6327                    for (int j=0; j<N; j++) {
6328                        final ResolveInfo ri = query.get(j);
6329                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6330                                + ": 0x" + Integer.toHexString(match));
6331                        if (ri.match > match) {
6332                            match = ri.match;
6333                        }
6334                    }
6335
6336                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6337                            + Integer.toHexString(match));
6338
6339                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6340                    final int M = prefs.size();
6341                    for (int i=0; i<M; i++) {
6342                        final PreferredActivity pa = prefs.get(i);
6343                        if (DEBUG_PREFERRED || debug) {
6344                            Slog.v(TAG, "Checking PreferredActivity ds="
6345                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6346                                    + "\n  component=" + pa.mPref.mComponent);
6347                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6348                        }
6349                        if (pa.mPref.mMatch != match) {
6350                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6351                                    + Integer.toHexString(pa.mPref.mMatch));
6352                            continue;
6353                        }
6354                        // If it's not an "always" type preferred activity and that's what we're
6355                        // looking for, skip it.
6356                        if (always && !pa.mPref.mAlways) {
6357                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6358                            continue;
6359                        }
6360                        final ActivityInfo ai = getActivityInfo(
6361                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6362                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6363                                userId);
6364                        if (DEBUG_PREFERRED || debug) {
6365                            Slog.v(TAG, "Found preferred activity:");
6366                            if (ai != null) {
6367                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6368                            } else {
6369                                Slog.v(TAG, "  null");
6370                            }
6371                        }
6372                        if (ai == null) {
6373                            // This previously registered preferred activity
6374                            // component is no longer known.  Most likely an update
6375                            // to the app was installed and in the new version this
6376                            // component no longer exists.  Clean it up by removing
6377                            // it from the preferred activities list, and skip it.
6378                            Slog.w(TAG, "Removing dangling preferred activity: "
6379                                    + pa.mPref.mComponent);
6380                            pir.removeFilter(pa);
6381                            changed = true;
6382                            continue;
6383                        }
6384                        for (int j=0; j<N; j++) {
6385                            final ResolveInfo ri = query.get(j);
6386                            if (!ri.activityInfo.applicationInfo.packageName
6387                                    .equals(ai.applicationInfo.packageName)) {
6388                                continue;
6389                            }
6390                            if (!ri.activityInfo.name.equals(ai.name)) {
6391                                continue;
6392                            }
6393
6394                            if (removeMatches) {
6395                                pir.removeFilter(pa);
6396                                changed = true;
6397                                if (DEBUG_PREFERRED) {
6398                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6399                                }
6400                                break;
6401                            }
6402
6403                            // Okay we found a previously set preferred or last chosen app.
6404                            // If the result set is different from when this
6405                            // was created, and is not a subset of the preferred set, we need to
6406                            // clear it and re-ask the user their preference, if we're looking for
6407                            // an "always" type entry.
6408                            if (always && !pa.mPref.sameSet(query)) {
6409                                if (pa.mPref.isSuperset(query)) {
6410                                    // some components of the set are no longer present in
6411                                    // the query, but the preferred activity can still be reused
6412                                    if (DEBUG_PREFERRED) {
6413                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6414                                                + " still valid as only non-preferred components"
6415                                                + " were removed for " + intent + " type "
6416                                                + resolvedType);
6417                                    }
6418                                    // remove obsolete components and re-add the up-to-date filter
6419                                    PreferredActivity freshPa = new PreferredActivity(pa,
6420                                            pa.mPref.mMatch,
6421                                            pa.mPref.discardObsoleteComponents(query),
6422                                            pa.mPref.mComponent,
6423                                            pa.mPref.mAlways);
6424                                    pir.removeFilter(pa);
6425                                    pir.addFilter(freshPa);
6426                                    changed = true;
6427                                } else {
6428                                    Slog.i(TAG,
6429                                            "Result set changed, dropping preferred activity for "
6430                                                    + intent + " type " + resolvedType);
6431                                    if (DEBUG_PREFERRED) {
6432                                        Slog.v(TAG, "Removing preferred activity since set changed "
6433                                                + pa.mPref.mComponent);
6434                                    }
6435                                    pir.removeFilter(pa);
6436                                    // Re-add the filter as a "last chosen" entry (!always)
6437                                    PreferredActivity lastChosen = new PreferredActivity(
6438                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6439                                    pir.addFilter(lastChosen);
6440                                    changed = true;
6441                                    return null;
6442                                }
6443                            }
6444
6445                            // Yay! Either the set matched or we're looking for the last chosen
6446                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6447                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6448                            return ri;
6449                        }
6450                    }
6451                } finally {
6452                    if (changed) {
6453                        if (DEBUG_PREFERRED) {
6454                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6455                        }
6456                        scheduleWritePackageRestrictionsLocked(userId);
6457                    }
6458                }
6459            }
6460        }
6461        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6462        return null;
6463    }
6464
6465    /*
6466     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6467     */
6468    @Override
6469    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6470            int targetUserId) {
6471        mContext.enforceCallingOrSelfPermission(
6472                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6473        List<CrossProfileIntentFilter> matches =
6474                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6475        if (matches != null) {
6476            int size = matches.size();
6477            for (int i = 0; i < size; i++) {
6478                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6479            }
6480        }
6481        if (intent.hasWebURI()) {
6482            // cross-profile app linking works only towards the parent.
6483            final int callingUid = Binder.getCallingUid();
6484            final UserInfo parent = getProfileParent(sourceUserId);
6485            synchronized(mPackages) {
6486                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6487                        false /*includeInstantApps*/);
6488                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6489                        intent, resolvedType, flags, sourceUserId, parent.id);
6490                return xpDomainInfo != null;
6491            }
6492        }
6493        return false;
6494    }
6495
6496    private UserInfo getProfileParent(int userId) {
6497        final long identity = Binder.clearCallingIdentity();
6498        try {
6499            return sUserManager.getProfileParent(userId);
6500        } finally {
6501            Binder.restoreCallingIdentity(identity);
6502        }
6503    }
6504
6505    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6506            String resolvedType, int userId) {
6507        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6508        if (resolver != null) {
6509            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6510        }
6511        return null;
6512    }
6513
6514    @Override
6515    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6516            String resolvedType, int flags, int userId) {
6517        try {
6518            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6519
6520            return new ParceledListSlice<>(
6521                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6522        } finally {
6523            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6524        }
6525    }
6526
6527    /**
6528     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6529     * instant, returns {@code null}.
6530     */
6531    private String getInstantAppPackageName(int callingUid) {
6532        synchronized (mPackages) {
6533            // If the caller is an isolated app use the owner's uid for the lookup.
6534            if (Process.isIsolated(callingUid)) {
6535                callingUid = mIsolatedOwners.get(callingUid);
6536            }
6537            final int appId = UserHandle.getAppId(callingUid);
6538            final Object obj = mSettings.getUserIdLPr(appId);
6539            if (obj instanceof PackageSetting) {
6540                final PackageSetting ps = (PackageSetting) obj;
6541                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6542                return isInstantApp ? ps.pkg.packageName : null;
6543            }
6544        }
6545        return null;
6546    }
6547
6548    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6549            String resolvedType, int flags, int userId) {
6550        return queryIntentActivitiesInternal(
6551                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6552                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6553    }
6554
6555    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6556            String resolvedType, int flags, int filterCallingUid, int userId,
6557            boolean resolveForStart, boolean allowDynamicSplits) {
6558        if (!sUserManager.exists(userId)) return Collections.emptyList();
6559        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6560        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6561                false /* requireFullPermission */, false /* checkShell */,
6562                "query intent activities");
6563        final String pkgName = intent.getPackage();
6564        ComponentName comp = intent.getComponent();
6565        if (comp == null) {
6566            if (intent.getSelector() != null) {
6567                intent = intent.getSelector();
6568                comp = intent.getComponent();
6569            }
6570        }
6571
6572        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6573                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6574        if (comp != null) {
6575            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6576            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6577            if (ai != null) {
6578                // When specifying an explicit component, we prevent the activity from being
6579                // used when either 1) the calling package is normal and the activity is within
6580                // an ephemeral application or 2) the calling package is ephemeral and the
6581                // activity is not visible to ephemeral applications.
6582                final boolean matchInstantApp =
6583                        (flags & PackageManager.MATCH_INSTANT) != 0;
6584                final boolean matchVisibleToInstantAppOnly =
6585                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6586                final boolean matchExplicitlyVisibleOnly =
6587                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6588                final boolean isCallerInstantApp =
6589                        instantAppPkgName != null;
6590                final boolean isTargetSameInstantApp =
6591                        comp.getPackageName().equals(instantAppPkgName);
6592                final boolean isTargetInstantApp =
6593                        (ai.applicationInfo.privateFlags
6594                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6595                final boolean isTargetVisibleToInstantApp =
6596                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6597                final boolean isTargetExplicitlyVisibleToInstantApp =
6598                        isTargetVisibleToInstantApp
6599                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6600                final boolean isTargetHiddenFromInstantApp =
6601                        !isTargetVisibleToInstantApp
6602                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6603                final boolean blockResolution =
6604                        !isTargetSameInstantApp
6605                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6606                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6607                                        && isTargetHiddenFromInstantApp));
6608                if (!blockResolution) {
6609                    final ResolveInfo ri = new ResolveInfo();
6610                    ri.activityInfo = ai;
6611                    list.add(ri);
6612                }
6613            }
6614            return applyPostResolutionFilter(
6615                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6616        }
6617
6618        // reader
6619        boolean sortResult = false;
6620        boolean addInstant = false;
6621        List<ResolveInfo> result;
6622        synchronized (mPackages) {
6623            if (pkgName == null) {
6624                List<CrossProfileIntentFilter> matchingFilters =
6625                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6626                // Check for results that need to skip the current profile.
6627                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6628                        resolvedType, flags, userId);
6629                if (xpResolveInfo != null) {
6630                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6631                    xpResult.add(xpResolveInfo);
6632                    return applyPostResolutionFilter(
6633                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6634                            allowDynamicSplits, filterCallingUid, userId, intent);
6635                }
6636
6637                // Check for results in the current profile.
6638                result = filterIfNotSystemUser(mActivities.queryIntent(
6639                        intent, resolvedType, flags, userId), userId);
6640                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6641                        false /*skipPackageCheck*/);
6642                // Check for cross profile results.
6643                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6644                xpResolveInfo = queryCrossProfileIntents(
6645                        matchingFilters, intent, resolvedType, flags, userId,
6646                        hasNonNegativePriorityResult);
6647                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6648                    boolean isVisibleToUser = filterIfNotSystemUser(
6649                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6650                    if (isVisibleToUser) {
6651                        result.add(xpResolveInfo);
6652                        sortResult = true;
6653                    }
6654                }
6655                if (intent.hasWebURI()) {
6656                    CrossProfileDomainInfo xpDomainInfo = null;
6657                    final UserInfo parent = getProfileParent(userId);
6658                    if (parent != null) {
6659                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6660                                flags, userId, parent.id);
6661                    }
6662                    if (xpDomainInfo != null) {
6663                        if (xpResolveInfo != null) {
6664                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6665                            // in the result.
6666                            result.remove(xpResolveInfo);
6667                        }
6668                        if (result.size() == 0 && !addInstant) {
6669                            // No result in current profile, but found candidate in parent user.
6670                            // And we are not going to add emphemeral app, so we can return the
6671                            // result straight away.
6672                            result.add(xpDomainInfo.resolveInfo);
6673                            return applyPostResolutionFilter(result, instantAppPkgName,
6674                                    allowDynamicSplits, filterCallingUid, userId, intent);
6675                        }
6676                    } else if (result.size() <= 1 && !addInstant) {
6677                        // No result in parent user and <= 1 result in current profile, and we
6678                        // are not going to add emphemeral app, so we can return the result without
6679                        // further processing.
6680                        return applyPostResolutionFilter(result, instantAppPkgName,
6681                                allowDynamicSplits, filterCallingUid, userId, intent);
6682                    }
6683                    // We have more than one candidate (combining results from current and parent
6684                    // profile), so we need filtering and sorting.
6685                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6686                            intent, flags, result, xpDomainInfo, userId);
6687                    sortResult = true;
6688                }
6689            } else {
6690                final PackageParser.Package pkg = mPackages.get(pkgName);
6691                result = null;
6692                if (pkg != null) {
6693                    result = filterIfNotSystemUser(
6694                            mActivities.queryIntentForPackage(
6695                                    intent, resolvedType, flags, pkg.activities, userId),
6696                            userId);
6697                }
6698                if (result == null || result.size() == 0) {
6699                    // the caller wants to resolve for a particular package; however, there
6700                    // were no installed results, so, try to find an ephemeral result
6701                    addInstant = isInstantAppResolutionAllowed(
6702                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6703                    if (result == null) {
6704                        result = new ArrayList<>();
6705                    }
6706                }
6707            }
6708        }
6709        if (addInstant) {
6710            result = maybeAddInstantAppInstaller(
6711                    result, intent, resolvedType, flags, userId, resolveForStart);
6712        }
6713        if (sortResult) {
6714            Collections.sort(result, mResolvePrioritySorter);
6715        }
6716        return applyPostResolutionFilter(
6717                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6718    }
6719
6720    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6721            String resolvedType, int flags, int userId, boolean resolveForStart) {
6722        // first, check to see if we've got an instant app already installed
6723        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6724        ResolveInfo localInstantApp = null;
6725        boolean blockResolution = false;
6726        if (!alreadyResolvedLocally) {
6727            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6728                    flags
6729                        | PackageManager.GET_RESOLVED_FILTER
6730                        | PackageManager.MATCH_INSTANT
6731                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6732                    userId);
6733            for (int i = instantApps.size() - 1; i >= 0; --i) {
6734                final ResolveInfo info = instantApps.get(i);
6735                final String packageName = info.activityInfo.packageName;
6736                final PackageSetting ps = mSettings.mPackages.get(packageName);
6737                if (ps.getInstantApp(userId)) {
6738                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6739                    final int status = (int)(packedStatus >> 32);
6740                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6741                        // there's a local instant application installed, but, the user has
6742                        // chosen to never use it; skip resolution and don't acknowledge
6743                        // an instant application is even available
6744                        if (DEBUG_INSTANT) {
6745                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6746                        }
6747                        blockResolution = true;
6748                        break;
6749                    } else {
6750                        // we have a locally installed instant application; skip resolution
6751                        // but acknowledge there's an instant application available
6752                        if (DEBUG_INSTANT) {
6753                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6754                        }
6755                        localInstantApp = info;
6756                        break;
6757                    }
6758                }
6759            }
6760        }
6761        // no app installed, let's see if one's available
6762        AuxiliaryResolveInfo auxiliaryResponse = null;
6763        if (!blockResolution) {
6764            if (localInstantApp == null) {
6765                // we don't have an instant app locally, resolve externally
6766                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6767                final InstantAppRequest requestObject = new InstantAppRequest(
6768                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6769                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6770                        resolveForStart);
6771                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6772                        mInstantAppResolverConnection, requestObject);
6773                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6774            } else {
6775                // we have an instant application locally, but, we can't admit that since
6776                // callers shouldn't be able to determine prior browsing. create a dummy
6777                // auxiliary response so the downstream code behaves as if there's an
6778                // instant application available externally. when it comes time to start
6779                // the instant application, we'll do the right thing.
6780                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6781                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6782                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6783            }
6784        }
6785        if (intent.isWebIntent() && auxiliaryResponse == null) {
6786            return result;
6787        }
6788        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6789        if (ps == null
6790                || ps.getUserState().get(userId) == null
6791                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6792            return result;
6793        }
6794        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6795        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6796                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6797        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6798                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6799        // add a non-generic filter
6800        ephemeralInstaller.filter = new IntentFilter();
6801        if (intent.getAction() != null) {
6802            ephemeralInstaller.filter.addAction(intent.getAction());
6803        }
6804        if (intent.getData() != null && intent.getData().getPath() != null) {
6805            ephemeralInstaller.filter.addDataPath(
6806                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6807        }
6808        ephemeralInstaller.isInstantAppAvailable = true;
6809        // make sure this resolver is the default
6810        ephemeralInstaller.isDefault = true;
6811        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6812        if (DEBUG_INSTANT) {
6813            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6814        }
6815
6816        result.add(ephemeralInstaller);
6817        return result;
6818    }
6819
6820    private static class CrossProfileDomainInfo {
6821        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6822        ResolveInfo resolveInfo;
6823        /* Best domain verification status of the activities found in the other profile */
6824        int bestDomainVerificationStatus;
6825    }
6826
6827    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6828            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6829        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6830                sourceUserId)) {
6831            return null;
6832        }
6833        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6834                resolvedType, flags, parentUserId);
6835
6836        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6837            return null;
6838        }
6839        CrossProfileDomainInfo result = null;
6840        int size = resultTargetUser.size();
6841        for (int i = 0; i < size; i++) {
6842            ResolveInfo riTargetUser = resultTargetUser.get(i);
6843            // Intent filter verification is only for filters that specify a host. So don't return
6844            // those that handle all web uris.
6845            if (riTargetUser.handleAllWebDataURI) {
6846                continue;
6847            }
6848            String packageName = riTargetUser.activityInfo.packageName;
6849            PackageSetting ps = mSettings.mPackages.get(packageName);
6850            if (ps == null) {
6851                continue;
6852            }
6853            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6854            int status = (int)(verificationState >> 32);
6855            if (result == null) {
6856                result = new CrossProfileDomainInfo();
6857                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6858                        sourceUserId, parentUserId);
6859                result.bestDomainVerificationStatus = status;
6860            } else {
6861                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6862                        result.bestDomainVerificationStatus);
6863            }
6864        }
6865        // Don't consider matches with status NEVER across profiles.
6866        if (result != null && result.bestDomainVerificationStatus
6867                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6868            return null;
6869        }
6870        return result;
6871    }
6872
6873    /**
6874     * Verification statuses are ordered from the worse to the best, except for
6875     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6876     */
6877    private int bestDomainVerificationStatus(int status1, int status2) {
6878        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6879            return status2;
6880        }
6881        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6882            return status1;
6883        }
6884        return (int) MathUtils.max(status1, status2);
6885    }
6886
6887    private boolean isUserEnabled(int userId) {
6888        long callingId = Binder.clearCallingIdentity();
6889        try {
6890            UserInfo userInfo = sUserManager.getUserInfo(userId);
6891            return userInfo != null && userInfo.isEnabled();
6892        } finally {
6893            Binder.restoreCallingIdentity(callingId);
6894        }
6895    }
6896
6897    /**
6898     * Filter out activities with systemUserOnly flag set, when current user is not System.
6899     *
6900     * @return filtered list
6901     */
6902    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6903        if (userId == UserHandle.USER_SYSTEM) {
6904            return resolveInfos;
6905        }
6906        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6907            ResolveInfo info = resolveInfos.get(i);
6908            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6909                resolveInfos.remove(i);
6910            }
6911        }
6912        return resolveInfos;
6913    }
6914
6915    /**
6916     * Filters out ephemeral activities.
6917     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6918     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6919     *
6920     * @param resolveInfos The pre-filtered list of resolved activities
6921     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6922     *          is performed.
6923     * @param intent
6924     * @return A filtered list of resolved activities.
6925     */
6926    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6927            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6928            Intent intent) {
6929        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6930        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6931            final ResolveInfo info = resolveInfos.get(i);
6932            // remove locally resolved instant app web results when disabled
6933            if (info.isInstantAppAvailable && blockInstant) {
6934                resolveInfos.remove(i);
6935                continue;
6936            }
6937            // allow activities that are defined in the provided package
6938            if (allowDynamicSplits
6939                    && info.activityInfo != null
6940                    && info.activityInfo.splitName != null
6941                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6942                            info.activityInfo.splitName)) {
6943                if (mInstantAppInstallerActivity == null) {
6944                    if (DEBUG_INSTALL) {
6945                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6946                    }
6947                    resolveInfos.remove(i);
6948                    continue;
6949                }
6950                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6951                    resolveInfos.remove(i);
6952                    continue;
6953                }
6954                // requested activity is defined in a split that hasn't been installed yet.
6955                // add the installer to the resolve list
6956                if (DEBUG_INSTALL) {
6957                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6958                }
6959                final ResolveInfo installerInfo = new ResolveInfo(
6960                        mInstantAppInstallerInfo);
6961                final ComponentName installFailureActivity = findInstallFailureActivity(
6962                        info.activityInfo.packageName,  filterCallingUid, userId);
6963                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6964                        installFailureActivity,
6965                        info.activityInfo.packageName,
6966                        info.activityInfo.applicationInfo.longVersionCode,
6967                        info.activityInfo.splitName);
6968                // add a non-generic filter
6969                installerInfo.filter = new IntentFilter();
6970
6971                // This resolve info may appear in the chooser UI, so let us make it
6972                // look as the one it replaces as far as the user is concerned which
6973                // requires loading the correct label and icon for the resolve info.
6974                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6975                installerInfo.labelRes = info.resolveLabelResId();
6976                installerInfo.icon = info.resolveIconResId();
6977                installerInfo.isInstantAppAvailable = true;
6978                resolveInfos.set(i, installerInfo);
6979                continue;
6980            }
6981            // caller is a full app, don't need to apply any other filtering
6982            if (ephemeralPkgName == null) {
6983                continue;
6984            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6985                // caller is same app; don't need to apply any other filtering
6986                continue;
6987            }
6988            // allow activities that have been explicitly exposed to ephemeral apps
6989            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6990            if (!isEphemeralApp
6991                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6992                continue;
6993            }
6994            resolveInfos.remove(i);
6995        }
6996        return resolveInfos;
6997    }
6998
6999    /**
7000     * Returns the activity component that can handle install failures.
7001     * <p>By default, the instant application installer handles failures. However, an
7002     * application may want to handle failures on its own. Applications do this by
7003     * creating an activity with an intent filter that handles the action
7004     * {@link Intent#ACTION_INSTALL_FAILURE}.
7005     */
7006    private @Nullable ComponentName findInstallFailureActivity(
7007            String packageName, int filterCallingUid, int userId) {
7008        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7009        failureActivityIntent.setPackage(packageName);
7010        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7011        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7012                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7013                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7014        final int NR = result.size();
7015        if (NR > 0) {
7016            for (int i = 0; i < NR; i++) {
7017                final ResolveInfo info = result.get(i);
7018                if (info.activityInfo.splitName != null) {
7019                    continue;
7020                }
7021                return new ComponentName(packageName, info.activityInfo.name);
7022            }
7023        }
7024        return null;
7025    }
7026
7027    /**
7028     * @param resolveInfos list of resolve infos in descending priority order
7029     * @return if the list contains a resolve info with non-negative priority
7030     */
7031    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7032        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7033    }
7034
7035    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7036            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7037            int userId) {
7038        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7039
7040        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7041            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7042                    candidates.size());
7043        }
7044
7045        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7046        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7047        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7048        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7049        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7050        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7051
7052        synchronized (mPackages) {
7053            final int count = candidates.size();
7054            // First, try to use linked apps. Partition the candidates into four lists:
7055            // one for the final results, one for the "do not use ever", one for "undefined status"
7056            // and finally one for "browser app type".
7057            for (int n=0; n<count; n++) {
7058                ResolveInfo info = candidates.get(n);
7059                String packageName = info.activityInfo.packageName;
7060                PackageSetting ps = mSettings.mPackages.get(packageName);
7061                if (ps != null) {
7062                    // Add to the special match all list (Browser use case)
7063                    if (info.handleAllWebDataURI) {
7064                        matchAllList.add(info);
7065                        continue;
7066                    }
7067                    // Try to get the status from User settings first
7068                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7069                    int status = (int)(packedStatus >> 32);
7070                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7071                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7072                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7073                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7074                                    + " : linkgen=" + linkGeneration);
7075                        }
7076                        // Use link-enabled generation as preferredOrder, i.e.
7077                        // prefer newly-enabled over earlier-enabled.
7078                        info.preferredOrder = linkGeneration;
7079                        alwaysList.add(info);
7080                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7081                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7082                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7083                        }
7084                        neverList.add(info);
7085                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7086                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7087                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7088                        }
7089                        alwaysAskList.add(info);
7090                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7091                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7092                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7093                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7094                        }
7095                        undefinedList.add(info);
7096                    }
7097                }
7098            }
7099
7100            // We'll want to include browser possibilities in a few cases
7101            boolean includeBrowser = false;
7102
7103            // First try to add the "always" resolution(s) for the current user, if any
7104            if (alwaysList.size() > 0) {
7105                result.addAll(alwaysList);
7106            } else {
7107                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7108                result.addAll(undefinedList);
7109                // Maybe add one for the other profile.
7110                if (xpDomainInfo != null && (
7111                        xpDomainInfo.bestDomainVerificationStatus
7112                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7113                    result.add(xpDomainInfo.resolveInfo);
7114                }
7115                includeBrowser = true;
7116            }
7117
7118            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7119            // If there were 'always' entries their preferred order has been set, so we also
7120            // back that off to make the alternatives equivalent
7121            if (alwaysAskList.size() > 0) {
7122                for (ResolveInfo i : result) {
7123                    i.preferredOrder = 0;
7124                }
7125                result.addAll(alwaysAskList);
7126                includeBrowser = true;
7127            }
7128
7129            if (includeBrowser) {
7130                // Also add browsers (all of them or only the default one)
7131                if (DEBUG_DOMAIN_VERIFICATION) {
7132                    Slog.v(TAG, "   ...including browsers in candidate set");
7133                }
7134                if ((matchFlags & MATCH_ALL) != 0) {
7135                    result.addAll(matchAllList);
7136                } else {
7137                    // Browser/generic handling case.  If there's a default browser, go straight
7138                    // to that (but only if there is no other higher-priority match).
7139                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7140                    int maxMatchPrio = 0;
7141                    ResolveInfo defaultBrowserMatch = null;
7142                    final int numCandidates = matchAllList.size();
7143                    for (int n = 0; n < numCandidates; n++) {
7144                        ResolveInfo info = matchAllList.get(n);
7145                        // track the highest overall match priority...
7146                        if (info.priority > maxMatchPrio) {
7147                            maxMatchPrio = info.priority;
7148                        }
7149                        // ...and the highest-priority default browser match
7150                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7151                            if (defaultBrowserMatch == null
7152                                    || (defaultBrowserMatch.priority < info.priority)) {
7153                                if (debug) {
7154                                    Slog.v(TAG, "Considering default browser match " + info);
7155                                }
7156                                defaultBrowserMatch = info;
7157                            }
7158                        }
7159                    }
7160                    if (defaultBrowserMatch != null
7161                            && defaultBrowserMatch.priority >= maxMatchPrio
7162                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7163                    {
7164                        if (debug) {
7165                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7166                        }
7167                        result.add(defaultBrowserMatch);
7168                    } else {
7169                        result.addAll(matchAllList);
7170                    }
7171                }
7172
7173                // If there is nothing selected, add all candidates and remove the ones that the user
7174                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7175                if (result.size() == 0) {
7176                    result.addAll(candidates);
7177                    result.removeAll(neverList);
7178                }
7179            }
7180        }
7181        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7182            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7183                    result.size());
7184            for (ResolveInfo info : result) {
7185                Slog.v(TAG, "  + " + info.activityInfo);
7186            }
7187        }
7188        return result;
7189    }
7190
7191    // Returns a packed value as a long:
7192    //
7193    // high 'int'-sized word: link status: undefined/ask/never/always.
7194    // low 'int'-sized word: relative priority among 'always' results.
7195    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7196        long result = ps.getDomainVerificationStatusForUser(userId);
7197        // if none available, get the master status
7198        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7199            if (ps.getIntentFilterVerificationInfo() != null) {
7200                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7201            }
7202        }
7203        return result;
7204    }
7205
7206    private ResolveInfo querySkipCurrentProfileIntents(
7207            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7208            int flags, int sourceUserId) {
7209        if (matchingFilters != null) {
7210            int size = matchingFilters.size();
7211            for (int i = 0; i < size; i ++) {
7212                CrossProfileIntentFilter filter = matchingFilters.get(i);
7213                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7214                    // Checking if there are activities in the target user that can handle the
7215                    // intent.
7216                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7217                            resolvedType, flags, sourceUserId);
7218                    if (resolveInfo != null) {
7219                        return resolveInfo;
7220                    }
7221                }
7222            }
7223        }
7224        return null;
7225    }
7226
7227    // Return matching ResolveInfo in target user if any.
7228    private ResolveInfo queryCrossProfileIntents(
7229            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7230            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7231        if (matchingFilters != null) {
7232            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7233            // match the same intent. For performance reasons, it is better not to
7234            // run queryIntent twice for the same userId
7235            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7236            int size = matchingFilters.size();
7237            for (int i = 0; i < size; i++) {
7238                CrossProfileIntentFilter filter = matchingFilters.get(i);
7239                int targetUserId = filter.getTargetUserId();
7240                boolean skipCurrentProfile =
7241                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7242                boolean skipCurrentProfileIfNoMatchFound =
7243                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7244                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7245                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7246                    // Checking if there are activities in the target user that can handle the
7247                    // intent.
7248                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7249                            resolvedType, flags, sourceUserId);
7250                    if (resolveInfo != null) return resolveInfo;
7251                    alreadyTriedUserIds.put(targetUserId, true);
7252                }
7253            }
7254        }
7255        return null;
7256    }
7257
7258    /**
7259     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7260     * will forward the intent to the filter's target user.
7261     * Otherwise, returns null.
7262     */
7263    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7264            String resolvedType, int flags, int sourceUserId) {
7265        int targetUserId = filter.getTargetUserId();
7266        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7267                resolvedType, flags, targetUserId);
7268        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7269            // If all the matches in the target profile are suspended, return null.
7270            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7271                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7272                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7273                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7274                            targetUserId);
7275                }
7276            }
7277        }
7278        return null;
7279    }
7280
7281    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7282            int sourceUserId, int targetUserId) {
7283        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7284        long ident = Binder.clearCallingIdentity();
7285        boolean targetIsProfile;
7286        try {
7287            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7288        } finally {
7289            Binder.restoreCallingIdentity(ident);
7290        }
7291        String className;
7292        if (targetIsProfile) {
7293            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7294        } else {
7295            className = FORWARD_INTENT_TO_PARENT;
7296        }
7297        ComponentName forwardingActivityComponentName = new ComponentName(
7298                mAndroidApplication.packageName, className);
7299        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7300                sourceUserId);
7301        if (!targetIsProfile) {
7302            forwardingActivityInfo.showUserIcon = targetUserId;
7303            forwardingResolveInfo.noResourceId = true;
7304        }
7305        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7306        forwardingResolveInfo.priority = 0;
7307        forwardingResolveInfo.preferredOrder = 0;
7308        forwardingResolveInfo.match = 0;
7309        forwardingResolveInfo.isDefault = true;
7310        forwardingResolveInfo.filter = filter;
7311        forwardingResolveInfo.targetUserId = targetUserId;
7312        return forwardingResolveInfo;
7313    }
7314
7315    @Override
7316    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7317            Intent[] specifics, String[] specificTypes, Intent intent,
7318            String resolvedType, int flags, int userId) {
7319        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7320                specificTypes, intent, resolvedType, flags, userId));
7321    }
7322
7323    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7324            Intent[] specifics, String[] specificTypes, Intent intent,
7325            String resolvedType, int flags, int userId) {
7326        if (!sUserManager.exists(userId)) return Collections.emptyList();
7327        final int callingUid = Binder.getCallingUid();
7328        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7329                false /*includeInstantApps*/);
7330        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7331                false /*requireFullPermission*/, false /*checkShell*/,
7332                "query intent activity options");
7333        final String resultsAction = intent.getAction();
7334
7335        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7336                | PackageManager.GET_RESOLVED_FILTER, userId);
7337
7338        if (DEBUG_INTENT_MATCHING) {
7339            Log.v(TAG, "Query " + intent + ": " + results);
7340        }
7341
7342        int specificsPos = 0;
7343        int N;
7344
7345        // todo: note that the algorithm used here is O(N^2).  This
7346        // isn't a problem in our current environment, but if we start running
7347        // into situations where we have more than 5 or 10 matches then this
7348        // should probably be changed to something smarter...
7349
7350        // First we go through and resolve each of the specific items
7351        // that were supplied, taking care of removing any corresponding
7352        // duplicate items in the generic resolve list.
7353        if (specifics != null) {
7354            for (int i=0; i<specifics.length; i++) {
7355                final Intent sintent = specifics[i];
7356                if (sintent == null) {
7357                    continue;
7358                }
7359
7360                if (DEBUG_INTENT_MATCHING) {
7361                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7362                }
7363
7364                String action = sintent.getAction();
7365                if (resultsAction != null && resultsAction.equals(action)) {
7366                    // If this action was explicitly requested, then don't
7367                    // remove things that have it.
7368                    action = null;
7369                }
7370
7371                ResolveInfo ri = null;
7372                ActivityInfo ai = null;
7373
7374                ComponentName comp = sintent.getComponent();
7375                if (comp == null) {
7376                    ri = resolveIntent(
7377                        sintent,
7378                        specificTypes != null ? specificTypes[i] : null,
7379                            flags, userId);
7380                    if (ri == null) {
7381                        continue;
7382                    }
7383                    if (ri == mResolveInfo) {
7384                        // ACK!  Must do something better with this.
7385                    }
7386                    ai = ri.activityInfo;
7387                    comp = new ComponentName(ai.applicationInfo.packageName,
7388                            ai.name);
7389                } else {
7390                    ai = getActivityInfo(comp, flags, userId);
7391                    if (ai == null) {
7392                        continue;
7393                    }
7394                }
7395
7396                // Look for any generic query activities that are duplicates
7397                // of this specific one, and remove them from the results.
7398                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7399                N = results.size();
7400                int j;
7401                for (j=specificsPos; j<N; j++) {
7402                    ResolveInfo sri = results.get(j);
7403                    if ((sri.activityInfo.name.equals(comp.getClassName())
7404                            && sri.activityInfo.applicationInfo.packageName.equals(
7405                                    comp.getPackageName()))
7406                        || (action != null && sri.filter.matchAction(action))) {
7407                        results.remove(j);
7408                        if (DEBUG_INTENT_MATCHING) Log.v(
7409                            TAG, "Removing duplicate item from " + j
7410                            + " due to specific " + specificsPos);
7411                        if (ri == null) {
7412                            ri = sri;
7413                        }
7414                        j--;
7415                        N--;
7416                    }
7417                }
7418
7419                // Add this specific item to its proper place.
7420                if (ri == null) {
7421                    ri = new ResolveInfo();
7422                    ri.activityInfo = ai;
7423                }
7424                results.add(specificsPos, ri);
7425                ri.specificIndex = i;
7426                specificsPos++;
7427            }
7428        }
7429
7430        // Now we go through the remaining generic results and remove any
7431        // duplicate actions that are found here.
7432        N = results.size();
7433        for (int i=specificsPos; i<N-1; i++) {
7434            final ResolveInfo rii = results.get(i);
7435            if (rii.filter == null) {
7436                continue;
7437            }
7438
7439            // Iterate over all of the actions of this result's intent
7440            // filter...  typically this should be just one.
7441            final Iterator<String> it = rii.filter.actionsIterator();
7442            if (it == null) {
7443                continue;
7444            }
7445            while (it.hasNext()) {
7446                final String action = it.next();
7447                if (resultsAction != null && resultsAction.equals(action)) {
7448                    // If this action was explicitly requested, then don't
7449                    // remove things that have it.
7450                    continue;
7451                }
7452                for (int j=i+1; j<N; j++) {
7453                    final ResolveInfo rij = results.get(j);
7454                    if (rij.filter != null && rij.filter.hasAction(action)) {
7455                        results.remove(j);
7456                        if (DEBUG_INTENT_MATCHING) Log.v(
7457                            TAG, "Removing duplicate item from " + j
7458                            + " due to action " + action + " at " + i);
7459                        j--;
7460                        N--;
7461                    }
7462                }
7463            }
7464
7465            // If the caller didn't request filter information, drop it now
7466            // so we don't have to marshall/unmarshall it.
7467            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7468                rii.filter = null;
7469            }
7470        }
7471
7472        // Filter out the caller activity if so requested.
7473        if (caller != null) {
7474            N = results.size();
7475            for (int i=0; i<N; i++) {
7476                ActivityInfo ainfo = results.get(i).activityInfo;
7477                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7478                        && caller.getClassName().equals(ainfo.name)) {
7479                    results.remove(i);
7480                    break;
7481                }
7482            }
7483        }
7484
7485        // If the caller didn't request filter information,
7486        // drop them now so we don't have to
7487        // marshall/unmarshall it.
7488        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7489            N = results.size();
7490            for (int i=0; i<N; i++) {
7491                results.get(i).filter = null;
7492            }
7493        }
7494
7495        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7496        return results;
7497    }
7498
7499    @Override
7500    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7501            String resolvedType, int flags, int userId) {
7502        return new ParceledListSlice<>(
7503                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7504                        false /*allowDynamicSplits*/));
7505    }
7506
7507    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7508            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7509        if (!sUserManager.exists(userId)) return Collections.emptyList();
7510        final int callingUid = Binder.getCallingUid();
7511        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7512                false /*requireFullPermission*/, false /*checkShell*/,
7513                "query intent receivers");
7514        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7515        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7516                false /*includeInstantApps*/);
7517        ComponentName comp = intent.getComponent();
7518        if (comp == null) {
7519            if (intent.getSelector() != null) {
7520                intent = intent.getSelector();
7521                comp = intent.getComponent();
7522            }
7523        }
7524        if (comp != null) {
7525            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7526            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7527            if (ai != null) {
7528                // When specifying an explicit component, we prevent the activity from being
7529                // used when either 1) the calling package is normal and the activity is within
7530                // an instant application or 2) the calling package is ephemeral and the
7531                // activity is not visible to instant applications.
7532                final boolean matchInstantApp =
7533                        (flags & PackageManager.MATCH_INSTANT) != 0;
7534                final boolean matchVisibleToInstantAppOnly =
7535                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7536                final boolean matchExplicitlyVisibleOnly =
7537                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7538                final boolean isCallerInstantApp =
7539                        instantAppPkgName != null;
7540                final boolean isTargetSameInstantApp =
7541                        comp.getPackageName().equals(instantAppPkgName);
7542                final boolean isTargetInstantApp =
7543                        (ai.applicationInfo.privateFlags
7544                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7545                final boolean isTargetVisibleToInstantApp =
7546                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7547                final boolean isTargetExplicitlyVisibleToInstantApp =
7548                        isTargetVisibleToInstantApp
7549                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7550                final boolean isTargetHiddenFromInstantApp =
7551                        !isTargetVisibleToInstantApp
7552                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7553                final boolean blockResolution =
7554                        !isTargetSameInstantApp
7555                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7556                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7557                                        && isTargetHiddenFromInstantApp));
7558                if (!blockResolution) {
7559                    ResolveInfo ri = new ResolveInfo();
7560                    ri.activityInfo = ai;
7561                    list.add(ri);
7562                }
7563            }
7564            return applyPostResolutionFilter(
7565                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7566        }
7567
7568        // reader
7569        synchronized (mPackages) {
7570            String pkgName = intent.getPackage();
7571            if (pkgName == null) {
7572                final List<ResolveInfo> result =
7573                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7574                return applyPostResolutionFilter(
7575                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7576            }
7577            final PackageParser.Package pkg = mPackages.get(pkgName);
7578            if (pkg != null) {
7579                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7580                        intent, resolvedType, flags, pkg.receivers, userId);
7581                return applyPostResolutionFilter(
7582                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7583            }
7584            return Collections.emptyList();
7585        }
7586    }
7587
7588    @Override
7589    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7590        final int callingUid = Binder.getCallingUid();
7591        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7592    }
7593
7594    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7595            int userId, int callingUid) {
7596        if (!sUserManager.exists(userId)) return null;
7597        flags = updateFlagsForResolve(
7598                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7599        List<ResolveInfo> query = queryIntentServicesInternal(
7600                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7601        if (query != null) {
7602            if (query.size() >= 1) {
7603                // If there is more than one service with the same priority,
7604                // just arbitrarily pick the first one.
7605                return query.get(0);
7606            }
7607        }
7608        return null;
7609    }
7610
7611    @Override
7612    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7613            String resolvedType, int flags, int userId) {
7614        final int callingUid = Binder.getCallingUid();
7615        return new ParceledListSlice<>(queryIntentServicesInternal(
7616                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7617    }
7618
7619    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7620            String resolvedType, int flags, int userId, int callingUid,
7621            boolean includeInstantApps) {
7622        if (!sUserManager.exists(userId)) return Collections.emptyList();
7623        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7624                false /*requireFullPermission*/, false /*checkShell*/,
7625                "query intent receivers");
7626        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7627        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7628        ComponentName comp = intent.getComponent();
7629        if (comp == null) {
7630            if (intent.getSelector() != null) {
7631                intent = intent.getSelector();
7632                comp = intent.getComponent();
7633            }
7634        }
7635        if (comp != null) {
7636            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7637            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7638            if (si != null) {
7639                // When specifying an explicit component, we prevent the service from being
7640                // used when either 1) the service is in an instant application and the
7641                // caller is not the same instant application or 2) the calling package is
7642                // ephemeral and the activity is not visible to ephemeral applications.
7643                final boolean matchInstantApp =
7644                        (flags & PackageManager.MATCH_INSTANT) != 0;
7645                final boolean matchVisibleToInstantAppOnly =
7646                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7647                final boolean isCallerInstantApp =
7648                        instantAppPkgName != null;
7649                final boolean isTargetSameInstantApp =
7650                        comp.getPackageName().equals(instantAppPkgName);
7651                final boolean isTargetInstantApp =
7652                        (si.applicationInfo.privateFlags
7653                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7654                final boolean isTargetHiddenFromInstantApp =
7655                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7656                final boolean blockResolution =
7657                        !isTargetSameInstantApp
7658                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7659                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7660                                        && isTargetHiddenFromInstantApp));
7661                if (!blockResolution) {
7662                    final ResolveInfo ri = new ResolveInfo();
7663                    ri.serviceInfo = si;
7664                    list.add(ri);
7665                }
7666            }
7667            return list;
7668        }
7669
7670        // reader
7671        synchronized (mPackages) {
7672            String pkgName = intent.getPackage();
7673            if (pkgName == null) {
7674                return applyPostServiceResolutionFilter(
7675                        mServices.queryIntent(intent, resolvedType, flags, userId),
7676                        instantAppPkgName);
7677            }
7678            final PackageParser.Package pkg = mPackages.get(pkgName);
7679            if (pkg != null) {
7680                return applyPostServiceResolutionFilter(
7681                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7682                                userId),
7683                        instantAppPkgName);
7684            }
7685            return Collections.emptyList();
7686        }
7687    }
7688
7689    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7690            String instantAppPkgName) {
7691        if (instantAppPkgName == null) {
7692            return resolveInfos;
7693        }
7694        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7695            final ResolveInfo info = resolveInfos.get(i);
7696            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7697            // allow services that are defined in the provided package
7698            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7699                if (info.serviceInfo.splitName != null
7700                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7701                                info.serviceInfo.splitName)) {
7702                    // requested service is defined in a split that hasn't been installed yet.
7703                    // add the installer to the resolve list
7704                    if (DEBUG_INSTANT) {
7705                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7706                    }
7707                    final ResolveInfo installerInfo = new ResolveInfo(
7708                            mInstantAppInstallerInfo);
7709                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7710                            null /* installFailureActivity */,
7711                            info.serviceInfo.packageName,
7712                            info.serviceInfo.applicationInfo.longVersionCode,
7713                            info.serviceInfo.splitName);
7714                    // add a non-generic filter
7715                    installerInfo.filter = new IntentFilter();
7716                    // load resources from the correct package
7717                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7718                    resolveInfos.set(i, installerInfo);
7719                }
7720                continue;
7721            }
7722            // allow services that have been explicitly exposed to ephemeral apps
7723            if (!isEphemeralApp
7724                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7725                continue;
7726            }
7727            resolveInfos.remove(i);
7728        }
7729        return resolveInfos;
7730    }
7731
7732    @Override
7733    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7734            String resolvedType, int flags, int userId) {
7735        return new ParceledListSlice<>(
7736                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7737    }
7738
7739    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7740            Intent intent, String resolvedType, int flags, int userId) {
7741        if (!sUserManager.exists(userId)) return Collections.emptyList();
7742        final int callingUid = Binder.getCallingUid();
7743        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7744        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7745                false /*includeInstantApps*/);
7746        ComponentName comp = intent.getComponent();
7747        if (comp == null) {
7748            if (intent.getSelector() != null) {
7749                intent = intent.getSelector();
7750                comp = intent.getComponent();
7751            }
7752        }
7753        if (comp != null) {
7754            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7755            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7756            if (pi != null) {
7757                // When specifying an explicit component, we prevent the provider from being
7758                // used when either 1) the provider is in an instant application and the
7759                // caller is not the same instant application or 2) the calling package is an
7760                // instant application and the provider is not visible to instant applications.
7761                final boolean matchInstantApp =
7762                        (flags & PackageManager.MATCH_INSTANT) != 0;
7763                final boolean matchVisibleToInstantAppOnly =
7764                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7765                final boolean isCallerInstantApp =
7766                        instantAppPkgName != null;
7767                final boolean isTargetSameInstantApp =
7768                        comp.getPackageName().equals(instantAppPkgName);
7769                final boolean isTargetInstantApp =
7770                        (pi.applicationInfo.privateFlags
7771                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7772                final boolean isTargetHiddenFromInstantApp =
7773                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7774                final boolean blockResolution =
7775                        !isTargetSameInstantApp
7776                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7777                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7778                                        && isTargetHiddenFromInstantApp));
7779                if (!blockResolution) {
7780                    final ResolveInfo ri = new ResolveInfo();
7781                    ri.providerInfo = pi;
7782                    list.add(ri);
7783                }
7784            }
7785            return list;
7786        }
7787
7788        // reader
7789        synchronized (mPackages) {
7790            String pkgName = intent.getPackage();
7791            if (pkgName == null) {
7792                return applyPostContentProviderResolutionFilter(
7793                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7794                        instantAppPkgName);
7795            }
7796            final PackageParser.Package pkg = mPackages.get(pkgName);
7797            if (pkg != null) {
7798                return applyPostContentProviderResolutionFilter(
7799                        mProviders.queryIntentForPackage(
7800                        intent, resolvedType, flags, pkg.providers, userId),
7801                        instantAppPkgName);
7802            }
7803            return Collections.emptyList();
7804        }
7805    }
7806
7807    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7808            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7809        if (instantAppPkgName == null) {
7810            return resolveInfos;
7811        }
7812        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7813            final ResolveInfo info = resolveInfos.get(i);
7814            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7815            // allow providers that are defined in the provided package
7816            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7817                if (info.providerInfo.splitName != null
7818                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7819                                info.providerInfo.splitName)) {
7820                    // requested provider is defined in a split that hasn't been installed yet.
7821                    // add the installer to the resolve list
7822                    if (DEBUG_INSTANT) {
7823                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7824                    }
7825                    final ResolveInfo installerInfo = new ResolveInfo(
7826                            mInstantAppInstallerInfo);
7827                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7828                            null /*failureActivity*/,
7829                            info.providerInfo.packageName,
7830                            info.providerInfo.applicationInfo.longVersionCode,
7831                            info.providerInfo.splitName);
7832                    // add a non-generic filter
7833                    installerInfo.filter = new IntentFilter();
7834                    // load resources from the correct package
7835                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7836                    resolveInfos.set(i, installerInfo);
7837                }
7838                continue;
7839            }
7840            // allow providers that have been explicitly exposed to instant applications
7841            if (!isEphemeralApp
7842                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7843                continue;
7844            }
7845            resolveInfos.remove(i);
7846        }
7847        return resolveInfos;
7848    }
7849
7850    @Override
7851    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7852        final int callingUid = Binder.getCallingUid();
7853        if (getInstantAppPackageName(callingUid) != null) {
7854            return ParceledListSlice.emptyList();
7855        }
7856        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7857        flags = updateFlagsForPackage(flags, userId, null);
7858        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7859        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7860                true /* requireFullPermission */, false /* checkShell */,
7861                "get installed packages");
7862
7863        // writer
7864        synchronized (mPackages) {
7865            ArrayList<PackageInfo> list;
7866            if (listUninstalled) {
7867                list = new ArrayList<>(mSettings.mPackages.size());
7868                for (PackageSetting ps : mSettings.mPackages.values()) {
7869                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7870                        continue;
7871                    }
7872                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7873                        continue;
7874                    }
7875                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7876                    if (pi != null) {
7877                        list.add(pi);
7878                    }
7879                }
7880            } else {
7881                list = new ArrayList<>(mPackages.size());
7882                for (PackageParser.Package p : mPackages.values()) {
7883                    final PackageSetting ps = (PackageSetting) p.mExtras;
7884                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7885                        continue;
7886                    }
7887                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7888                        continue;
7889                    }
7890                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7891                            p.mExtras, flags, userId);
7892                    if (pi != null) {
7893                        list.add(pi);
7894                    }
7895                }
7896            }
7897
7898            return new ParceledListSlice<>(list);
7899        }
7900    }
7901
7902    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7903            String[] permissions, boolean[] tmp, int flags, int userId) {
7904        int numMatch = 0;
7905        final PermissionsState permissionsState = ps.getPermissionsState();
7906        for (int i=0; i<permissions.length; i++) {
7907            final String permission = permissions[i];
7908            if (permissionsState.hasPermission(permission, userId)) {
7909                tmp[i] = true;
7910                numMatch++;
7911            } else {
7912                tmp[i] = false;
7913            }
7914        }
7915        if (numMatch == 0) {
7916            return;
7917        }
7918        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7919
7920        // The above might return null in cases of uninstalled apps or install-state
7921        // skew across users/profiles.
7922        if (pi != null) {
7923            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7924                if (numMatch == permissions.length) {
7925                    pi.requestedPermissions = permissions;
7926                } else {
7927                    pi.requestedPermissions = new String[numMatch];
7928                    numMatch = 0;
7929                    for (int i=0; i<permissions.length; i++) {
7930                        if (tmp[i]) {
7931                            pi.requestedPermissions[numMatch] = permissions[i];
7932                            numMatch++;
7933                        }
7934                    }
7935                }
7936            }
7937            list.add(pi);
7938        }
7939    }
7940
7941    @Override
7942    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7943            String[] permissions, int flags, int userId) {
7944        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7945        flags = updateFlagsForPackage(flags, userId, permissions);
7946        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7947                true /* requireFullPermission */, false /* checkShell */,
7948                "get packages holding permissions");
7949        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7950
7951        // writer
7952        synchronized (mPackages) {
7953            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7954            boolean[] tmpBools = new boolean[permissions.length];
7955            if (listUninstalled) {
7956                for (PackageSetting ps : mSettings.mPackages.values()) {
7957                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7958                            userId);
7959                }
7960            } else {
7961                for (PackageParser.Package pkg : mPackages.values()) {
7962                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7963                    if (ps != null) {
7964                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7965                                userId);
7966                    }
7967                }
7968            }
7969
7970            return new ParceledListSlice<PackageInfo>(list);
7971        }
7972    }
7973
7974    @Override
7975    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7976        final int callingUid = Binder.getCallingUid();
7977        if (getInstantAppPackageName(callingUid) != null) {
7978            return ParceledListSlice.emptyList();
7979        }
7980        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7981        flags = updateFlagsForApplication(flags, userId, null);
7982        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7983
7984        // writer
7985        synchronized (mPackages) {
7986            ArrayList<ApplicationInfo> list;
7987            if (listUninstalled) {
7988                list = new ArrayList<>(mSettings.mPackages.size());
7989                for (PackageSetting ps : mSettings.mPackages.values()) {
7990                    ApplicationInfo ai;
7991                    int effectiveFlags = flags;
7992                    if (ps.isSystem()) {
7993                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7994                    }
7995                    if (ps.pkg != null) {
7996                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7997                            continue;
7998                        }
7999                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8000                            continue;
8001                        }
8002                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8003                                ps.readUserState(userId), userId);
8004                        if (ai != null) {
8005                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8006                        }
8007                    } else {
8008                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8009                        // and already converts to externally visible package name
8010                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8011                                callingUid, effectiveFlags, userId);
8012                    }
8013                    if (ai != null) {
8014                        list.add(ai);
8015                    }
8016                }
8017            } else {
8018                list = new ArrayList<>(mPackages.size());
8019                for (PackageParser.Package p : mPackages.values()) {
8020                    if (p.mExtras != null) {
8021                        PackageSetting ps = (PackageSetting) p.mExtras;
8022                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8023                            continue;
8024                        }
8025                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8026                            continue;
8027                        }
8028                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8029                                ps.readUserState(userId), userId);
8030                        if (ai != null) {
8031                            ai.packageName = resolveExternalPackageNameLPr(p);
8032                            list.add(ai);
8033                        }
8034                    }
8035                }
8036            }
8037
8038            return new ParceledListSlice<>(list);
8039        }
8040    }
8041
8042    @Override
8043    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8044        if (HIDE_EPHEMERAL_APIS) {
8045            return null;
8046        }
8047        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8048            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8049                    "getEphemeralApplications");
8050        }
8051        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8052                true /* requireFullPermission */, false /* checkShell */,
8053                "getEphemeralApplications");
8054        synchronized (mPackages) {
8055            List<InstantAppInfo> instantApps = mInstantAppRegistry
8056                    .getInstantAppsLPr(userId);
8057            if (instantApps != null) {
8058                return new ParceledListSlice<>(instantApps);
8059            }
8060        }
8061        return null;
8062    }
8063
8064    @Override
8065    public boolean isInstantApp(String packageName, int userId) {
8066        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8067                true /* requireFullPermission */, false /* checkShell */,
8068                "isInstantApp");
8069        if (HIDE_EPHEMERAL_APIS) {
8070            return false;
8071        }
8072
8073        synchronized (mPackages) {
8074            int callingUid = Binder.getCallingUid();
8075            if (Process.isIsolated(callingUid)) {
8076                callingUid = mIsolatedOwners.get(callingUid);
8077            }
8078            final PackageSetting ps = mSettings.mPackages.get(packageName);
8079            PackageParser.Package pkg = mPackages.get(packageName);
8080            final boolean returnAllowed =
8081                    ps != null
8082                    && (isCallerSameApp(packageName, callingUid)
8083                            || canViewInstantApps(callingUid, userId)
8084                            || mInstantAppRegistry.isInstantAccessGranted(
8085                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8086            if (returnAllowed) {
8087                return ps.getInstantApp(userId);
8088            }
8089        }
8090        return false;
8091    }
8092
8093    @Override
8094    public byte[] getInstantAppCookie(String packageName, int userId) {
8095        if (HIDE_EPHEMERAL_APIS) {
8096            return null;
8097        }
8098
8099        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8100                true /* requireFullPermission */, false /* checkShell */,
8101                "getInstantAppCookie");
8102        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8103            return null;
8104        }
8105        synchronized (mPackages) {
8106            return mInstantAppRegistry.getInstantAppCookieLPw(
8107                    packageName, userId);
8108        }
8109    }
8110
8111    @Override
8112    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8113        if (HIDE_EPHEMERAL_APIS) {
8114            return true;
8115        }
8116
8117        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8118                true /* requireFullPermission */, true /* checkShell */,
8119                "setInstantAppCookie");
8120        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8121            return false;
8122        }
8123        synchronized (mPackages) {
8124            return mInstantAppRegistry.setInstantAppCookieLPw(
8125                    packageName, cookie, userId);
8126        }
8127    }
8128
8129    @Override
8130    public Bitmap getInstantAppIcon(String packageName, int userId) {
8131        if (HIDE_EPHEMERAL_APIS) {
8132            return null;
8133        }
8134
8135        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8136            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8137                    "getInstantAppIcon");
8138        }
8139        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8140                true /* requireFullPermission */, false /* checkShell */,
8141                "getInstantAppIcon");
8142
8143        synchronized (mPackages) {
8144            return mInstantAppRegistry.getInstantAppIconLPw(
8145                    packageName, userId);
8146        }
8147    }
8148
8149    private boolean isCallerSameApp(String packageName, int uid) {
8150        PackageParser.Package pkg = mPackages.get(packageName);
8151        return pkg != null
8152                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8153    }
8154
8155    @Override
8156    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8157        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8158            return ParceledListSlice.emptyList();
8159        }
8160        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8161    }
8162
8163    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8164        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8165
8166        // reader
8167        synchronized (mPackages) {
8168            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8169            final int userId = UserHandle.getCallingUserId();
8170            while (i.hasNext()) {
8171                final PackageParser.Package p = i.next();
8172                if (p.applicationInfo == null) continue;
8173
8174                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8175                        && !p.applicationInfo.isDirectBootAware();
8176                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8177                        && p.applicationInfo.isDirectBootAware();
8178
8179                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8180                        && (!mSafeMode || isSystemApp(p))
8181                        && (matchesUnaware || matchesAware)) {
8182                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8183                    if (ps != null) {
8184                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8185                                ps.readUserState(userId), userId);
8186                        if (ai != null) {
8187                            finalList.add(ai);
8188                        }
8189                    }
8190                }
8191            }
8192        }
8193
8194        return finalList;
8195    }
8196
8197    @Override
8198    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8199        return resolveContentProviderInternal(name, flags, userId);
8200    }
8201
8202    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8203        if (!sUserManager.exists(userId)) return null;
8204        flags = updateFlagsForComponent(flags, userId, name);
8205        final int callingUid = Binder.getCallingUid();
8206        synchronized (mPackages) {
8207            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8208            PackageSetting ps = provider != null
8209                    ? mSettings.mPackages.get(provider.owner.packageName)
8210                    : null;
8211            if (ps != null) {
8212                // provider not enabled
8213                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8214                    return null;
8215                }
8216                final ComponentName component =
8217                        new ComponentName(provider.info.packageName, provider.info.name);
8218                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8219                    return null;
8220                }
8221                return PackageParser.generateProviderInfo(
8222                        provider, flags, ps.readUserState(userId), userId);
8223            }
8224            return null;
8225        }
8226    }
8227
8228    /**
8229     * @deprecated
8230     */
8231    @Deprecated
8232    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8233        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8234            return;
8235        }
8236        // reader
8237        synchronized (mPackages) {
8238            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8239                    .entrySet().iterator();
8240            final int userId = UserHandle.getCallingUserId();
8241            while (i.hasNext()) {
8242                Map.Entry<String, PackageParser.Provider> entry = i.next();
8243                PackageParser.Provider p = entry.getValue();
8244                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8245
8246                if (ps != null && p.syncable
8247                        && (!mSafeMode || (p.info.applicationInfo.flags
8248                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8249                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8250                            ps.readUserState(userId), userId);
8251                    if (info != null) {
8252                        outNames.add(entry.getKey());
8253                        outInfo.add(info);
8254                    }
8255                }
8256            }
8257        }
8258    }
8259
8260    @Override
8261    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8262            int uid, int flags, String metaDataKey) {
8263        final int callingUid = Binder.getCallingUid();
8264        final int userId = processName != null ? UserHandle.getUserId(uid)
8265                : UserHandle.getCallingUserId();
8266        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8267        flags = updateFlagsForComponent(flags, userId, processName);
8268        ArrayList<ProviderInfo> finalList = null;
8269        // reader
8270        synchronized (mPackages) {
8271            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8272            while (i.hasNext()) {
8273                final PackageParser.Provider p = i.next();
8274                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8275                if (ps != null && p.info.authority != null
8276                        && (processName == null
8277                                || (p.info.processName.equals(processName)
8278                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8279                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8280
8281                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8282                    // parameter.
8283                    if (metaDataKey != null
8284                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8285                        continue;
8286                    }
8287                    final ComponentName component =
8288                            new ComponentName(p.info.packageName, p.info.name);
8289                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8290                        continue;
8291                    }
8292                    if (finalList == null) {
8293                        finalList = new ArrayList<ProviderInfo>(3);
8294                    }
8295                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8296                            ps.readUserState(userId), userId);
8297                    if (info != null) {
8298                        finalList.add(info);
8299                    }
8300                }
8301            }
8302        }
8303
8304        if (finalList != null) {
8305            Collections.sort(finalList, mProviderInitOrderSorter);
8306            return new ParceledListSlice<ProviderInfo>(finalList);
8307        }
8308
8309        return ParceledListSlice.emptyList();
8310    }
8311
8312    @Override
8313    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8314        // reader
8315        synchronized (mPackages) {
8316            final int callingUid = Binder.getCallingUid();
8317            final int callingUserId = UserHandle.getUserId(callingUid);
8318            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8319            if (ps == null) return null;
8320            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8321                return null;
8322            }
8323            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8324            return PackageParser.generateInstrumentationInfo(i, flags);
8325        }
8326    }
8327
8328    @Override
8329    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8330            String targetPackage, int flags) {
8331        final int callingUid = Binder.getCallingUid();
8332        final int callingUserId = UserHandle.getUserId(callingUid);
8333        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8334        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8335            return ParceledListSlice.emptyList();
8336        }
8337        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8338    }
8339
8340    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8341            int flags) {
8342        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8343
8344        // reader
8345        synchronized (mPackages) {
8346            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8347            while (i.hasNext()) {
8348                final PackageParser.Instrumentation p = i.next();
8349                if (targetPackage == null
8350                        || targetPackage.equals(p.info.targetPackage)) {
8351                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8352                            flags);
8353                    if (ii != null) {
8354                        finalList.add(ii);
8355                    }
8356                }
8357            }
8358        }
8359
8360        return finalList;
8361    }
8362
8363    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8365        try {
8366            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8367        } finally {
8368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8369        }
8370    }
8371
8372    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8373        final File[] files = scanDir.listFiles();
8374        if (ArrayUtils.isEmpty(files)) {
8375            Log.d(TAG, "No files in app dir " + scanDir);
8376            return;
8377        }
8378
8379        if (DEBUG_PACKAGE_SCANNING) {
8380            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8381                    + " flags=0x" + Integer.toHexString(parseFlags));
8382        }
8383        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8384                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8385                mParallelPackageParserCallback)) {
8386            // Submit files for parsing in parallel
8387            int fileCount = 0;
8388            for (File file : files) {
8389                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8390                        && !PackageInstallerService.isStageName(file.getName());
8391                if (!isPackage) {
8392                    // Ignore entries which are not packages
8393                    continue;
8394                }
8395                parallelPackageParser.submit(file, parseFlags);
8396                fileCount++;
8397            }
8398
8399            // Process results one by one
8400            for (; fileCount > 0; fileCount--) {
8401                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8402                Throwable throwable = parseResult.throwable;
8403                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8404
8405                if (throwable == null) {
8406                    // TODO(toddke): move lower in the scan chain
8407                    // Static shared libraries have synthetic package names
8408                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8409                        renameStaticSharedLibraryPackage(parseResult.pkg);
8410                    }
8411                    try {
8412                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8413                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8414                                    currentTime, null);
8415                        }
8416                    } catch (PackageManagerException e) {
8417                        errorCode = e.error;
8418                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8419                    }
8420                } else if (throwable instanceof PackageParser.PackageParserException) {
8421                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8422                            throwable;
8423                    errorCode = e.error;
8424                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8425                } else {
8426                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8427                            + parseResult.scanFile, throwable);
8428                }
8429
8430                // Delete invalid userdata apps
8431                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8432                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8433                    logCriticalInfo(Log.WARN,
8434                            "Deleting invalid package at " + parseResult.scanFile);
8435                    removeCodePathLI(parseResult.scanFile);
8436                }
8437            }
8438        }
8439    }
8440
8441    public static void reportSettingsProblem(int priority, String msg) {
8442        logCriticalInfo(priority, msg);
8443    }
8444
8445    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8446            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8447        // When upgrading from pre-N MR1, verify the package time stamp using the package
8448        // directory and not the APK file.
8449        final long lastModifiedTime = mIsPreNMR1Upgrade
8450                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8451        if (ps != null && !forceCollect
8452                && ps.codePathString.equals(pkg.codePath)
8453                && ps.timeStamp == lastModifiedTime
8454                && !isCompatSignatureUpdateNeeded(pkg)
8455                && !isRecoverSignatureUpdateNeeded(pkg)) {
8456            if (ps.signatures.mSigningDetails.signatures != null
8457                    && ps.signatures.mSigningDetails.signatures.length != 0
8458                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8459                            != SignatureSchemeVersion.UNKNOWN) {
8460                // Optimization: reuse the existing cached signing data
8461                // if the package appears to be unchanged.
8462                pkg.mSigningDetails =
8463                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8464                return;
8465            }
8466
8467            Slog.w(TAG, "PackageSetting for " + ps.name
8468                    + " is missing signatures.  Collecting certs again to recover them.");
8469        } else {
8470            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8471                    (forceCollect ? " (forced)" : ""));
8472        }
8473
8474        try {
8475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8476            PackageParser.collectCertificates(pkg, skipVerify);
8477        } catch (PackageParserException e) {
8478            throw PackageManagerException.from(e);
8479        } finally {
8480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8481        }
8482    }
8483
8484    /**
8485     *  Traces a package scan.
8486     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8487     */
8488    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8489            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8490        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8491        try {
8492            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8493        } finally {
8494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8495        }
8496    }
8497
8498    /**
8499     *  Scans a package and returns the newly parsed package.
8500     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8501     */
8502    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8503            long currentTime, UserHandle user) throws PackageManagerException {
8504        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8505        PackageParser pp = new PackageParser();
8506        pp.setSeparateProcesses(mSeparateProcesses);
8507        pp.setOnlyCoreApps(mOnlyCore);
8508        pp.setDisplayMetrics(mMetrics);
8509        pp.setCallback(mPackageParserCallback);
8510
8511        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8512        final PackageParser.Package pkg;
8513        try {
8514            pkg = pp.parsePackage(scanFile, parseFlags);
8515        } catch (PackageParserException e) {
8516            throw PackageManagerException.from(e);
8517        } finally {
8518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8519        }
8520
8521        // Static shared libraries have synthetic package names
8522        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8523            renameStaticSharedLibraryPackage(pkg);
8524        }
8525
8526        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8527    }
8528
8529    /**
8530     *  Scans a package and returns the newly parsed package.
8531     *  @throws PackageManagerException on a parse error.
8532     */
8533    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8534            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8535            @Nullable UserHandle user)
8536                    throws PackageManagerException {
8537        // If the package has children and this is the first dive in the function
8538        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8539        // packages (parent and children) would be successfully scanned before the
8540        // actual scan since scanning mutates internal state and we want to atomically
8541        // install the package and its children.
8542        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8543            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8544                scanFlags |= SCAN_CHECK_ONLY;
8545            }
8546        } else {
8547            scanFlags &= ~SCAN_CHECK_ONLY;
8548        }
8549
8550        // Scan the parent
8551        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8552                scanFlags, currentTime, user);
8553
8554        // Scan the children
8555        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8556        for (int i = 0; i < childCount; i++) {
8557            PackageParser.Package childPackage = pkg.childPackages.get(i);
8558            addForInitLI(childPackage, parseFlags, scanFlags,
8559                    currentTime, user);
8560        }
8561
8562
8563        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8564            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8565        }
8566
8567        return scannedPkg;
8568    }
8569
8570    /**
8571     * Returns if full apk verification can be skipped for the whole package, including the splits.
8572     */
8573    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8574        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8575            return false;
8576        }
8577        // TODO: Allow base and splits to be verified individually.
8578        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8579            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8580                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8581                    return false;
8582                }
8583            }
8584        }
8585        return true;
8586    }
8587
8588    /**
8589     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8590     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8591     * match one in a trusted source, and should be done separately.
8592     */
8593    private boolean canSkipFullApkVerification(String apkPath) {
8594        byte[] rootHashObserved = null;
8595        try {
8596            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8597            if (rootHashObserved == null) {
8598                return false;  // APK does not contain Merkle tree root hash.
8599            }
8600            synchronized (mInstallLock) {
8601                // Returns whether the observed root hash matches what kernel has.
8602                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8603                return true;
8604            }
8605        } catch (InstallerException | IOException | DigestException |
8606                NoSuchAlgorithmException e) {
8607            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8608        }
8609        return false;
8610    }
8611
8612    /**
8613     * Adds a new package to the internal data structures during platform initialization.
8614     * <p>After adding, the package is known to the system and available for querying.
8615     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8616     * etc...], additional checks are performed. Basic verification [such as ensuring
8617     * matching signatures, checking version codes, etc...] occurs if the package is
8618     * identical to a previously known package. If the package fails a signature check,
8619     * the version installed on /data will be removed. If the version of the new package
8620     * is less than or equal than the version on /data, it will be ignored.
8621     * <p>Regardless of the package location, the results are applied to the internal
8622     * structures and the package is made available to the rest of the system.
8623     * <p>NOTE: The return value should be removed. It's the passed in package object.
8624     */
8625    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8626            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8627            @Nullable UserHandle user)
8628                    throws PackageManagerException {
8629        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8630        final String renamedPkgName;
8631        final PackageSetting disabledPkgSetting;
8632        final boolean isSystemPkgUpdated;
8633        final boolean pkgAlreadyExists;
8634        PackageSetting pkgSetting;
8635
8636        // NOTE: installPackageLI() has the same code to setup the package's
8637        // application info. This probably should be done lower in the call
8638        // stack [such as scanPackageOnly()]. However, we verify the application
8639        // info prior to that [in scanPackageNew()] and thus have to setup
8640        // the application info early.
8641        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8642        pkg.setApplicationInfoCodePath(pkg.codePath);
8643        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8644        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8645        pkg.setApplicationInfoResourcePath(pkg.codePath);
8646        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8647        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8648
8649        synchronized (mPackages) {
8650            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8651            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8652            if (realPkgName != null) {
8653                ensurePackageRenamed(pkg, renamedPkgName);
8654            }
8655            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8656            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8657            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8658            pkgAlreadyExists = pkgSetting != null;
8659            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8660            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8661            isSystemPkgUpdated = disabledPkgSetting != null;
8662
8663            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8664                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8665            }
8666
8667            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8668                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8669                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8670                    : null;
8671            if (DEBUG_PACKAGE_SCANNING
8672                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8673                    && sharedUserSetting != null) {
8674                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8675                        + " (uid=" + sharedUserSetting.userId + "):"
8676                        + " packages=" + sharedUserSetting.packages);
8677            }
8678
8679            if (scanSystemPartition) {
8680                // Potentially prune child packages. If the application on the /system
8681                // partition has been updated via OTA, but, is still disabled by a
8682                // version on /data, cycle through all of its children packages and
8683                // remove children that are no longer defined.
8684                if (isSystemPkgUpdated) {
8685                    final int scannedChildCount = (pkg.childPackages != null)
8686                            ? pkg.childPackages.size() : 0;
8687                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8688                            ? disabledPkgSetting.childPackageNames.size() : 0;
8689                    for (int i = 0; i < disabledChildCount; i++) {
8690                        String disabledChildPackageName =
8691                                disabledPkgSetting.childPackageNames.get(i);
8692                        boolean disabledPackageAvailable = false;
8693                        for (int j = 0; j < scannedChildCount; j++) {
8694                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8695                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8696                                disabledPackageAvailable = true;
8697                                break;
8698                            }
8699                        }
8700                        if (!disabledPackageAvailable) {
8701                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8702                        }
8703                    }
8704                    // we're updating the disabled package, so, scan it as the package setting
8705                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8706                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8707                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8708                            (pkg == mPlatformPackage), user);
8709                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8710                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8711                }
8712            }
8713        }
8714
8715        final boolean newPkgChangedPaths =
8716                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8717        final boolean newPkgVersionGreater =
8718                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8719        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8720                && newPkgChangedPaths && newPkgVersionGreater;
8721        if (isSystemPkgBetter) {
8722            // The version of the application on /system is greater than the version on
8723            // /data. Switch back to the application on /system.
8724            // It's safe to assume the application on /system will correctly scan. If not,
8725            // there won't be a working copy of the application.
8726            synchronized (mPackages) {
8727                // just remove the loaded entries from package lists
8728                mPackages.remove(pkgSetting.name);
8729            }
8730
8731            logCriticalInfo(Log.WARN,
8732                    "System package updated;"
8733                    + " name: " + pkgSetting.name
8734                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8735                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8736
8737            final InstallArgs args = createInstallArgsForExisting(
8738                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8739                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8740            args.cleanUpResourcesLI();
8741            synchronized (mPackages) {
8742                mSettings.enableSystemPackageLPw(pkgSetting.name);
8743            }
8744        }
8745
8746        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8747            // The version of the application on the /system partition is less than or
8748            // equal to the version on the /data partition. Throw an exception and use
8749            // the application already installed on the /data partition.
8750            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8751                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8752                    + " better than this " + pkg.getLongVersionCode());
8753        }
8754
8755        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8756        // force re-collecting certificate.
8757        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8758                disabledPkgSetting);
8759        // Full APK verification can be skipped during certificate collection, only if the file is
8760        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8761        // cases, only data in Signing Block is verified instead of the whole file.
8762        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8763                (forceCollect && canSkipFullPackageVerification(pkg));
8764        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8765
8766        boolean shouldHideSystemApp = false;
8767        // A new application appeared on /system, but, we already have a copy of
8768        // the application installed on /data.
8769        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8770                && !pkgSetting.isSystem()) {
8771
8772            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8773                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8774                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8775                                    pkg.mSigningDetails,
8776                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8777                logCriticalInfo(Log.WARN,
8778                        "System package signature mismatch;"
8779                        + " name: " + pkgSetting.name);
8780                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8781                        "scanPackageInternalLI")) {
8782                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8783                }
8784                pkgSetting = null;
8785            } else if (newPkgVersionGreater) {
8786                // The application on /system is newer than the application on /data.
8787                // Simply remove the application on /data [keeping application data]
8788                // and replace it with the version on /system.
8789                logCriticalInfo(Log.WARN,
8790                        "System package enabled;"
8791                        + " name: " + pkgSetting.name
8792                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8793                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8794                InstallArgs args = createInstallArgsForExisting(
8795                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8796                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8797                synchronized (mInstallLock) {
8798                    args.cleanUpResourcesLI();
8799                }
8800            } else {
8801                // The application on /system is older than the application on /data. Hide
8802                // the application on /system and the version on /data will be scanned later
8803                // and re-added like an update.
8804                shouldHideSystemApp = true;
8805                logCriticalInfo(Log.INFO,
8806                        "System package disabled;"
8807                        + " name: " + pkgSetting.name
8808                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8809                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8810            }
8811        }
8812
8813        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8814                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8815
8816        if (shouldHideSystemApp) {
8817            synchronized (mPackages) {
8818                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8819            }
8820        }
8821        return scannedPkg;
8822    }
8823
8824    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8825        // Derive the new package synthetic package name
8826        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8827                + pkg.staticSharedLibVersion);
8828    }
8829
8830    private static String fixProcessName(String defProcessName,
8831            String processName) {
8832        if (processName == null) {
8833            return defProcessName;
8834        }
8835        return processName;
8836    }
8837
8838    /**
8839     * Enforces that only the system UID or root's UID can call a method exposed
8840     * via Binder.
8841     *
8842     * @param message used as message if SecurityException is thrown
8843     * @throws SecurityException if the caller is not system or root
8844     */
8845    private static final void enforceSystemOrRoot(String message) {
8846        final int uid = Binder.getCallingUid();
8847        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8848            throw new SecurityException(message);
8849        }
8850    }
8851
8852    @Override
8853    public void performFstrimIfNeeded() {
8854        enforceSystemOrRoot("Only the system can request fstrim");
8855
8856        // Before everything else, see whether we need to fstrim.
8857        try {
8858            IStorageManager sm = PackageHelper.getStorageManager();
8859            if (sm != null) {
8860                boolean doTrim = false;
8861                final long interval = android.provider.Settings.Global.getLong(
8862                        mContext.getContentResolver(),
8863                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8864                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8865                if (interval > 0) {
8866                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8867                    if (timeSinceLast > interval) {
8868                        doTrim = true;
8869                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8870                                + "; running immediately");
8871                    }
8872                }
8873                if (doTrim) {
8874                    final boolean dexOptDialogShown;
8875                    synchronized (mPackages) {
8876                        dexOptDialogShown = mDexOptDialogShown;
8877                    }
8878                    if (!isFirstBoot() && dexOptDialogShown) {
8879                        try {
8880                            ActivityManager.getService().showBootMessage(
8881                                    mContext.getResources().getString(
8882                                            R.string.android_upgrading_fstrim), true);
8883                        } catch (RemoteException e) {
8884                        }
8885                    }
8886                    sm.runMaintenance();
8887                }
8888            } else {
8889                Slog.e(TAG, "storageManager service unavailable!");
8890            }
8891        } catch (RemoteException e) {
8892            // Can't happen; StorageManagerService is local
8893        }
8894    }
8895
8896    @Override
8897    public void updatePackagesIfNeeded() {
8898        enforceSystemOrRoot("Only the system can request package update");
8899
8900        // We need to re-extract after an OTA.
8901        boolean causeUpgrade = isUpgrade();
8902
8903        // First boot or factory reset.
8904        // Note: we also handle devices that are upgrading to N right now as if it is their
8905        //       first boot, as they do not have profile data.
8906        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8907
8908        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8909        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8910
8911        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8912            return;
8913        }
8914
8915        List<PackageParser.Package> pkgs;
8916        synchronized (mPackages) {
8917            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8918        }
8919
8920        final long startTime = System.nanoTime();
8921        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8922                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8923                    false /* bootComplete */);
8924
8925        final int elapsedTimeSeconds =
8926                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8927
8928        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8929        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8930        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8931        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8932        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8933    }
8934
8935    /*
8936     * Return the prebuilt profile path given a package base code path.
8937     */
8938    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8939        return pkg.baseCodePath + ".prof";
8940    }
8941
8942    /**
8943     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8944     * containing statistics about the invocation. The array consists of three elements,
8945     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8946     * and {@code numberOfPackagesFailed}.
8947     */
8948    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8949            final int compilationReason, boolean bootComplete) {
8950
8951        int numberOfPackagesVisited = 0;
8952        int numberOfPackagesOptimized = 0;
8953        int numberOfPackagesSkipped = 0;
8954        int numberOfPackagesFailed = 0;
8955        final int numberOfPackagesToDexopt = pkgs.size();
8956
8957        for (PackageParser.Package pkg : pkgs) {
8958            numberOfPackagesVisited++;
8959
8960            boolean useProfileForDexopt = false;
8961
8962            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8963                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8964                // that are already compiled.
8965                File profileFile = new File(getPrebuildProfilePath(pkg));
8966                // Copy profile if it exists.
8967                if (profileFile.exists()) {
8968                    try {
8969                        // We could also do this lazily before calling dexopt in
8970                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8971                        // is that we don't have a good way to say "do this only once".
8972                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8973                                pkg.applicationInfo.uid, pkg.packageName,
8974                                ArtManager.getProfileName(null))) {
8975                            Log.e(TAG, "Installer failed to copy system profile!");
8976                        } else {
8977                            // Disabled as this causes speed-profile compilation during first boot
8978                            // even if things are already compiled.
8979                            // useProfileForDexopt = true;
8980                        }
8981                    } catch (Exception e) {
8982                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8983                                e);
8984                    }
8985                } else {
8986                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8987                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8988                    // minimize the number off apps being speed-profile compiled during first boot.
8989                    // The other paths will not change the filter.
8990                    if (disabledPs != null && disabledPs.pkg.isStub) {
8991                        // The package is the stub one, remove the stub suffix to get the normal
8992                        // package and APK names.
8993                        String systemProfilePath =
8994                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8995                        profileFile = new File(systemProfilePath);
8996                        // If we have a profile for a compressed APK, copy it to the reference
8997                        // location.
8998                        // Note that copying the profile here will cause it to override the
8999                        // reference profile every OTA even though the existing reference profile
9000                        // may have more data. We can't copy during decompression since the
9001                        // directories are not set up at that point.
9002                        if (profileFile.exists()) {
9003                            try {
9004                                // We could also do this lazily before calling dexopt in
9005                                // PackageDexOptimizer to prevent this happening on first boot. The
9006                                // issue is that we don't have a good way to say "do this only
9007                                // once".
9008                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9009                                        pkg.applicationInfo.uid, pkg.packageName,
9010                                        ArtManager.getProfileName(null))) {
9011                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9012                                } else {
9013                                    useProfileForDexopt = true;
9014                                }
9015                            } catch (Exception e) {
9016                                Log.e(TAG, "Failed to copy profile " +
9017                                        profileFile.getAbsolutePath() + " ", e);
9018                            }
9019                        }
9020                    }
9021                }
9022            }
9023
9024            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9025                if (DEBUG_DEXOPT) {
9026                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9027                }
9028                numberOfPackagesSkipped++;
9029                continue;
9030            }
9031
9032            if (DEBUG_DEXOPT) {
9033                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9034                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9035            }
9036
9037            if (showDialog) {
9038                try {
9039                    ActivityManager.getService().showBootMessage(
9040                            mContext.getResources().getString(R.string.android_upgrading_apk,
9041                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9042                } catch (RemoteException e) {
9043                }
9044                synchronized (mPackages) {
9045                    mDexOptDialogShown = true;
9046                }
9047            }
9048
9049            int pkgCompilationReason = compilationReason;
9050            if (useProfileForDexopt) {
9051                // Use background dexopt mode to try and use the profile. Note that this does not
9052                // guarantee usage of the profile.
9053                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9054            }
9055
9056            // checkProfiles is false to avoid merging profiles during boot which
9057            // might interfere with background compilation (b/28612421).
9058            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9059            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9060            // trade-off worth doing to save boot time work.
9061            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9062            if (compilationReason == REASON_FIRST_BOOT) {
9063                // TODO: This doesn't cover the upgrade case, we should check for this too.
9064                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9065            }
9066            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9067                    pkg.packageName,
9068                    pkgCompilationReason,
9069                    dexoptFlags));
9070
9071            switch (primaryDexOptStaus) {
9072                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9073                    numberOfPackagesOptimized++;
9074                    break;
9075                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9076                    numberOfPackagesSkipped++;
9077                    break;
9078                case PackageDexOptimizer.DEX_OPT_FAILED:
9079                    numberOfPackagesFailed++;
9080                    break;
9081                default:
9082                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9083                    break;
9084            }
9085        }
9086
9087        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9088                numberOfPackagesFailed };
9089    }
9090
9091    @Override
9092    public void notifyPackageUse(String packageName, int reason) {
9093        synchronized (mPackages) {
9094            final int callingUid = Binder.getCallingUid();
9095            final int callingUserId = UserHandle.getUserId(callingUid);
9096            if (getInstantAppPackageName(callingUid) != null) {
9097                if (!isCallerSameApp(packageName, callingUid)) {
9098                    return;
9099                }
9100            } else {
9101                if (isInstantApp(packageName, callingUserId)) {
9102                    return;
9103                }
9104            }
9105            notifyPackageUseLocked(packageName, reason);
9106        }
9107    }
9108
9109    @GuardedBy("mPackages")
9110    private void notifyPackageUseLocked(String packageName, int reason) {
9111        final PackageParser.Package p = mPackages.get(packageName);
9112        if (p == null) {
9113            return;
9114        }
9115        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9116    }
9117
9118    @Override
9119    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9120            List<String> classPaths, String loaderIsa) {
9121        int userId = UserHandle.getCallingUserId();
9122        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9123        if (ai == null) {
9124            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9125                + loadingPackageName + ", user=" + userId);
9126            return;
9127        }
9128        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9129    }
9130
9131    @Override
9132    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9133            IDexModuleRegisterCallback callback) {
9134        int userId = UserHandle.getCallingUserId();
9135        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9136        DexManager.RegisterDexModuleResult result;
9137        if (ai == null) {
9138            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9139                     " calling user. package=" + packageName + ", user=" + userId);
9140            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9141        } else {
9142            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9143        }
9144
9145        if (callback != null) {
9146            mHandler.post(() -> {
9147                try {
9148                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9149                } catch (RemoteException e) {
9150                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9151                }
9152            });
9153        }
9154    }
9155
9156    /**
9157     * Ask the package manager to perform a dex-opt with the given compiler filter.
9158     *
9159     * Note: exposed only for the shell command to allow moving packages explicitly to a
9160     *       definite state.
9161     */
9162    @Override
9163    public boolean performDexOptMode(String packageName,
9164            boolean checkProfiles, String targetCompilerFilter, boolean force,
9165            boolean bootComplete, String splitName) {
9166        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9167                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9168                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9169        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9170                targetCompilerFilter, splitName, flags));
9171    }
9172
9173    /**
9174     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9175     * secondary dex files belonging to the given package.
9176     *
9177     * Note: exposed only for the shell command to allow moving packages explicitly to a
9178     *       definite state.
9179     */
9180    @Override
9181    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9182            boolean force) {
9183        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9184                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9185                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9186                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9187        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9188    }
9189
9190    /*package*/ boolean performDexOpt(DexoptOptions options) {
9191        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9192            return false;
9193        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9194            return false;
9195        }
9196
9197        if (options.isDexoptOnlySecondaryDex()) {
9198            return mDexManager.dexoptSecondaryDex(options);
9199        } else {
9200            int dexoptStatus = performDexOptWithStatus(options);
9201            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9202        }
9203    }
9204
9205    /**
9206     * Perform dexopt on the given package and return one of following result:
9207     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9208     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9209     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9210     */
9211    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9212        return performDexOptTraced(options);
9213    }
9214
9215    private int performDexOptTraced(DexoptOptions options) {
9216        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9217        try {
9218            return performDexOptInternal(options);
9219        } finally {
9220            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9221        }
9222    }
9223
9224    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9225    // if the package can now be considered up to date for the given filter.
9226    private int performDexOptInternal(DexoptOptions options) {
9227        PackageParser.Package p;
9228        synchronized (mPackages) {
9229            p = mPackages.get(options.getPackageName());
9230            if (p == null) {
9231                // Package could not be found. Report failure.
9232                return PackageDexOptimizer.DEX_OPT_FAILED;
9233            }
9234            mPackageUsage.maybeWriteAsync(mPackages);
9235            mCompilerStats.maybeWriteAsync();
9236        }
9237        long callingId = Binder.clearCallingIdentity();
9238        try {
9239            synchronized (mInstallLock) {
9240                return performDexOptInternalWithDependenciesLI(p, options);
9241            }
9242        } finally {
9243            Binder.restoreCallingIdentity(callingId);
9244        }
9245    }
9246
9247    public ArraySet<String> getOptimizablePackages() {
9248        ArraySet<String> pkgs = new ArraySet<String>();
9249        synchronized (mPackages) {
9250            for (PackageParser.Package p : mPackages.values()) {
9251                if (PackageDexOptimizer.canOptimizePackage(p)) {
9252                    pkgs.add(p.packageName);
9253                }
9254            }
9255        }
9256        return pkgs;
9257    }
9258
9259    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9260            DexoptOptions options) {
9261        // Select the dex optimizer based on the force parameter.
9262        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9263        //       allocate an object here.
9264        PackageDexOptimizer pdo = options.isForce()
9265                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9266                : mPackageDexOptimizer;
9267
9268        // Dexopt all dependencies first. Note: we ignore the return value and march on
9269        // on errors.
9270        // Note that we are going to call performDexOpt on those libraries as many times as
9271        // they are referenced in packages. When we do a batch of performDexOpt (for example
9272        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9273        // and the first package that uses the library will dexopt it. The
9274        // others will see that the compiled code for the library is up to date.
9275        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9276        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9277        if (!deps.isEmpty()) {
9278            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9279                    options.getCompilationReason(), options.getCompilerFilter(),
9280                    options.getSplitName(),
9281                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9282            for (PackageParser.Package depPackage : deps) {
9283                // TODO: Analyze and investigate if we (should) profile libraries.
9284                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9285                        getOrCreateCompilerPackageStats(depPackage),
9286                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9287            }
9288        }
9289        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9290                getOrCreateCompilerPackageStats(p),
9291                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9292    }
9293
9294    /**
9295     * Reconcile the information we have about the secondary dex files belonging to
9296     * {@code packagName} and the actual dex files. For all dex files that were
9297     * deleted, update the internal records and delete the generated oat files.
9298     */
9299    @Override
9300    public void reconcileSecondaryDexFiles(String packageName) {
9301        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9302            return;
9303        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9304            return;
9305        }
9306        mDexManager.reconcileSecondaryDexFiles(packageName);
9307    }
9308
9309    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9310    // a reference there.
9311    /*package*/ DexManager getDexManager() {
9312        return mDexManager;
9313    }
9314
9315    /**
9316     * Execute the background dexopt job immediately.
9317     */
9318    @Override
9319    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9320        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9321            return false;
9322        }
9323        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9324    }
9325
9326    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9327        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9328                || p.usesStaticLibraries != null) {
9329            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9330            Set<String> collectedNames = new HashSet<>();
9331            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9332
9333            retValue.remove(p);
9334
9335            return retValue;
9336        } else {
9337            return Collections.emptyList();
9338        }
9339    }
9340
9341    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9342            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9343        if (!collectedNames.contains(p.packageName)) {
9344            collectedNames.add(p.packageName);
9345            collected.add(p);
9346
9347            if (p.usesLibraries != null) {
9348                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9349                        null, collected, collectedNames);
9350            }
9351            if (p.usesOptionalLibraries != null) {
9352                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9353                        null, collected, collectedNames);
9354            }
9355            if (p.usesStaticLibraries != null) {
9356                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9357                        p.usesStaticLibrariesVersions, collected, collectedNames);
9358            }
9359        }
9360    }
9361
9362    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9363            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9364        final int libNameCount = libs.size();
9365        for (int i = 0; i < libNameCount; i++) {
9366            String libName = libs.get(i);
9367            long version = (versions != null && versions.length == libNameCount)
9368                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9369            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9370            if (libPkg != null) {
9371                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9372            }
9373        }
9374    }
9375
9376    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9377        synchronized (mPackages) {
9378            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9379            if (libEntry != null) {
9380                return mPackages.get(libEntry.apk);
9381            }
9382            return null;
9383        }
9384    }
9385
9386    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9387        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9388        if (versionedLib == null) {
9389            return null;
9390        }
9391        return versionedLib.get(version);
9392    }
9393
9394    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9395        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9396                pkg.staticSharedLibName);
9397        if (versionedLib == null) {
9398            return null;
9399        }
9400        long previousLibVersion = -1;
9401        final int versionCount = versionedLib.size();
9402        for (int i = 0; i < versionCount; i++) {
9403            final long libVersion = versionedLib.keyAt(i);
9404            if (libVersion < pkg.staticSharedLibVersion) {
9405                previousLibVersion = Math.max(previousLibVersion, libVersion);
9406            }
9407        }
9408        if (previousLibVersion >= 0) {
9409            return versionedLib.get(previousLibVersion);
9410        }
9411        return null;
9412    }
9413
9414    public void shutdown() {
9415        mPackageUsage.writeNow(mPackages);
9416        mCompilerStats.writeNow();
9417        mDexManager.writePackageDexUsageNow();
9418    }
9419
9420    @Override
9421    public void dumpProfiles(String packageName) {
9422        PackageParser.Package pkg;
9423        synchronized (mPackages) {
9424            pkg = mPackages.get(packageName);
9425            if (pkg == null) {
9426                throw new IllegalArgumentException("Unknown package: " + packageName);
9427            }
9428        }
9429        /* Only the shell, root, or the app user should be able to dump profiles. */
9430        int callingUid = Binder.getCallingUid();
9431        if (callingUid != Process.SHELL_UID &&
9432            callingUid != Process.ROOT_UID &&
9433            callingUid != pkg.applicationInfo.uid) {
9434            throw new SecurityException("dumpProfiles");
9435        }
9436
9437        synchronized (mInstallLock) {
9438            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9439            mArtManagerService.dumpProfiles(pkg);
9440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9441        }
9442    }
9443
9444    @Override
9445    public void forceDexOpt(String packageName) {
9446        enforceSystemOrRoot("forceDexOpt");
9447
9448        PackageParser.Package pkg;
9449        synchronized (mPackages) {
9450            pkg = mPackages.get(packageName);
9451            if (pkg == null) {
9452                throw new IllegalArgumentException("Unknown package: " + packageName);
9453            }
9454        }
9455
9456        synchronized (mInstallLock) {
9457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9458
9459            // Whoever is calling forceDexOpt wants a compiled package.
9460            // Don't use profiles since that may cause compilation to be skipped.
9461            final int res = performDexOptInternalWithDependenciesLI(
9462                    pkg,
9463                    new DexoptOptions(packageName,
9464                            getDefaultCompilerFilter(),
9465                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9466
9467            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9468            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9469                throw new IllegalStateException("Failed to dexopt: " + res);
9470            }
9471        }
9472    }
9473
9474    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9475        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9476            Slog.w(TAG, "Unable to update from " + oldPkg.name
9477                    + " to " + newPkg.packageName
9478                    + ": old package not in system partition");
9479            return false;
9480        } else if (mPackages.get(oldPkg.name) != null) {
9481            Slog.w(TAG, "Unable to update from " + oldPkg.name
9482                    + " to " + newPkg.packageName
9483                    + ": old package still exists");
9484            return false;
9485        }
9486        return true;
9487    }
9488
9489    void removeCodePathLI(File codePath) {
9490        if (codePath.isDirectory()) {
9491            try {
9492                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9493            } catch (InstallerException e) {
9494                Slog.w(TAG, "Failed to remove code path", e);
9495            }
9496        } else {
9497            codePath.delete();
9498        }
9499    }
9500
9501    private int[] resolveUserIds(int userId) {
9502        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9503    }
9504
9505    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9506        if (pkg == null) {
9507            Slog.wtf(TAG, "Package was null!", new Throwable());
9508            return;
9509        }
9510        clearAppDataLeafLIF(pkg, userId, flags);
9511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9512        for (int i = 0; i < childCount; i++) {
9513            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9514        }
9515
9516        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9517    }
9518
9519    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9520        final PackageSetting ps;
9521        synchronized (mPackages) {
9522            ps = mSettings.mPackages.get(pkg.packageName);
9523        }
9524        for (int realUserId : resolveUserIds(userId)) {
9525            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9526            try {
9527                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9528                        ceDataInode);
9529            } catch (InstallerException e) {
9530                Slog.w(TAG, String.valueOf(e));
9531            }
9532        }
9533    }
9534
9535    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9536        if (pkg == null) {
9537            Slog.wtf(TAG, "Package was null!", new Throwable());
9538            return;
9539        }
9540        destroyAppDataLeafLIF(pkg, userId, flags);
9541        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9542        for (int i = 0; i < childCount; i++) {
9543            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9544        }
9545    }
9546
9547    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9548        final PackageSetting ps;
9549        synchronized (mPackages) {
9550            ps = mSettings.mPackages.get(pkg.packageName);
9551        }
9552        for (int realUserId : resolveUserIds(userId)) {
9553            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9554            try {
9555                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9556                        ceDataInode);
9557            } catch (InstallerException e) {
9558                Slog.w(TAG, String.valueOf(e));
9559            }
9560            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9561        }
9562    }
9563
9564    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9565        if (pkg == null) {
9566            Slog.wtf(TAG, "Package was null!", new Throwable());
9567            return;
9568        }
9569        destroyAppProfilesLeafLIF(pkg);
9570        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9571        for (int i = 0; i < childCount; i++) {
9572            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9573        }
9574    }
9575
9576    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9577        try {
9578            mInstaller.destroyAppProfiles(pkg.packageName);
9579        } catch (InstallerException e) {
9580            Slog.w(TAG, String.valueOf(e));
9581        }
9582    }
9583
9584    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9585        if (pkg == null) {
9586            Slog.wtf(TAG, "Package was null!", new Throwable());
9587            return;
9588        }
9589        mArtManagerService.clearAppProfiles(pkg);
9590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9591        for (int i = 0; i < childCount; i++) {
9592            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9593        }
9594    }
9595
9596    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9597            long lastUpdateTime) {
9598        // Set parent install/update time
9599        PackageSetting ps = (PackageSetting) pkg.mExtras;
9600        if (ps != null) {
9601            ps.firstInstallTime = firstInstallTime;
9602            ps.lastUpdateTime = lastUpdateTime;
9603        }
9604        // Set children install/update time
9605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9606        for (int i = 0; i < childCount; i++) {
9607            PackageParser.Package childPkg = pkg.childPackages.get(i);
9608            ps = (PackageSetting) childPkg.mExtras;
9609            if (ps != null) {
9610                ps.firstInstallTime = firstInstallTime;
9611                ps.lastUpdateTime = lastUpdateTime;
9612            }
9613        }
9614    }
9615
9616    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9617            SharedLibraryEntry file,
9618            PackageParser.Package changingLib) {
9619        if (file.path != null) {
9620            usesLibraryFiles.add(file.path);
9621            return;
9622        }
9623        PackageParser.Package p = mPackages.get(file.apk);
9624        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9625            // If we are doing this while in the middle of updating a library apk,
9626            // then we need to make sure to use that new apk for determining the
9627            // dependencies here.  (We haven't yet finished committing the new apk
9628            // to the package manager state.)
9629            if (p == null || p.packageName.equals(changingLib.packageName)) {
9630                p = changingLib;
9631            }
9632        }
9633        if (p != null) {
9634            usesLibraryFiles.addAll(p.getAllCodePaths());
9635            if (p.usesLibraryFiles != null) {
9636                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9637            }
9638        }
9639    }
9640
9641    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9642            PackageParser.Package changingLib) throws PackageManagerException {
9643        if (pkg == null) {
9644            return;
9645        }
9646        // The collection used here must maintain the order of addition (so
9647        // that libraries are searched in the correct order) and must have no
9648        // duplicates.
9649        Set<String> usesLibraryFiles = null;
9650        if (pkg.usesLibraries != null) {
9651            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9652                    null, null, pkg.packageName, changingLib, true,
9653                    pkg.applicationInfo.targetSdkVersion, null);
9654        }
9655        if (pkg.usesStaticLibraries != null) {
9656            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9657                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9658                    pkg.packageName, changingLib, true,
9659                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9660        }
9661        if (pkg.usesOptionalLibraries != null) {
9662            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9663                    null, null, pkg.packageName, changingLib, false,
9664                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9665        }
9666        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9667            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9668        } else {
9669            pkg.usesLibraryFiles = null;
9670        }
9671    }
9672
9673    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9674            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9675            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9676            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9677            throws PackageManagerException {
9678        final int libCount = requestedLibraries.size();
9679        for (int i = 0; i < libCount; i++) {
9680            final String libName = requestedLibraries.get(i);
9681            final long libVersion = requiredVersions != null ? requiredVersions[i]
9682                    : SharedLibraryInfo.VERSION_UNDEFINED;
9683            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9684            if (libEntry == null) {
9685                if (required) {
9686                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9687                            "Package " + packageName + " requires unavailable shared library "
9688                                    + libName + "; failing!");
9689                } else if (DEBUG_SHARED_LIBRARIES) {
9690                    Slog.i(TAG, "Package " + packageName
9691                            + " desires unavailable shared library "
9692                            + libName + "; ignoring!");
9693                }
9694            } else {
9695                if (requiredVersions != null && requiredCertDigests != null) {
9696                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9697                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9698                            "Package " + packageName + " requires unavailable static shared"
9699                                    + " library " + libName + " version "
9700                                    + libEntry.info.getLongVersion() + "; failing!");
9701                    }
9702
9703                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9704                    if (libPkg == null) {
9705                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9706                                "Package " + packageName + " requires unavailable static shared"
9707                                        + " library; failing!");
9708                    }
9709
9710                    final String[] expectedCertDigests = requiredCertDigests[i];
9711
9712
9713                    if (expectedCertDigests.length > 1) {
9714
9715                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9716                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9717                                ? PackageUtils.computeSignaturesSha256Digests(
9718                                libPkg.mSigningDetails.signatures)
9719                                : PackageUtils.computeSignaturesSha256Digests(
9720                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9721
9722                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9723                        // target O we don't parse the "additional-certificate" tags similarly
9724                        // how we only consider all certs only for apps targeting O (see above).
9725                        // Therefore, the size check is safe to make.
9726                        if (expectedCertDigests.length != libCertDigests.length) {
9727                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9728                                    "Package " + packageName + " requires differently signed" +
9729                                            " static shared library; failing!");
9730                        }
9731
9732                        // Use a predictable order as signature order may vary
9733                        Arrays.sort(libCertDigests);
9734                        Arrays.sort(expectedCertDigests);
9735
9736                        final int certCount = libCertDigests.length;
9737                        for (int j = 0; j < certCount; j++) {
9738                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9739                                throw new PackageManagerException(
9740                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9741                                        "Package " + packageName + " requires differently signed" +
9742                                                " static shared library; failing!");
9743                            }
9744                        }
9745                    } else {
9746
9747                        // lib signing cert could have rotated beyond the one expected, check to see
9748                        // if the new one has been blessed by the old
9749                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9750                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9751                            throw new PackageManagerException(
9752                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9753                                    "Package " + packageName + " requires differently signed" +
9754                                            " static shared library; failing!");
9755                        }
9756                    }
9757                }
9758
9759                if (outUsedLibraries == null) {
9760                    // Use LinkedHashSet to preserve the order of files added to
9761                    // usesLibraryFiles while eliminating duplicates.
9762                    outUsedLibraries = new LinkedHashSet<>();
9763                }
9764                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9765            }
9766        }
9767        return outUsedLibraries;
9768    }
9769
9770    private static boolean hasString(List<String> list, List<String> which) {
9771        if (list == null) {
9772            return false;
9773        }
9774        for (int i=list.size()-1; i>=0; i--) {
9775            for (int j=which.size()-1; j>=0; j--) {
9776                if (which.get(j).equals(list.get(i))) {
9777                    return true;
9778                }
9779            }
9780        }
9781        return false;
9782    }
9783
9784    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9785            PackageParser.Package changingPkg) {
9786        ArrayList<PackageParser.Package> res = null;
9787        for (PackageParser.Package pkg : mPackages.values()) {
9788            if (changingPkg != null
9789                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9790                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9791                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9792                            changingPkg.staticSharedLibName)) {
9793                return null;
9794            }
9795            if (res == null) {
9796                res = new ArrayList<>();
9797            }
9798            res.add(pkg);
9799            try {
9800                updateSharedLibrariesLPr(pkg, changingPkg);
9801            } catch (PackageManagerException e) {
9802                // If a system app update or an app and a required lib missing we
9803                // delete the package and for updated system apps keep the data as
9804                // it is better for the user to reinstall than to be in an limbo
9805                // state. Also libs disappearing under an app should never happen
9806                // - just in case.
9807                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9808                    final int flags = pkg.isUpdatedSystemApp()
9809                            ? PackageManager.DELETE_KEEP_DATA : 0;
9810                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9811                            flags , null, true, null);
9812                }
9813                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9814            }
9815        }
9816        return res;
9817    }
9818
9819    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9820            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9821            @Nullable UserHandle user) throws PackageManagerException {
9822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9823        // If the package has children and this is the first dive in the function
9824        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9825        // whether all packages (parent and children) would be successfully scanned
9826        // before the actual scan since scanning mutates internal state and we want
9827        // to atomically install the package and its children.
9828        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9829            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9830                scanFlags |= SCAN_CHECK_ONLY;
9831            }
9832        } else {
9833            scanFlags &= ~SCAN_CHECK_ONLY;
9834        }
9835
9836        final PackageParser.Package scannedPkg;
9837        try {
9838            // Scan the parent
9839            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9840            // Scan the children
9841            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9842            for (int i = 0; i < childCount; i++) {
9843                PackageParser.Package childPkg = pkg.childPackages.get(i);
9844                scanPackageNewLI(childPkg, parseFlags,
9845                        scanFlags, currentTime, user);
9846            }
9847        } finally {
9848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9849        }
9850
9851        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9852            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9853        }
9854
9855        return scannedPkg;
9856    }
9857
9858    /** The result of a package scan. */
9859    private static class ScanResult {
9860        /** Whether or not the package scan was successful */
9861        public final boolean success;
9862        /**
9863         * The final package settings. This may be the same object passed in
9864         * the {@link ScanRequest}, but, with modified values.
9865         */
9866        @Nullable public final PackageSetting pkgSetting;
9867        /** ABI code paths that have changed in the package scan */
9868        @Nullable public final List<String> changedAbiCodePath;
9869        public ScanResult(
9870                boolean success,
9871                @Nullable PackageSetting pkgSetting,
9872                @Nullable List<String> changedAbiCodePath) {
9873            this.success = success;
9874            this.pkgSetting = pkgSetting;
9875            this.changedAbiCodePath = changedAbiCodePath;
9876        }
9877    }
9878
9879    /** A package to be scanned */
9880    private static class ScanRequest {
9881        /** The parsed package */
9882        @NonNull public final PackageParser.Package pkg;
9883        /** The package this package replaces */
9884        @Nullable public final PackageParser.Package oldPkg;
9885        /** Shared user settings, if the package has a shared user */
9886        @Nullable public final SharedUserSetting sharedUserSetting;
9887        /**
9888         * Package settings of the currently installed version.
9889         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9890         * during scan.
9891         */
9892        @Nullable public final PackageSetting pkgSetting;
9893        /** A copy of the settings for the currently installed version */
9894        @Nullable public final PackageSetting oldPkgSetting;
9895        /** Package settings for the disabled version on the /system partition */
9896        @Nullable public final PackageSetting disabledPkgSetting;
9897        /** Package settings for the installed version under its original package name */
9898        @Nullable public final PackageSetting originalPkgSetting;
9899        /** The real package name of a renamed application */
9900        @Nullable public final String realPkgName;
9901        public final @ParseFlags int parseFlags;
9902        public final @ScanFlags int scanFlags;
9903        /** The user for which the package is being scanned */
9904        @Nullable public final UserHandle user;
9905        /** Whether or not the platform package is being scanned */
9906        public final boolean isPlatformPackage;
9907        public ScanRequest(
9908                @NonNull PackageParser.Package pkg,
9909                @Nullable SharedUserSetting sharedUserSetting,
9910                @Nullable PackageParser.Package oldPkg,
9911                @Nullable PackageSetting pkgSetting,
9912                @Nullable PackageSetting disabledPkgSetting,
9913                @Nullable PackageSetting originalPkgSetting,
9914                @Nullable String realPkgName,
9915                @ParseFlags int parseFlags,
9916                @ScanFlags int scanFlags,
9917                boolean isPlatformPackage,
9918                @Nullable UserHandle user) {
9919            this.pkg = pkg;
9920            this.oldPkg = oldPkg;
9921            this.pkgSetting = pkgSetting;
9922            this.sharedUserSetting = sharedUserSetting;
9923            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9924            this.disabledPkgSetting = disabledPkgSetting;
9925            this.originalPkgSetting = originalPkgSetting;
9926            this.realPkgName = realPkgName;
9927            this.parseFlags = parseFlags;
9928            this.scanFlags = scanFlags;
9929            this.isPlatformPackage = isPlatformPackage;
9930            this.user = user;
9931        }
9932    }
9933
9934    /**
9935     * Returns the actual scan flags depending upon the state of the other settings.
9936     * <p>Updated system applications will not have the following flags set
9937     * by default and need to be adjusted after the fact:
9938     * <ul>
9939     * <li>{@link #SCAN_AS_SYSTEM}</li>
9940     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9941     * <li>{@link #SCAN_AS_OEM}</li>
9942     * <li>{@link #SCAN_AS_VENDOR}</li>
9943     * <li>{@link #SCAN_AS_PRODUCT}</li>
9944     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9945     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9946     * </ul>
9947     */
9948    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9949            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9950            PackageParser.Package pkg) {
9951        if (disabledPkgSetting != null) {
9952            // updated system application, must at least have SCAN_AS_SYSTEM
9953            scanFlags |= SCAN_AS_SYSTEM;
9954            if ((disabledPkgSetting.pkgPrivateFlags
9955                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9956                scanFlags |= SCAN_AS_PRIVILEGED;
9957            }
9958            if ((disabledPkgSetting.pkgPrivateFlags
9959                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9960                scanFlags |= SCAN_AS_OEM;
9961            }
9962            if ((disabledPkgSetting.pkgPrivateFlags
9963                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9964                scanFlags |= SCAN_AS_VENDOR;
9965            }
9966            if ((disabledPkgSetting.pkgPrivateFlags
9967                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9968                scanFlags |= SCAN_AS_PRODUCT;
9969            }
9970        }
9971        if (pkgSetting != null) {
9972            final int userId = ((user == null) ? 0 : user.getIdentifier());
9973            if (pkgSetting.getInstantApp(userId)) {
9974                scanFlags |= SCAN_AS_INSTANT_APP;
9975            }
9976            if (pkgSetting.getVirtulalPreload(userId)) {
9977                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9978            }
9979        }
9980
9981        // Scan as privileged apps that share a user with a priv-app.
9982        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
9983                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
9984        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
9985                && !pkg.isPrivileged()
9986                && (pkg.mSharedUserId != null)
9987                && !skipVendorPrivilegeScan) {
9988            SharedUserSetting sharedUserSetting = null;
9989            try {
9990                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9991            } catch (PackageManagerException ignore) {}
9992            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9993                // Exempt SharedUsers signed with the platform key.
9994                // TODO(b/72378145) Fix this exemption. Force signature apps
9995                // to whitelist their privileged permissions just like other
9996                // priv-apps.
9997                synchronized (mPackages) {
9998                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9999                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10000                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10001                        scanFlags |= SCAN_AS_PRIVILEGED;
10002                    }
10003                }
10004            }
10005        }
10006
10007        return scanFlags;
10008    }
10009
10010    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10011    // the results / removing app data needs to be moved up a level to the callers of this
10012    // method. Also, we need to solve the problem of potentially creating a new shared user
10013    // setting. That can probably be done later and patch things up after the fact.
10014    @GuardedBy("mInstallLock")
10015    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10016            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10017            @Nullable UserHandle user) throws PackageManagerException {
10018
10019        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10020        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10021        if (realPkgName != null) {
10022            ensurePackageRenamed(pkg, renamedPkgName);
10023        }
10024        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10025        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10026        final PackageSetting disabledPkgSetting =
10027                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10028
10029        if (mTransferedPackages.contains(pkg.packageName)) {
10030            Slog.w(TAG, "Package " + pkg.packageName
10031                    + " was transferred to another, but its .apk remains");
10032        }
10033
10034        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10035        synchronized (mPackages) {
10036            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10037            assertPackageIsValid(pkg, parseFlags, scanFlags);
10038
10039            SharedUserSetting sharedUserSetting = null;
10040            if (pkg.mSharedUserId != null) {
10041                // SIDE EFFECTS; may potentially allocate a new shared user
10042                sharedUserSetting = mSettings.getSharedUserLPw(
10043                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10044                if (DEBUG_PACKAGE_SCANNING) {
10045                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10046                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10047                                + " (uid=" + sharedUserSetting.userId + "):"
10048                                + " packages=" + sharedUserSetting.packages);
10049                }
10050            }
10051
10052            boolean scanSucceeded = false;
10053            try {
10054                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10055                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10056                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10057                        (pkg == mPlatformPackage), user);
10058                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10059                if (result.success) {
10060                    commitScanResultsLocked(request, result);
10061                }
10062                scanSucceeded = true;
10063            } finally {
10064                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10065                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10066                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10067                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10068                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10069                  }
10070            }
10071        }
10072        return pkg;
10073    }
10074
10075    /**
10076     * Commits the package scan and modifies system state.
10077     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10078     * of committing the package, leaving the system in an inconsistent state.
10079     * This needs to be fixed so, once we get to this point, no errors are
10080     * possible and the system is not left in an inconsistent state.
10081     */
10082    @GuardedBy("mPackages")
10083    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10084            throws PackageManagerException {
10085        final PackageParser.Package pkg = request.pkg;
10086        final PackageParser.Package oldPkg = request.oldPkg;
10087        final @ParseFlags int parseFlags = request.parseFlags;
10088        final @ScanFlags int scanFlags = request.scanFlags;
10089        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10090        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10091        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10092        final UserHandle user = request.user;
10093        final String realPkgName = request.realPkgName;
10094        final PackageSetting pkgSetting = result.pkgSetting;
10095        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10096        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10097
10098        if (newPkgSettingCreated) {
10099            if (originalPkgSetting != null) {
10100                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10101            }
10102            // THROWS: when we can't allocate a user id. add call to check if there's
10103            // enough space to ensure we won't throw; otherwise, don't modify state
10104            mSettings.addUserToSettingLPw(pkgSetting);
10105
10106            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10107                mTransferedPackages.add(originalPkgSetting.name);
10108            }
10109        }
10110        // TODO(toddke): Consider a method specifically for modifying the Package object
10111        // post scan; or, moving this stuff out of the Package object since it has nothing
10112        // to do with the package on disk.
10113        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10114        // for creating the application ID. If we did this earlier, we would be saving the
10115        // correct ID.
10116        pkg.applicationInfo.uid = pkgSetting.appId;
10117
10118        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10119
10120        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10121            mTransferedPackages.add(pkg.packageName);
10122        }
10123
10124        // THROWS: when requested libraries that can't be found. it only changes
10125        // the state of the passed in pkg object, so, move to the top of the method
10126        // and allow it to abort
10127        if ((scanFlags & SCAN_BOOTING) == 0
10128                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10129            // Check all shared libraries and map to their actual file path.
10130            // We only do this here for apps not on a system dir, because those
10131            // are the only ones that can fail an install due to this.  We
10132            // will take care of the system apps by updating all of their
10133            // library paths after the scan is done. Also during the initial
10134            // scan don't update any libs as we do this wholesale after all
10135            // apps are scanned to avoid dependency based scanning.
10136            updateSharedLibrariesLPr(pkg, null);
10137        }
10138
10139        // All versions of a static shared library are referenced with the same
10140        // package name. Internally, we use a synthetic package name to allow
10141        // multiple versions of the same shared library to be installed. So,
10142        // we need to generate the synthetic package name of the latest shared
10143        // library in order to compare signatures.
10144        PackageSetting signatureCheckPs = pkgSetting;
10145        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10146            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10147            if (libraryEntry != null) {
10148                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10149            }
10150        }
10151
10152        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10153        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10154            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10155                // We just determined the app is signed correctly, so bring
10156                // over the latest parsed certs.
10157                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10158            } else {
10159                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10160                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10161                            "Package " + pkg.packageName + " upgrade keys do not match the "
10162                                    + "previously installed version");
10163                } else {
10164                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10165                    String msg = "System package " + pkg.packageName
10166                            + " signature changed; retaining data.";
10167                    reportSettingsProblem(Log.WARN, msg);
10168                }
10169            }
10170        } else {
10171            try {
10172                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10173                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10174                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10175                        pkg.mSigningDetails, compareCompat, compareRecover);
10176                // The new KeySets will be re-added later in the scanning process.
10177                if (compatMatch) {
10178                    synchronized (mPackages) {
10179                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10180                    }
10181                }
10182                // We just determined the app is signed correctly, so bring
10183                // over the latest parsed certs.
10184                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10185
10186
10187                // if this is is a sharedUser, check to see if the new package is signed by a newer
10188                // signing certificate than the existing one, and if so, copy over the new details
10189                if (signatureCheckPs.sharedUser != null
10190                        && pkg.mSigningDetails.hasAncestor(
10191                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10192                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10193                }
10194            } catch (PackageManagerException e) {
10195                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10196                    throw e;
10197                }
10198                // The signature has changed, but this package is in the system
10199                // image...  let's recover!
10200                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10201                // However...  if this package is part of a shared user, but it
10202                // doesn't match the signature of the shared user, let's fail.
10203                // What this means is that you can't change the signatures
10204                // associated with an overall shared user, which doesn't seem all
10205                // that unreasonable.
10206                if (signatureCheckPs.sharedUser != null) {
10207                    if (compareSignatures(
10208                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10209                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10210                        throw new PackageManagerException(
10211                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10212                                "Signature mismatch for shared user: "
10213                                        + pkgSetting.sharedUser);
10214                    }
10215                }
10216                // File a report about this.
10217                String msg = "System package " + pkg.packageName
10218                        + " signature changed; retaining data.";
10219                reportSettingsProblem(Log.WARN, msg);
10220            } catch (IllegalArgumentException e) {
10221
10222                // should never happen: certs matched when checking, but not when comparing
10223                // old to new for sharedUser
10224                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10225                        "Signing certificates comparison made on incomparable signing details"
10226                        + " but somehow passed verifySignatures!");
10227            }
10228        }
10229
10230        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10231            // This package wants to adopt ownership of permissions from
10232            // another package.
10233            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10234                final String origName = pkg.mAdoptPermissions.get(i);
10235                final PackageSetting orig = mSettings.getPackageLPr(origName);
10236                if (orig != null) {
10237                    if (verifyPackageUpdateLPr(orig, pkg)) {
10238                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10239                                + pkg.packageName);
10240                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10241                    }
10242                }
10243            }
10244        }
10245
10246        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10247            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10248                final String codePathString = changedAbiCodePath.get(i);
10249                try {
10250                    mInstaller.rmdex(codePathString,
10251                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10252                } catch (InstallerException ignored) {
10253                }
10254            }
10255        }
10256
10257        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10258            if (oldPkgSetting != null) {
10259                synchronized (mPackages) {
10260                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10261                }
10262            }
10263        } else {
10264            final int userId = user == null ? 0 : user.getIdentifier();
10265            // Modify state for the given package setting
10266            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10267                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10268            if (pkgSetting.getInstantApp(userId)) {
10269                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10270            }
10271        }
10272    }
10273
10274    /**
10275     * Returns the "real" name of the package.
10276     * <p>This may differ from the package's actual name if the application has already
10277     * been installed under one of this package's original names.
10278     */
10279    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10280            @Nullable String renamedPkgName) {
10281        if (isPackageRenamed(pkg, renamedPkgName)) {
10282            return pkg.mRealPackage;
10283        }
10284        return null;
10285    }
10286
10287    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10288    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10289            @Nullable String renamedPkgName) {
10290        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10291    }
10292
10293    /**
10294     * Returns the original package setting.
10295     * <p>A package can migrate its name during an update. In this scenario, a package
10296     * designates a set of names that it considers as one of its original names.
10297     * <p>An original package must be signed identically and it must have the same
10298     * shared user [if any].
10299     */
10300    @GuardedBy("mPackages")
10301    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10302            @Nullable String renamedPkgName) {
10303        if (!isPackageRenamed(pkg, renamedPkgName)) {
10304            return null;
10305        }
10306        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10307            final PackageSetting originalPs =
10308                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10309            if (originalPs != null) {
10310                // the package is already installed under its original name...
10311                // but, should we use it?
10312                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10313                    // the new package is incompatible with the original
10314                    continue;
10315                } else if (originalPs.sharedUser != null) {
10316                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10317                        // the shared user id is incompatible with the original
10318                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10319                                + " to " + pkg.packageName + ": old uid "
10320                                + originalPs.sharedUser.name
10321                                + " differs from " + pkg.mSharedUserId);
10322                        continue;
10323                    }
10324                    // TODO: Add case when shared user id is added [b/28144775]
10325                } else {
10326                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10327                            + pkg.packageName + " to old name " + originalPs.name);
10328                }
10329                return originalPs;
10330            }
10331        }
10332        return null;
10333    }
10334
10335    /**
10336     * Renames the package if it was installed under a different name.
10337     * <p>When we've already installed the package under an original name, update
10338     * the new package so we can continue to have the old name.
10339     */
10340    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10341            @NonNull String renamedPackageName) {
10342        if (pkg.mOriginalPackages == null
10343                || !pkg.mOriginalPackages.contains(renamedPackageName)
10344                || pkg.packageName.equals(renamedPackageName)) {
10345            return;
10346        }
10347        pkg.setPackageName(renamedPackageName);
10348    }
10349
10350    /**
10351     * Just scans the package without any side effects.
10352     * <p>Not entirely true at the moment. There is still one side effect -- this
10353     * method potentially modifies a live {@link PackageSetting} object representing
10354     * the package being scanned. This will be resolved in the future.
10355     *
10356     * @param request Information about the package to be scanned
10357     * @param isUnderFactoryTest Whether or not the device is under factory test
10358     * @param currentTime The current time, in millis
10359     * @return The results of the scan
10360     */
10361    @GuardedBy("mInstallLock")
10362    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10363            boolean isUnderFactoryTest, long currentTime)
10364                    throws PackageManagerException {
10365        final PackageParser.Package pkg = request.pkg;
10366        PackageSetting pkgSetting = request.pkgSetting;
10367        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10368        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10369        final @ParseFlags int parseFlags = request.parseFlags;
10370        final @ScanFlags int scanFlags = request.scanFlags;
10371        final String realPkgName = request.realPkgName;
10372        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10373        final UserHandle user = request.user;
10374        final boolean isPlatformPackage = request.isPlatformPackage;
10375
10376        List<String> changedAbiCodePath = null;
10377
10378        if (DEBUG_PACKAGE_SCANNING) {
10379            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10380                Log.d(TAG, "Scanning package " + pkg.packageName);
10381        }
10382
10383        if (Build.IS_DEBUGGABLE &&
10384                pkg.isPrivileged() &&
10385                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10386            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10387        }
10388
10389        // Initialize package source and resource directories
10390        final File scanFile = new File(pkg.codePath);
10391        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10392        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10393
10394        // We keep references to the derived CPU Abis from settings in oder to reuse
10395        // them in the case where we're not upgrading or booting for the first time.
10396        String primaryCpuAbiFromSettings = null;
10397        String secondaryCpuAbiFromSettings = null;
10398        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10399
10400        if (!needToDeriveAbi) {
10401            if (pkgSetting != null) {
10402                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10403                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10404            } else {
10405                // Re-scanning a system package after uninstalling updates; need to derive ABI
10406                needToDeriveAbi = true;
10407            }
10408        }
10409
10410        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10411            PackageManagerService.reportSettingsProblem(Log.WARN,
10412                    "Package " + pkg.packageName + " shared user changed from "
10413                            + (pkgSetting.sharedUser != null
10414                            ? pkgSetting.sharedUser.name : "<nothing>")
10415                            + " to "
10416                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10417                            + "; replacing with new");
10418            pkgSetting = null;
10419        }
10420
10421        String[] usesStaticLibraries = null;
10422        if (pkg.usesStaticLibraries != null) {
10423            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10424            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10425        }
10426        final boolean createNewPackage = (pkgSetting == null);
10427        if (createNewPackage) {
10428            final String parentPackageName = (pkg.parentPackage != null)
10429                    ? pkg.parentPackage.packageName : null;
10430            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10431            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10432            // REMOVE SharedUserSetting from method; update in a separate call
10433            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10434                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10435                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10436                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10437                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10438                    user, true /*allowInstall*/, instantApp, virtualPreload,
10439                    parentPackageName, pkg.getChildPackageNames(),
10440                    UserManagerService.getInstance(), usesStaticLibraries,
10441                    pkg.usesStaticLibrariesVersions);
10442        } else {
10443            // REMOVE SharedUserSetting from method; update in a separate call.
10444            //
10445            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10446            // secondaryCpuAbi are not known at this point so we always update them
10447            // to null here, only to reset them at a later point.
10448            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10449                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10450                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10451                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10452                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10453                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10454        }
10455        if (createNewPackage && originalPkgSetting != null) {
10456            // This is the initial transition from the original package, so,
10457            // fix up the new package's name now. We must do this after looking
10458            // up the package under its new name, so getPackageLP takes care of
10459            // fiddling things correctly.
10460            pkg.setPackageName(originalPkgSetting.name);
10461
10462            // File a report about this.
10463            String msg = "New package " + pkgSetting.realName
10464                    + " renamed to replace old package " + pkgSetting.name;
10465            reportSettingsProblem(Log.WARN, msg);
10466        }
10467
10468        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10469        // for existing packages, change the install state; but, only if it's explicitly specified
10470        if (!createNewPackage) {
10471            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10472            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10473            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10474        }
10475
10476        if (disabledPkgSetting != null) {
10477            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10478        }
10479
10480        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10481        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10482        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10483        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10484        // least restrictive selinux domain.
10485        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10486        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10487        // ensures that all packages continue to run in the same selinux domain.
10488        final int targetSdkVersion =
10489            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10490            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10491        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10492        // They currently can be if the sharedUser apps are signed with the platform key.
10493        final boolean isPrivileged = (sharedUserSetting != null) ?
10494            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10495
10496        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10497                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10498        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10499                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10500
10501        pkg.mExtras = pkgSetting;
10502        pkg.applicationInfo.processName = fixProcessName(
10503                pkg.applicationInfo.packageName,
10504                pkg.applicationInfo.processName);
10505
10506        if (!isPlatformPackage) {
10507            // Get all of our default paths setup
10508            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10509        }
10510
10511        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10512
10513        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10514            if (needToDeriveAbi) {
10515                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10516                final boolean extractNativeLibs = !pkg.isLibrary();
10517                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10518                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10519
10520                // Some system apps still use directory structure for native libraries
10521                // in which case we might end up not detecting abi solely based on apk
10522                // structure. Try to detect abi based on directory structure.
10523                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10524                        pkg.applicationInfo.primaryCpuAbi == null) {
10525                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10526                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10527                }
10528            } else {
10529                // This is not a first boot or an upgrade, don't bother deriving the
10530                // ABI during the scan. Instead, trust the value that was stored in the
10531                // package setting.
10532                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10533                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10534
10535                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10536
10537                if (DEBUG_ABI_SELECTION) {
10538                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10539                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10540                            pkg.applicationInfo.secondaryCpuAbi);
10541                }
10542            }
10543        } else {
10544            if ((scanFlags & SCAN_MOVE) != 0) {
10545                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10546                // but we already have this packages package info in the PackageSetting. We just
10547                // use that and derive the native library path based on the new codepath.
10548                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10549                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10550            }
10551
10552            // Set native library paths again. For moves, the path will be updated based on the
10553            // ABIs we've determined above. For non-moves, the path will be updated based on the
10554            // ABIs we determined during compilation, but the path will depend on the final
10555            // package path (after the rename away from the stage path).
10556            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10557        }
10558
10559        // This is a special case for the "system" package, where the ABI is
10560        // dictated by the zygote configuration (and init.rc). We should keep track
10561        // of this ABI so that we can deal with "normal" applications that run under
10562        // the same UID correctly.
10563        if (isPlatformPackage) {
10564            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10565                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10566        }
10567
10568        // If there's a mismatch between the abi-override in the package setting
10569        // and the abiOverride specified for the install. Warn about this because we
10570        // would've already compiled the app without taking the package setting into
10571        // account.
10572        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10573            if (cpuAbiOverride == null && pkg.packageName != null) {
10574                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10575                        " for package " + pkg.packageName);
10576            }
10577        }
10578
10579        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10580        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10581        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10582
10583        // Copy the derived override back to the parsed package, so that we can
10584        // update the package settings accordingly.
10585        pkg.cpuAbiOverride = cpuAbiOverride;
10586
10587        if (DEBUG_ABI_SELECTION) {
10588            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10589                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10590                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10591        }
10592
10593        // Push the derived path down into PackageSettings so we know what to
10594        // clean up at uninstall time.
10595        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10596
10597        if (DEBUG_ABI_SELECTION) {
10598            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10599                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10600                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10601        }
10602
10603        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10604            // We don't do this here during boot because we can do it all
10605            // at once after scanning all existing packages.
10606            //
10607            // We also do this *before* we perform dexopt on this package, so that
10608            // we can avoid redundant dexopts, and also to make sure we've got the
10609            // code and package path correct.
10610            changedAbiCodePath =
10611                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10612        }
10613
10614        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10615                android.Manifest.permission.FACTORY_TEST)) {
10616            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10617        }
10618
10619        if (isSystemApp(pkg)) {
10620            pkgSetting.isOrphaned = true;
10621        }
10622
10623        // Take care of first install / last update times.
10624        final long scanFileTime = getLastModifiedTime(pkg);
10625        if (currentTime != 0) {
10626            if (pkgSetting.firstInstallTime == 0) {
10627                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10628            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10629                pkgSetting.lastUpdateTime = currentTime;
10630            }
10631        } else if (pkgSetting.firstInstallTime == 0) {
10632            // We need *something*.  Take time time stamp of the file.
10633            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10634        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10635            if (scanFileTime != pkgSetting.timeStamp) {
10636                // A package on the system image has changed; consider this
10637                // to be an update.
10638                pkgSetting.lastUpdateTime = scanFileTime;
10639            }
10640        }
10641        pkgSetting.setTimeStamp(scanFileTime);
10642
10643        pkgSetting.pkg = pkg;
10644        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10645        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10646            pkgSetting.versionCode = pkg.getLongVersionCode();
10647        }
10648        // Update volume if needed
10649        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10650        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10651            Slog.i(PackageManagerService.TAG,
10652                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10653                    + " package " + pkg.packageName
10654                    + " volume from " + pkgSetting.volumeUuid
10655                    + " to " + volumeUuid);
10656            pkgSetting.volumeUuid = volumeUuid;
10657        }
10658
10659        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10660    }
10661
10662    /**
10663     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10664     */
10665    private static boolean apkHasCode(String fileName) {
10666        StrictJarFile jarFile = null;
10667        try {
10668            jarFile = new StrictJarFile(fileName,
10669                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10670            return jarFile.findEntry("classes.dex") != null;
10671        } catch (IOException ignore) {
10672        } finally {
10673            try {
10674                if (jarFile != null) {
10675                    jarFile.close();
10676                }
10677            } catch (IOException ignore) {}
10678        }
10679        return false;
10680    }
10681
10682    /**
10683     * Enforces code policy for the package. This ensures that if an APK has
10684     * declared hasCode="true" in its manifest that the APK actually contains
10685     * code.
10686     *
10687     * @throws PackageManagerException If bytecode could not be found when it should exist
10688     */
10689    private static void assertCodePolicy(PackageParser.Package pkg)
10690            throws PackageManagerException {
10691        final boolean shouldHaveCode =
10692                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10693        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10694            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10695                    "Package " + pkg.baseCodePath + " code is missing");
10696        }
10697
10698        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10699            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10700                final boolean splitShouldHaveCode =
10701                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10702                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10703                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10704                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10705                }
10706            }
10707        }
10708    }
10709
10710    /**
10711     * Applies policy to the parsed package based upon the given policy flags.
10712     * Ensures the package is in a good state.
10713     * <p>
10714     * Implementation detail: This method must NOT have any side effect. It would
10715     * ideally be static, but, it requires locks to read system state.
10716     */
10717    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10718            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10719        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10720            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10721            if (pkg.applicationInfo.isDirectBootAware()) {
10722                // we're direct boot aware; set for all components
10723                for (PackageParser.Service s : pkg.services) {
10724                    s.info.encryptionAware = s.info.directBootAware = true;
10725                }
10726                for (PackageParser.Provider p : pkg.providers) {
10727                    p.info.encryptionAware = p.info.directBootAware = true;
10728                }
10729                for (PackageParser.Activity a : pkg.activities) {
10730                    a.info.encryptionAware = a.info.directBootAware = true;
10731                }
10732                for (PackageParser.Activity r : pkg.receivers) {
10733                    r.info.encryptionAware = r.info.directBootAware = true;
10734                }
10735            }
10736            if (compressedFileExists(pkg.codePath)) {
10737                pkg.isStub = true;
10738            }
10739        } else {
10740            // non system apps can't be flagged as core
10741            pkg.coreApp = false;
10742            // clear flags not applicable to regular apps
10743            pkg.applicationInfo.flags &=
10744                    ~ApplicationInfo.FLAG_PERSISTENT;
10745            pkg.applicationInfo.privateFlags &=
10746                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10747            pkg.applicationInfo.privateFlags &=
10748                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10749            // cap permission priorities
10750            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10751                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10752                    pkg.permissionGroups.get(i).info.priority = 0;
10753                }
10754            }
10755        }
10756        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10757            // clear protected broadcasts
10758            pkg.protectedBroadcasts = null;
10759            // ignore export request for single user receivers
10760            if (pkg.receivers != null) {
10761                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10762                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10763                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10764                        receiver.info.exported = false;
10765                    }
10766                }
10767            }
10768            // ignore export request for single user services
10769            if (pkg.services != null) {
10770                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10771                    final PackageParser.Service service = pkg.services.get(i);
10772                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10773                        service.info.exported = false;
10774                    }
10775                }
10776            }
10777            // ignore export request for single user providers
10778            if (pkg.providers != null) {
10779                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10780                    final PackageParser.Provider provider = pkg.providers.get(i);
10781                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10782                        provider.info.exported = false;
10783                    }
10784                }
10785            }
10786        }
10787
10788        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10789            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10790        }
10791
10792        if ((scanFlags & SCAN_AS_OEM) != 0) {
10793            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10794        }
10795
10796        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10797            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10798        }
10799
10800        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10801            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10802        }
10803
10804        // Check if the package is signed with the same key as the platform package.
10805        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10806                (platformPkg != null && compareSignatures(
10807                        platformPkg.mSigningDetails.signatures,
10808                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10809            pkg.applicationInfo.privateFlags |=
10810                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10811        }
10812
10813        if (!isSystemApp(pkg)) {
10814            // Only system apps can use these features.
10815            pkg.mOriginalPackages = null;
10816            pkg.mRealPackage = null;
10817            pkg.mAdoptPermissions = null;
10818        }
10819    }
10820
10821    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10822            throws PackageManagerException {
10823        if (object == null) {
10824            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10825        }
10826        return object;
10827    }
10828
10829    /**
10830     * Asserts the parsed package is valid according to the given policy. If the
10831     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10832     * <p>
10833     * Implementation detail: This method must NOT have any side effects. It would
10834     * ideally be static, but, it requires locks to read system state.
10835     *
10836     * @throws PackageManagerException If the package fails any of the validation checks
10837     */
10838    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10839            final @ScanFlags int scanFlags)
10840                    throws PackageManagerException {
10841        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10842            assertCodePolicy(pkg);
10843        }
10844
10845        if (pkg.applicationInfo.getCodePath() == null ||
10846                pkg.applicationInfo.getResourcePath() == null) {
10847            // Bail out. The resource and code paths haven't been set.
10848            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10849                    "Code and resource paths haven't been set correctly");
10850        }
10851
10852        // Make sure we're not adding any bogus keyset info
10853        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10854        ksms.assertScannedPackageValid(pkg);
10855
10856        synchronized (mPackages) {
10857            // The special "android" package can only be defined once
10858            if (pkg.packageName.equals("android")) {
10859                if (mAndroidApplication != null) {
10860                    Slog.w(TAG, "*************************************************");
10861                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10862                    Slog.w(TAG, " codePath=" + pkg.codePath);
10863                    Slog.w(TAG, "*************************************************");
10864                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10865                            "Core android package being redefined.  Skipping.");
10866                }
10867            }
10868
10869            // A package name must be unique; don't allow duplicates
10870            if (mPackages.containsKey(pkg.packageName)) {
10871                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10872                        "Application package " + pkg.packageName
10873                        + " already installed.  Skipping duplicate.");
10874            }
10875
10876            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10877                // Static libs have a synthetic package name containing the version
10878                // but we still want the base name to be unique.
10879                if (mPackages.containsKey(pkg.manifestPackageName)) {
10880                    throw new PackageManagerException(
10881                            "Duplicate static shared lib provider package");
10882                }
10883
10884                // Static shared libraries should have at least O target SDK
10885                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10886                    throw new PackageManagerException(
10887                            "Packages declaring static-shared libs must target O SDK or higher");
10888                }
10889
10890                // Package declaring static a shared lib cannot be instant apps
10891                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10892                    throw new PackageManagerException(
10893                            "Packages declaring static-shared libs cannot be instant apps");
10894                }
10895
10896                // Package declaring static a shared lib cannot be renamed since the package
10897                // name is synthetic and apps can't code around package manager internals.
10898                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10899                    throw new PackageManagerException(
10900                            "Packages declaring static-shared libs cannot be renamed");
10901                }
10902
10903                // Package declaring static a shared lib cannot declare child packages
10904                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10905                    throw new PackageManagerException(
10906                            "Packages declaring static-shared libs cannot have child packages");
10907                }
10908
10909                // Package declaring static a shared lib cannot declare dynamic libs
10910                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10911                    throw new PackageManagerException(
10912                            "Packages declaring static-shared libs cannot declare dynamic libs");
10913                }
10914
10915                // Package declaring static a shared lib cannot declare shared users
10916                if (pkg.mSharedUserId != null) {
10917                    throw new PackageManagerException(
10918                            "Packages declaring static-shared libs cannot declare shared users");
10919                }
10920
10921                // Static shared libs cannot declare activities
10922                if (!pkg.activities.isEmpty()) {
10923                    throw new PackageManagerException(
10924                            "Static shared libs cannot declare activities");
10925                }
10926
10927                // Static shared libs cannot declare services
10928                if (!pkg.services.isEmpty()) {
10929                    throw new PackageManagerException(
10930                            "Static shared libs cannot declare services");
10931                }
10932
10933                // Static shared libs cannot declare providers
10934                if (!pkg.providers.isEmpty()) {
10935                    throw new PackageManagerException(
10936                            "Static shared libs cannot declare content providers");
10937                }
10938
10939                // Static shared libs cannot declare receivers
10940                if (!pkg.receivers.isEmpty()) {
10941                    throw new PackageManagerException(
10942                            "Static shared libs cannot declare broadcast receivers");
10943                }
10944
10945                // Static shared libs cannot declare permission groups
10946                if (!pkg.permissionGroups.isEmpty()) {
10947                    throw new PackageManagerException(
10948                            "Static shared libs cannot declare permission groups");
10949                }
10950
10951                // Static shared libs cannot declare permissions
10952                if (!pkg.permissions.isEmpty()) {
10953                    throw new PackageManagerException(
10954                            "Static shared libs cannot declare permissions");
10955                }
10956
10957                // Static shared libs cannot declare protected broadcasts
10958                if (pkg.protectedBroadcasts != null) {
10959                    throw new PackageManagerException(
10960                            "Static shared libs cannot declare protected broadcasts");
10961                }
10962
10963                // Static shared libs cannot be overlay targets
10964                if (pkg.mOverlayTarget != null) {
10965                    throw new PackageManagerException(
10966                            "Static shared libs cannot be overlay targets");
10967                }
10968
10969                // The version codes must be ordered as lib versions
10970                long minVersionCode = Long.MIN_VALUE;
10971                long maxVersionCode = Long.MAX_VALUE;
10972
10973                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10974                        pkg.staticSharedLibName);
10975                if (versionedLib != null) {
10976                    final int versionCount = versionedLib.size();
10977                    for (int i = 0; i < versionCount; i++) {
10978                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10979                        final long libVersionCode = libInfo.getDeclaringPackage()
10980                                .getLongVersionCode();
10981                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10982                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10983                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10984                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10985                        } else {
10986                            minVersionCode = maxVersionCode = libVersionCode;
10987                            break;
10988                        }
10989                    }
10990                }
10991                if (pkg.getLongVersionCode() < minVersionCode
10992                        || pkg.getLongVersionCode() > maxVersionCode) {
10993                    throw new PackageManagerException("Static shared"
10994                            + " lib version codes must be ordered as lib versions");
10995                }
10996            }
10997
10998            // Only privileged apps and updated privileged apps can add child packages.
10999            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11000                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11001                    throw new PackageManagerException("Only privileged apps can add child "
11002                            + "packages. Ignoring package " + pkg.packageName);
11003                }
11004                final int childCount = pkg.childPackages.size();
11005                for (int i = 0; i < childCount; i++) {
11006                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11007                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11008                            childPkg.packageName)) {
11009                        throw new PackageManagerException("Can't override child of "
11010                                + "another disabled app. Ignoring package " + pkg.packageName);
11011                    }
11012                }
11013            }
11014
11015            // If we're only installing presumed-existing packages, require that the
11016            // scanned APK is both already known and at the path previously established
11017            // for it.  Previously unknown packages we pick up normally, but if we have an
11018            // a priori expectation about this package's install presence, enforce it.
11019            // With a singular exception for new system packages. When an OTA contains
11020            // a new system package, we allow the codepath to change from a system location
11021            // to the user-installed location. If we don't allow this change, any newer,
11022            // user-installed version of the application will be ignored.
11023            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11024                if (mExpectingBetter.containsKey(pkg.packageName)) {
11025                    logCriticalInfo(Log.WARN,
11026                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11027                } else {
11028                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11029                    if (known != null) {
11030                        if (DEBUG_PACKAGE_SCANNING) {
11031                            Log.d(TAG, "Examining " + pkg.codePath
11032                                    + " and requiring known paths " + known.codePathString
11033                                    + " & " + known.resourcePathString);
11034                        }
11035                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11036                                || !pkg.applicationInfo.getResourcePath().equals(
11037                                        known.resourcePathString)) {
11038                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11039                                    "Application package " + pkg.packageName
11040                                    + " found at " + pkg.applicationInfo.getCodePath()
11041                                    + " but expected at " + known.codePathString
11042                                    + "; ignoring.");
11043                        }
11044                    } else {
11045                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11046                                "Application package " + pkg.packageName
11047                                + " not found; ignoring.");
11048                    }
11049                }
11050            }
11051
11052            // Verify that this new package doesn't have any content providers
11053            // that conflict with existing packages.  Only do this if the
11054            // package isn't already installed, since we don't want to break
11055            // things that are installed.
11056            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11057                final int N = pkg.providers.size();
11058                int i;
11059                for (i=0; i<N; i++) {
11060                    PackageParser.Provider p = pkg.providers.get(i);
11061                    if (p.info.authority != null) {
11062                        String names[] = p.info.authority.split(";");
11063                        for (int j = 0; j < names.length; j++) {
11064                            if (mProvidersByAuthority.containsKey(names[j])) {
11065                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11066                                final String otherPackageName =
11067                                        ((other != null && other.getComponentName() != null) ?
11068                                                other.getComponentName().getPackageName() : "?");
11069                                throw new PackageManagerException(
11070                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11071                                        "Can't install because provider name " + names[j]
11072                                                + " (in package " + pkg.applicationInfo.packageName
11073                                                + ") is already used by " + otherPackageName);
11074                            }
11075                        }
11076                    }
11077                }
11078            }
11079
11080            // Verify that packages sharing a user with a privileged app are marked as privileged.
11081            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11082                SharedUserSetting sharedUserSetting = null;
11083                try {
11084                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11085                } catch (PackageManagerException ignore) {}
11086                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11087                    // Exempt SharedUsers signed with the platform key.
11088                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11089                    if ((platformPkgSetting.signatures.mSigningDetails
11090                            != PackageParser.SigningDetails.UNKNOWN)
11091                            && (compareSignatures(
11092                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11093                                    pkg.mSigningDetails.signatures)
11094                                            != PackageManager.SIGNATURE_MATCH)) {
11095                        throw new PackageManagerException("Apps that share a user with a " +
11096                                "privileged app must themselves be marked as privileged. " +
11097                                pkg.packageName + " shares privileged user " +
11098                                pkg.mSharedUserId + ".");
11099                    }
11100                }
11101            }
11102
11103            // Apply policies specific for runtime resource overlays (RROs).
11104            if (pkg.mOverlayTarget != null) {
11105                // System overlays have some restrictions on their use of the 'static' state.
11106                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11107                    // We are scanning a system overlay. This can be the first scan of the
11108                    // system/vendor/oem partition, or an update to the system overlay.
11109                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11110                        // This must be an update to a system overlay.
11111                        final PackageSetting previousPkg = assertNotNull(
11112                                mSettings.getPackageLPr(pkg.packageName),
11113                                "previous package state not present");
11114
11115                        // Static overlays cannot be updated.
11116                        if (previousPkg.pkg.mOverlayIsStatic) {
11117                            throw new PackageManagerException("Overlay " + pkg.packageName +
11118                                    " is static and cannot be upgraded.");
11119                        // Non-static overlays cannot be converted to static overlays.
11120                        } else if (pkg.mOverlayIsStatic) {
11121                            throw new PackageManagerException("Overlay " + pkg.packageName +
11122                                    " cannot be upgraded into a static overlay.");
11123                        }
11124                    }
11125                } else {
11126                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11127                    if (pkg.mOverlayIsStatic) {
11128                        throw new PackageManagerException("Overlay " + pkg.packageName +
11129                                " is static but not pre-installed.");
11130                    }
11131
11132                    // The only case where we allow installation of a non-system overlay is when
11133                    // its signature is signed with the platform certificate.
11134                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11135                    if ((platformPkgSetting.signatures.mSigningDetails
11136                            != PackageParser.SigningDetails.UNKNOWN)
11137                            && (compareSignatures(
11138                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11139                                    pkg.mSigningDetails.signatures)
11140                                            != PackageManager.SIGNATURE_MATCH)) {
11141                        throw new PackageManagerException("Overlay " + pkg.packageName +
11142                                " must be signed with the platform certificate.");
11143                    }
11144                }
11145            }
11146        }
11147    }
11148
11149    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11150            int type, String declaringPackageName, long declaringVersionCode) {
11151        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11152        if (versionedLib == null) {
11153            versionedLib = new LongSparseArray<>();
11154            mSharedLibraries.put(name, versionedLib);
11155            if (type == SharedLibraryInfo.TYPE_STATIC) {
11156                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11157            }
11158        } else if (versionedLib.indexOfKey(version) >= 0) {
11159            return false;
11160        }
11161        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11162                version, type, declaringPackageName, declaringVersionCode);
11163        versionedLib.put(version, libEntry);
11164        return true;
11165    }
11166
11167    private boolean removeSharedLibraryLPw(String name, long version) {
11168        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11169        if (versionedLib == null) {
11170            return false;
11171        }
11172        final int libIdx = versionedLib.indexOfKey(version);
11173        if (libIdx < 0) {
11174            return false;
11175        }
11176        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11177        versionedLib.remove(version);
11178        if (versionedLib.size() <= 0) {
11179            mSharedLibraries.remove(name);
11180            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11181                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11182                        .getPackageName());
11183            }
11184        }
11185        return true;
11186    }
11187
11188    /**
11189     * Adds a scanned package to the system. When this method is finished, the package will
11190     * be available for query, resolution, etc...
11191     */
11192    private void commitPackageSettings(PackageParser.Package pkg,
11193            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11194            final @ScanFlags int scanFlags, boolean chatty) {
11195        final String pkgName = pkg.packageName;
11196        if (mCustomResolverComponentName != null &&
11197                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11198            setUpCustomResolverActivity(pkg);
11199        }
11200
11201        if (pkg.packageName.equals("android")) {
11202            synchronized (mPackages) {
11203                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11204                    // Set up information for our fall-back user intent resolution activity.
11205                    mPlatformPackage = pkg;
11206                    pkg.mVersionCode = mSdkVersion;
11207                    pkg.mVersionCodeMajor = 0;
11208                    mAndroidApplication = pkg.applicationInfo;
11209                    if (!mResolverReplaced) {
11210                        mResolveActivity.applicationInfo = mAndroidApplication;
11211                        mResolveActivity.name = ResolverActivity.class.getName();
11212                        mResolveActivity.packageName = mAndroidApplication.packageName;
11213                        mResolveActivity.processName = "system:ui";
11214                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11215                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11216                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11217                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11218                        mResolveActivity.exported = true;
11219                        mResolveActivity.enabled = true;
11220                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11221                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11222                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11223                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11224                                | ActivityInfo.CONFIG_ORIENTATION
11225                                | ActivityInfo.CONFIG_KEYBOARD
11226                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11227                        mResolveInfo.activityInfo = mResolveActivity;
11228                        mResolveInfo.priority = 0;
11229                        mResolveInfo.preferredOrder = 0;
11230                        mResolveInfo.match = 0;
11231                        mResolveComponentName = new ComponentName(
11232                                mAndroidApplication.packageName, mResolveActivity.name);
11233                    }
11234                }
11235            }
11236        }
11237
11238        ArrayList<PackageParser.Package> clientLibPkgs = null;
11239        // writer
11240        synchronized (mPackages) {
11241            boolean hasStaticSharedLibs = false;
11242
11243            // Any app can add new static shared libraries
11244            if (pkg.staticSharedLibName != null) {
11245                // Static shared libs don't allow renaming as they have synthetic package
11246                // names to allow install of multiple versions, so use name from manifest.
11247                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11248                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11249                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11250                    hasStaticSharedLibs = true;
11251                } else {
11252                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11253                                + pkg.staticSharedLibName + " already exists; skipping");
11254                }
11255                // Static shared libs cannot be updated once installed since they
11256                // use synthetic package name which includes the version code, so
11257                // not need to update other packages's shared lib dependencies.
11258            }
11259
11260            if (!hasStaticSharedLibs
11261                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11262                // Only system apps can add new dynamic shared libraries.
11263                if (pkg.libraryNames != null) {
11264                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11265                        String name = pkg.libraryNames.get(i);
11266                        boolean allowed = false;
11267                        if (pkg.isUpdatedSystemApp()) {
11268                            // New library entries can only be added through the
11269                            // system image.  This is important to get rid of a lot
11270                            // of nasty edge cases: for example if we allowed a non-
11271                            // system update of the app to add a library, then uninstalling
11272                            // the update would make the library go away, and assumptions
11273                            // we made such as through app install filtering would now
11274                            // have allowed apps on the device which aren't compatible
11275                            // with it.  Better to just have the restriction here, be
11276                            // conservative, and create many fewer cases that can negatively
11277                            // impact the user experience.
11278                            final PackageSetting sysPs = mSettings
11279                                    .getDisabledSystemPkgLPr(pkg.packageName);
11280                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11281                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11282                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11283                                        allowed = true;
11284                                        break;
11285                                    }
11286                                }
11287                            }
11288                        } else {
11289                            allowed = true;
11290                        }
11291                        if (allowed) {
11292                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11293                                    SharedLibraryInfo.VERSION_UNDEFINED,
11294                                    SharedLibraryInfo.TYPE_DYNAMIC,
11295                                    pkg.packageName, pkg.getLongVersionCode())) {
11296                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11297                                        + name + " already exists; skipping");
11298                            }
11299                        } else {
11300                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11301                                    + name + " that is not declared on system image; skipping");
11302                        }
11303                    }
11304
11305                    if ((scanFlags & SCAN_BOOTING) == 0) {
11306                        // If we are not booting, we need to update any applications
11307                        // that are clients of our shared library.  If we are booting,
11308                        // this will all be done once the scan is complete.
11309                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11310                    }
11311                }
11312            }
11313        }
11314
11315        if ((scanFlags & SCAN_BOOTING) != 0) {
11316            // No apps can run during boot scan, so they don't need to be frozen
11317        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11318            // Caller asked to not kill app, so it's probably not frozen
11319        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11320            // Caller asked us to ignore frozen check for some reason; they
11321            // probably didn't know the package name
11322        } else {
11323            // We're doing major surgery on this package, so it better be frozen
11324            // right now to keep it from launching
11325            checkPackageFrozen(pkgName);
11326        }
11327
11328        // Also need to kill any apps that are dependent on the library.
11329        if (clientLibPkgs != null) {
11330            for (int i=0; i<clientLibPkgs.size(); i++) {
11331                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11332                killApplication(clientPkg.applicationInfo.packageName,
11333                        clientPkg.applicationInfo.uid, "update lib");
11334            }
11335        }
11336
11337        // writer
11338        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11339
11340        synchronized (mPackages) {
11341            // We don't expect installation to fail beyond this point
11342
11343            // Add the new setting to mSettings
11344            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11345            // Add the new setting to mPackages
11346            mPackages.put(pkg.applicationInfo.packageName, pkg);
11347            // Make sure we don't accidentally delete its data.
11348            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11349            while (iter.hasNext()) {
11350                PackageCleanItem item = iter.next();
11351                if (pkgName.equals(item.packageName)) {
11352                    iter.remove();
11353                }
11354            }
11355
11356            // Add the package's KeySets to the global KeySetManagerService
11357            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11358            ksms.addScannedPackageLPw(pkg);
11359
11360            int N = pkg.providers.size();
11361            StringBuilder r = null;
11362            int i;
11363            for (i=0; i<N; i++) {
11364                PackageParser.Provider p = pkg.providers.get(i);
11365                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11366                        p.info.processName);
11367                mProviders.addProvider(p);
11368                p.syncable = p.info.isSyncable;
11369                if (p.info.authority != null) {
11370                    String names[] = p.info.authority.split(";");
11371                    p.info.authority = null;
11372                    for (int j = 0; j < names.length; j++) {
11373                        if (j == 1 && p.syncable) {
11374                            // We only want the first authority for a provider to possibly be
11375                            // syncable, so if we already added this provider using a different
11376                            // authority clear the syncable flag. We copy the provider before
11377                            // changing it because the mProviders object contains a reference
11378                            // to a provider that we don't want to change.
11379                            // Only do this for the second authority since the resulting provider
11380                            // object can be the same for all future authorities for this provider.
11381                            p = new PackageParser.Provider(p);
11382                            p.syncable = false;
11383                        }
11384                        if (!mProvidersByAuthority.containsKey(names[j])) {
11385                            mProvidersByAuthority.put(names[j], p);
11386                            if (p.info.authority == null) {
11387                                p.info.authority = names[j];
11388                            } else {
11389                                p.info.authority = p.info.authority + ";" + names[j];
11390                            }
11391                            if (DEBUG_PACKAGE_SCANNING) {
11392                                if (chatty)
11393                                    Log.d(TAG, "Registered content provider: " + names[j]
11394                                            + ", className = " + p.info.name + ", isSyncable = "
11395                                            + p.info.isSyncable);
11396                            }
11397                        } else {
11398                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11399                            Slog.w(TAG, "Skipping provider name " + names[j] +
11400                                    " (in package " + pkg.applicationInfo.packageName +
11401                                    "): name already used by "
11402                                    + ((other != null && other.getComponentName() != null)
11403                                            ? other.getComponentName().getPackageName() : "?"));
11404                        }
11405                    }
11406                }
11407                if (chatty) {
11408                    if (r == null) {
11409                        r = new StringBuilder(256);
11410                    } else {
11411                        r.append(' ');
11412                    }
11413                    r.append(p.info.name);
11414                }
11415            }
11416            if (r != null) {
11417                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11418            }
11419
11420            N = pkg.services.size();
11421            r = null;
11422            for (i=0; i<N; i++) {
11423                PackageParser.Service s = pkg.services.get(i);
11424                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11425                        s.info.processName);
11426                mServices.addService(s);
11427                if (chatty) {
11428                    if (r == null) {
11429                        r = new StringBuilder(256);
11430                    } else {
11431                        r.append(' ');
11432                    }
11433                    r.append(s.info.name);
11434                }
11435            }
11436            if (r != null) {
11437                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11438            }
11439
11440            N = pkg.receivers.size();
11441            r = null;
11442            for (i=0; i<N; i++) {
11443                PackageParser.Activity a = pkg.receivers.get(i);
11444                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11445                        a.info.processName);
11446                mReceivers.addActivity(a, "receiver");
11447                if (chatty) {
11448                    if (r == null) {
11449                        r = new StringBuilder(256);
11450                    } else {
11451                        r.append(' ');
11452                    }
11453                    r.append(a.info.name);
11454                }
11455            }
11456            if (r != null) {
11457                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11458            }
11459
11460            N = pkg.activities.size();
11461            r = null;
11462            for (i=0; i<N; i++) {
11463                PackageParser.Activity a = pkg.activities.get(i);
11464                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11465                        a.info.processName);
11466                mActivities.addActivity(a, "activity");
11467                if (chatty) {
11468                    if (r == null) {
11469                        r = new StringBuilder(256);
11470                    } else {
11471                        r.append(' ');
11472                    }
11473                    r.append(a.info.name);
11474                }
11475            }
11476            if (r != null) {
11477                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11478            }
11479
11480            // Don't allow ephemeral applications to define new permissions groups.
11481            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11482                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11483                        + " ignored: instant apps cannot define new permission groups.");
11484            } else {
11485                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11486            }
11487
11488            // Don't allow ephemeral applications to define new permissions.
11489            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11490                Slog.w(TAG, "Permissions from package " + pkg.packageName
11491                        + " ignored: instant apps cannot define new permissions.");
11492            } else {
11493                mPermissionManager.addAllPermissions(pkg, chatty);
11494            }
11495
11496            N = pkg.instrumentation.size();
11497            r = null;
11498            for (i=0; i<N; i++) {
11499                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11500                a.info.packageName = pkg.applicationInfo.packageName;
11501                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11502                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11503                a.info.splitNames = pkg.splitNames;
11504                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11505                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11506                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11507                a.info.dataDir = pkg.applicationInfo.dataDir;
11508                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11509                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11510                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11511                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11512                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11513                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11514                mInstrumentation.put(a.getComponentName(), a);
11515                if (chatty) {
11516                    if (r == null) {
11517                        r = new StringBuilder(256);
11518                    } else {
11519                        r.append(' ');
11520                    }
11521                    r.append(a.info.name);
11522                }
11523            }
11524            if (r != null) {
11525                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11526            }
11527
11528            if (pkg.protectedBroadcasts != null) {
11529                N = pkg.protectedBroadcasts.size();
11530                synchronized (mProtectedBroadcasts) {
11531                    for (i = 0; i < N; i++) {
11532                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11533                    }
11534                }
11535            }
11536
11537            if (oldPkg != null) {
11538                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11539                // revoke callbacks from this method might need to kill apps which need the
11540                // mPackages lock on a different thread. This would dead lock.
11541                //
11542                // Hence create a copy of all package names and pass it into
11543                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11544                // revoked. If a new package is added before the async code runs the permission
11545                // won't be granted yet, hence new packages are no problem.
11546                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11547
11548                AsyncTask.execute(() ->
11549                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11550                                allPackageNames, mPermissionCallback));
11551            }
11552        }
11553
11554        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11555    }
11556
11557    /**
11558     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11559     * is derived purely on the basis of the contents of {@code scanFile} and
11560     * {@code cpuAbiOverride}.
11561     *
11562     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11563     */
11564    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11565            boolean extractLibs)
11566                    throws PackageManagerException {
11567        // Give ourselves some initial paths; we'll come back for another
11568        // pass once we've determined ABI below.
11569        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11570
11571        // We would never need to extract libs for forward-locked and external packages,
11572        // since the container service will do it for us. We shouldn't attempt to
11573        // extract libs from system app when it was not updated.
11574        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11575                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11576            extractLibs = false;
11577        }
11578
11579        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11580        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11581
11582        NativeLibraryHelper.Handle handle = null;
11583        try {
11584            handle = NativeLibraryHelper.Handle.create(pkg);
11585            // TODO(multiArch): This can be null for apps that didn't go through the
11586            // usual installation process. We can calculate it again, like we
11587            // do during install time.
11588            //
11589            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11590            // unnecessary.
11591            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11592
11593            // Null out the abis so that they can be recalculated.
11594            pkg.applicationInfo.primaryCpuAbi = null;
11595            pkg.applicationInfo.secondaryCpuAbi = null;
11596            if (isMultiArch(pkg.applicationInfo)) {
11597                // Warn if we've set an abiOverride for multi-lib packages..
11598                // By definition, we need to copy both 32 and 64 bit libraries for
11599                // such packages.
11600                if (pkg.cpuAbiOverride != null
11601                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11602                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11603                }
11604
11605                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11606                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11607                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11608                    if (extractLibs) {
11609                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11610                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11611                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11612                                useIsaSpecificSubdirs);
11613                    } else {
11614                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11615                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11616                    }
11617                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11618                }
11619
11620                // Shared library native code should be in the APK zip aligned
11621                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11622                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11623                            "Shared library native lib extraction not supported");
11624                }
11625
11626                maybeThrowExceptionForMultiArchCopy(
11627                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11628
11629                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11630                    if (extractLibs) {
11631                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11632                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11633                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11634                                useIsaSpecificSubdirs);
11635                    } else {
11636                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11637                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11638                    }
11639                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11640                }
11641
11642                maybeThrowExceptionForMultiArchCopy(
11643                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11644
11645                if (abi64 >= 0) {
11646                    // Shared library native libs should be in the APK zip aligned
11647                    if (extractLibs && pkg.isLibrary()) {
11648                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11649                                "Shared library native lib extraction not supported");
11650                    }
11651                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11652                }
11653
11654                if (abi32 >= 0) {
11655                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11656                    if (abi64 >= 0) {
11657                        if (pkg.use32bitAbi) {
11658                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11659                            pkg.applicationInfo.primaryCpuAbi = abi;
11660                        } else {
11661                            pkg.applicationInfo.secondaryCpuAbi = abi;
11662                        }
11663                    } else {
11664                        pkg.applicationInfo.primaryCpuAbi = abi;
11665                    }
11666                }
11667            } else {
11668                String[] abiList = (cpuAbiOverride != null) ?
11669                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11670
11671                // Enable gross and lame hacks for apps that are built with old
11672                // SDK tools. We must scan their APKs for renderscript bitcode and
11673                // not launch them if it's present. Don't bother checking on devices
11674                // that don't have 64 bit support.
11675                boolean needsRenderScriptOverride = false;
11676                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11677                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11678                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11679                    needsRenderScriptOverride = true;
11680                }
11681
11682                final int copyRet;
11683                if (extractLibs) {
11684                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11685                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11686                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11687                } else {
11688                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11689                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11690                }
11691                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11692
11693                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11694                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11695                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11696                }
11697
11698                if (copyRet >= 0) {
11699                    // Shared libraries that have native libs must be multi-architecture
11700                    if (pkg.isLibrary()) {
11701                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11702                                "Shared library with native libs must be multiarch");
11703                    }
11704                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11705                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11706                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11707                } else if (needsRenderScriptOverride) {
11708                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11709                }
11710            }
11711        } catch (IOException ioe) {
11712            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11713        } finally {
11714            IoUtils.closeQuietly(handle);
11715        }
11716
11717        // Now that we've calculated the ABIs and determined if it's an internal app,
11718        // we will go ahead and populate the nativeLibraryPath.
11719        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11720    }
11721
11722    /**
11723     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11724     * i.e, so that all packages can be run inside a single process if required.
11725     *
11726     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11727     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11728     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11729     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11730     * updating a package that belongs to a shared user.
11731     *
11732     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11733     * adds unnecessary complexity.
11734     */
11735    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11736            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11737        List<String> changedAbiCodePath = null;
11738        String requiredInstructionSet = null;
11739        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11740            requiredInstructionSet = VMRuntime.getInstructionSet(
11741                     scannedPackage.applicationInfo.primaryCpuAbi);
11742        }
11743
11744        PackageSetting requirer = null;
11745        for (PackageSetting ps : packagesForUser) {
11746            // If packagesForUser contains scannedPackage, we skip it. This will happen
11747            // when scannedPackage is an update of an existing package. Without this check,
11748            // we will never be able to change the ABI of any package belonging to a shared
11749            // user, even if it's compatible with other packages.
11750            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11751                if (ps.primaryCpuAbiString == null) {
11752                    continue;
11753                }
11754
11755                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11756                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11757                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11758                    // this but there's not much we can do.
11759                    String errorMessage = "Instruction set mismatch, "
11760                            + ((requirer == null) ? "[caller]" : requirer)
11761                            + " requires " + requiredInstructionSet + " whereas " + ps
11762                            + " requires " + instructionSet;
11763                    Slog.w(TAG, errorMessage);
11764                }
11765
11766                if (requiredInstructionSet == null) {
11767                    requiredInstructionSet = instructionSet;
11768                    requirer = ps;
11769                }
11770            }
11771        }
11772
11773        if (requiredInstructionSet != null) {
11774            String adjustedAbi;
11775            if (requirer != null) {
11776                // requirer != null implies that either scannedPackage was null or that scannedPackage
11777                // did not require an ABI, in which case we have to adjust scannedPackage to match
11778                // the ABI of the set (which is the same as requirer's ABI)
11779                adjustedAbi = requirer.primaryCpuAbiString;
11780                if (scannedPackage != null) {
11781                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11782                }
11783            } else {
11784                // requirer == null implies that we're updating all ABIs in the set to
11785                // match scannedPackage.
11786                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11787            }
11788
11789            for (PackageSetting ps : packagesForUser) {
11790                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11791                    if (ps.primaryCpuAbiString != null) {
11792                        continue;
11793                    }
11794
11795                    ps.primaryCpuAbiString = adjustedAbi;
11796                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11797                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11798                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11799                        if (DEBUG_ABI_SELECTION) {
11800                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11801                                    + " (requirer="
11802                                    + (requirer != null ? requirer.pkg : "null")
11803                                    + ", scannedPackage="
11804                                    + (scannedPackage != null ? scannedPackage : "null")
11805                                    + ")");
11806                        }
11807                        if (changedAbiCodePath == null) {
11808                            changedAbiCodePath = new ArrayList<>();
11809                        }
11810                        changedAbiCodePath.add(ps.codePathString);
11811                    }
11812                }
11813            }
11814        }
11815        return changedAbiCodePath;
11816    }
11817
11818    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11819        synchronized (mPackages) {
11820            mResolverReplaced = true;
11821            // Set up information for custom user intent resolution activity.
11822            mResolveActivity.applicationInfo = pkg.applicationInfo;
11823            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11824            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11825            mResolveActivity.processName = pkg.applicationInfo.packageName;
11826            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11827            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11828                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11829            mResolveActivity.theme = 0;
11830            mResolveActivity.exported = true;
11831            mResolveActivity.enabled = true;
11832            mResolveInfo.activityInfo = mResolveActivity;
11833            mResolveInfo.priority = 0;
11834            mResolveInfo.preferredOrder = 0;
11835            mResolveInfo.match = 0;
11836            mResolveComponentName = mCustomResolverComponentName;
11837            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11838                    mResolveComponentName);
11839        }
11840    }
11841
11842    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11843        if (installerActivity == null) {
11844            if (DEBUG_INSTANT) {
11845                Slog.d(TAG, "Clear ephemeral installer activity");
11846            }
11847            mInstantAppInstallerActivity = null;
11848            return;
11849        }
11850
11851        if (DEBUG_INSTANT) {
11852            Slog.d(TAG, "Set ephemeral installer activity: "
11853                    + installerActivity.getComponentName());
11854        }
11855        // Set up information for ephemeral installer activity
11856        mInstantAppInstallerActivity = installerActivity;
11857        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11858                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11859        mInstantAppInstallerActivity.exported = true;
11860        mInstantAppInstallerActivity.enabled = true;
11861        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11862        mInstantAppInstallerInfo.priority = 1;
11863        mInstantAppInstallerInfo.preferredOrder = 1;
11864        mInstantAppInstallerInfo.isDefault = true;
11865        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11866                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11867    }
11868
11869    private static String calculateBundledApkRoot(final String codePathString) {
11870        final File codePath = new File(codePathString);
11871        final File codeRoot;
11872        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11873            codeRoot = Environment.getRootDirectory();
11874        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11875            codeRoot = Environment.getOemDirectory();
11876        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11877            codeRoot = Environment.getVendorDirectory();
11878        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11879            codeRoot = Environment.getOdmDirectory();
11880        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11881            codeRoot = Environment.getProductDirectory();
11882        } else {
11883            // Unrecognized code path; take its top real segment as the apk root:
11884            // e.g. /something/app/blah.apk => /something
11885            try {
11886                File f = codePath.getCanonicalFile();
11887                File parent = f.getParentFile();    // non-null because codePath is a file
11888                File tmp;
11889                while ((tmp = parent.getParentFile()) != null) {
11890                    f = parent;
11891                    parent = tmp;
11892                }
11893                codeRoot = f;
11894                Slog.w(TAG, "Unrecognized code path "
11895                        + codePath + " - using " + codeRoot);
11896            } catch (IOException e) {
11897                // Can't canonicalize the code path -- shenanigans?
11898                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11899                return Environment.getRootDirectory().getPath();
11900            }
11901        }
11902        return codeRoot.getPath();
11903    }
11904
11905    /**
11906     * Derive and set the location of native libraries for the given package,
11907     * which varies depending on where and how the package was installed.
11908     */
11909    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11910        final ApplicationInfo info = pkg.applicationInfo;
11911        final String codePath = pkg.codePath;
11912        final File codeFile = new File(codePath);
11913        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11914        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11915
11916        info.nativeLibraryRootDir = null;
11917        info.nativeLibraryRootRequiresIsa = false;
11918        info.nativeLibraryDir = null;
11919        info.secondaryNativeLibraryDir = null;
11920
11921        if (isApkFile(codeFile)) {
11922            // Monolithic install
11923            if (bundledApp) {
11924                // If "/system/lib64/apkname" exists, assume that is the per-package
11925                // native library directory to use; otherwise use "/system/lib/apkname".
11926                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11927                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11928                        getPrimaryInstructionSet(info));
11929
11930                // This is a bundled system app so choose the path based on the ABI.
11931                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11932                // is just the default path.
11933                final String apkName = deriveCodePathName(codePath);
11934                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11935                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11936                        apkName).getAbsolutePath();
11937
11938                if (info.secondaryCpuAbi != null) {
11939                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11940                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11941                            secondaryLibDir, apkName).getAbsolutePath();
11942                }
11943            } else if (asecApp) {
11944                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11945                        .getAbsolutePath();
11946            } else {
11947                final String apkName = deriveCodePathName(codePath);
11948                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11949                        .getAbsolutePath();
11950            }
11951
11952            info.nativeLibraryRootRequiresIsa = false;
11953            info.nativeLibraryDir = info.nativeLibraryRootDir;
11954        } else {
11955            // Cluster install
11956            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11957            info.nativeLibraryRootRequiresIsa = true;
11958
11959            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11960                    getPrimaryInstructionSet(info)).getAbsolutePath();
11961
11962            if (info.secondaryCpuAbi != null) {
11963                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11964                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11965            }
11966        }
11967    }
11968
11969    /**
11970     * Calculate the abis and roots for a bundled app. These can uniquely
11971     * be determined from the contents of the system partition, i.e whether
11972     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11973     * of this information, and instead assume that the system was built
11974     * sensibly.
11975     */
11976    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11977                                           PackageSetting pkgSetting) {
11978        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11979
11980        // If "/system/lib64/apkname" exists, assume that is the per-package
11981        // native library directory to use; otherwise use "/system/lib/apkname".
11982        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11983        setBundledAppAbi(pkg, apkRoot, apkName);
11984        // pkgSetting might be null during rescan following uninstall of updates
11985        // to a bundled app, so accommodate that possibility.  The settings in
11986        // that case will be established later from the parsed package.
11987        //
11988        // If the settings aren't null, sync them up with what we've just derived.
11989        // note that apkRoot isn't stored in the package settings.
11990        if (pkgSetting != null) {
11991            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11992            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11993        }
11994    }
11995
11996    /**
11997     * Deduces the ABI of a bundled app and sets the relevant fields on the
11998     * parsed pkg object.
11999     *
12000     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12001     *        under which system libraries are installed.
12002     * @param apkName the name of the installed package.
12003     */
12004    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12005        final File codeFile = new File(pkg.codePath);
12006
12007        final boolean has64BitLibs;
12008        final boolean has32BitLibs;
12009        if (isApkFile(codeFile)) {
12010            // Monolithic install
12011            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12012            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12013        } else {
12014            // Cluster install
12015            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12016            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12017                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12018                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12019                has64BitLibs = (new File(rootDir, isa)).exists();
12020            } else {
12021                has64BitLibs = false;
12022            }
12023            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12024                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12025                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12026                has32BitLibs = (new File(rootDir, isa)).exists();
12027            } else {
12028                has32BitLibs = false;
12029            }
12030        }
12031
12032        if (has64BitLibs && !has32BitLibs) {
12033            // The package has 64 bit libs, but not 32 bit libs. Its primary
12034            // ABI should be 64 bit. We can safely assume here that the bundled
12035            // native libraries correspond to the most preferred ABI in the list.
12036
12037            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12038            pkg.applicationInfo.secondaryCpuAbi = null;
12039        } else if (has32BitLibs && !has64BitLibs) {
12040            // The package has 32 bit libs but not 64 bit libs. Its primary
12041            // ABI should be 32 bit.
12042
12043            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12044            pkg.applicationInfo.secondaryCpuAbi = null;
12045        } else if (has32BitLibs && has64BitLibs) {
12046            // The application has both 64 and 32 bit bundled libraries. We check
12047            // here that the app declares multiArch support, and warn if it doesn't.
12048            //
12049            // We will be lenient here and record both ABIs. The primary will be the
12050            // ABI that's higher on the list, i.e, a device that's configured to prefer
12051            // 64 bit apps will see a 64 bit primary ABI,
12052
12053            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12054                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12055            }
12056
12057            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12058                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12059                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12060            } else {
12061                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12062                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12063            }
12064        } else {
12065            pkg.applicationInfo.primaryCpuAbi = null;
12066            pkg.applicationInfo.secondaryCpuAbi = null;
12067        }
12068    }
12069
12070    private void killApplication(String pkgName, int appId, String reason) {
12071        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12072    }
12073
12074    private void killApplication(String pkgName, int appId, int userId, String reason) {
12075        // Request the ActivityManager to kill the process(only for existing packages)
12076        // so that we do not end up in a confused state while the user is still using the older
12077        // version of the application while the new one gets installed.
12078        final long token = Binder.clearCallingIdentity();
12079        try {
12080            IActivityManager am = ActivityManager.getService();
12081            if (am != null) {
12082                try {
12083                    am.killApplication(pkgName, appId, userId, reason);
12084                } catch (RemoteException e) {
12085                }
12086            }
12087        } finally {
12088            Binder.restoreCallingIdentity(token);
12089        }
12090    }
12091
12092    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12093        // Remove the parent package setting
12094        PackageSetting ps = (PackageSetting) pkg.mExtras;
12095        if (ps != null) {
12096            removePackageLI(ps, chatty);
12097        }
12098        // Remove the child package setting
12099        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12100        for (int i = 0; i < childCount; i++) {
12101            PackageParser.Package childPkg = pkg.childPackages.get(i);
12102            ps = (PackageSetting) childPkg.mExtras;
12103            if (ps != null) {
12104                removePackageLI(ps, chatty);
12105            }
12106        }
12107    }
12108
12109    void removePackageLI(PackageSetting ps, boolean chatty) {
12110        if (DEBUG_INSTALL) {
12111            if (chatty)
12112                Log.d(TAG, "Removing package " + ps.name);
12113        }
12114
12115        // writer
12116        synchronized (mPackages) {
12117            mPackages.remove(ps.name);
12118            final PackageParser.Package pkg = ps.pkg;
12119            if (pkg != null) {
12120                cleanPackageDataStructuresLILPw(pkg, chatty);
12121            }
12122        }
12123    }
12124
12125    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12126        if (DEBUG_INSTALL) {
12127            if (chatty)
12128                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12129        }
12130
12131        // writer
12132        synchronized (mPackages) {
12133            // Remove the parent package
12134            mPackages.remove(pkg.applicationInfo.packageName);
12135            cleanPackageDataStructuresLILPw(pkg, chatty);
12136
12137            // Remove the child packages
12138            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12139            for (int i = 0; i < childCount; i++) {
12140                PackageParser.Package childPkg = pkg.childPackages.get(i);
12141                mPackages.remove(childPkg.applicationInfo.packageName);
12142                cleanPackageDataStructuresLILPw(childPkg, chatty);
12143            }
12144        }
12145    }
12146
12147    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12148        int N = pkg.providers.size();
12149        StringBuilder r = null;
12150        int i;
12151        for (i=0; i<N; i++) {
12152            PackageParser.Provider p = pkg.providers.get(i);
12153            mProviders.removeProvider(p);
12154            if (p.info.authority == null) {
12155
12156                /* There was another ContentProvider with this authority when
12157                 * this app was installed so this authority is null,
12158                 * Ignore it as we don't have to unregister the provider.
12159                 */
12160                continue;
12161            }
12162            String names[] = p.info.authority.split(";");
12163            for (int j = 0; j < names.length; j++) {
12164                if (mProvidersByAuthority.get(names[j]) == p) {
12165                    mProvidersByAuthority.remove(names[j]);
12166                    if (DEBUG_REMOVE) {
12167                        if (chatty)
12168                            Log.d(TAG, "Unregistered content provider: " + names[j]
12169                                    + ", className = " + p.info.name + ", isSyncable = "
12170                                    + p.info.isSyncable);
12171                    }
12172                }
12173            }
12174            if (DEBUG_REMOVE && chatty) {
12175                if (r == null) {
12176                    r = new StringBuilder(256);
12177                } else {
12178                    r.append(' ');
12179                }
12180                r.append(p.info.name);
12181            }
12182        }
12183        if (r != null) {
12184            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12185        }
12186
12187        N = pkg.services.size();
12188        r = null;
12189        for (i=0; i<N; i++) {
12190            PackageParser.Service s = pkg.services.get(i);
12191            mServices.removeService(s);
12192            if (chatty) {
12193                if (r == null) {
12194                    r = new StringBuilder(256);
12195                } else {
12196                    r.append(' ');
12197                }
12198                r.append(s.info.name);
12199            }
12200        }
12201        if (r != null) {
12202            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12203        }
12204
12205        N = pkg.receivers.size();
12206        r = null;
12207        for (i=0; i<N; i++) {
12208            PackageParser.Activity a = pkg.receivers.get(i);
12209            mReceivers.removeActivity(a, "receiver");
12210            if (DEBUG_REMOVE && chatty) {
12211                if (r == null) {
12212                    r = new StringBuilder(256);
12213                } else {
12214                    r.append(' ');
12215                }
12216                r.append(a.info.name);
12217            }
12218        }
12219        if (r != null) {
12220            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12221        }
12222
12223        N = pkg.activities.size();
12224        r = null;
12225        for (i=0; i<N; i++) {
12226            PackageParser.Activity a = pkg.activities.get(i);
12227            mActivities.removeActivity(a, "activity");
12228            if (DEBUG_REMOVE && chatty) {
12229                if (r == null) {
12230                    r = new StringBuilder(256);
12231                } else {
12232                    r.append(' ');
12233                }
12234                r.append(a.info.name);
12235            }
12236        }
12237        if (r != null) {
12238            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12239        }
12240
12241        mPermissionManager.removeAllPermissions(pkg, chatty);
12242
12243        N = pkg.instrumentation.size();
12244        r = null;
12245        for (i=0; i<N; i++) {
12246            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12247            mInstrumentation.remove(a.getComponentName());
12248            if (DEBUG_REMOVE && chatty) {
12249                if (r == null) {
12250                    r = new StringBuilder(256);
12251                } else {
12252                    r.append(' ');
12253                }
12254                r.append(a.info.name);
12255            }
12256        }
12257        if (r != null) {
12258            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12259        }
12260
12261        r = null;
12262        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12263            // Only system apps can hold shared libraries.
12264            if (pkg.libraryNames != null) {
12265                for (i = 0; i < pkg.libraryNames.size(); i++) {
12266                    String name = pkg.libraryNames.get(i);
12267                    if (removeSharedLibraryLPw(name, 0)) {
12268                        if (DEBUG_REMOVE && chatty) {
12269                            if (r == null) {
12270                                r = new StringBuilder(256);
12271                            } else {
12272                                r.append(' ');
12273                            }
12274                            r.append(name);
12275                        }
12276                    }
12277                }
12278            }
12279        }
12280
12281        r = null;
12282
12283        // Any package can hold static shared libraries.
12284        if (pkg.staticSharedLibName != null) {
12285            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12286                if (DEBUG_REMOVE && chatty) {
12287                    if (r == null) {
12288                        r = new StringBuilder(256);
12289                    } else {
12290                        r.append(' ');
12291                    }
12292                    r.append(pkg.staticSharedLibName);
12293                }
12294            }
12295        }
12296
12297        if (r != null) {
12298            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12299        }
12300    }
12301
12302
12303    final class ActivityIntentResolver
12304            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12305        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12306                boolean defaultOnly, int userId) {
12307            if (!sUserManager.exists(userId)) return null;
12308            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12309            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12310        }
12311
12312        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12313                int userId) {
12314            if (!sUserManager.exists(userId)) return null;
12315            mFlags = flags;
12316            return super.queryIntent(intent, resolvedType,
12317                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12318                    userId);
12319        }
12320
12321        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12322                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12323            if (!sUserManager.exists(userId)) return null;
12324            if (packageActivities == null) {
12325                return null;
12326            }
12327            mFlags = flags;
12328            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12329            final int N = packageActivities.size();
12330            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12331                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12332
12333            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12334            for (int i = 0; i < N; ++i) {
12335                intentFilters = packageActivities.get(i).intents;
12336                if (intentFilters != null && intentFilters.size() > 0) {
12337                    PackageParser.ActivityIntentInfo[] array =
12338                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12339                    intentFilters.toArray(array);
12340                    listCut.add(array);
12341                }
12342            }
12343            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12344        }
12345
12346        /**
12347         * Finds a privileged activity that matches the specified activity names.
12348         */
12349        private PackageParser.Activity findMatchingActivity(
12350                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12351            for (PackageParser.Activity sysActivity : activityList) {
12352                if (sysActivity.info.name.equals(activityInfo.name)) {
12353                    return sysActivity;
12354                }
12355                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12356                    return sysActivity;
12357                }
12358                if (sysActivity.info.targetActivity != null) {
12359                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12360                        return sysActivity;
12361                    }
12362                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12363                        return sysActivity;
12364                    }
12365                }
12366            }
12367            return null;
12368        }
12369
12370        public class IterGenerator<E> {
12371            public Iterator<E> generate(ActivityIntentInfo info) {
12372                return null;
12373            }
12374        }
12375
12376        public class ActionIterGenerator extends IterGenerator<String> {
12377            @Override
12378            public Iterator<String> generate(ActivityIntentInfo info) {
12379                return info.actionsIterator();
12380            }
12381        }
12382
12383        public class CategoriesIterGenerator extends IterGenerator<String> {
12384            @Override
12385            public Iterator<String> generate(ActivityIntentInfo info) {
12386                return info.categoriesIterator();
12387            }
12388        }
12389
12390        public class SchemesIterGenerator extends IterGenerator<String> {
12391            @Override
12392            public Iterator<String> generate(ActivityIntentInfo info) {
12393                return info.schemesIterator();
12394            }
12395        }
12396
12397        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12398            @Override
12399            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12400                return info.authoritiesIterator();
12401            }
12402        }
12403
12404        /**
12405         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12406         * MODIFIED. Do not pass in a list that should not be changed.
12407         */
12408        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12409                IterGenerator<T> generator, Iterator<T> searchIterator) {
12410            // loop through the set of actions; every one must be found in the intent filter
12411            while (searchIterator.hasNext()) {
12412                // we must have at least one filter in the list to consider a match
12413                if (intentList.size() == 0) {
12414                    break;
12415                }
12416
12417                final T searchAction = searchIterator.next();
12418
12419                // loop through the set of intent filters
12420                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12421                while (intentIter.hasNext()) {
12422                    final ActivityIntentInfo intentInfo = intentIter.next();
12423                    boolean selectionFound = false;
12424
12425                    // loop through the intent filter's selection criteria; at least one
12426                    // of them must match the searched criteria
12427                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12428                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12429                        final T intentSelection = intentSelectionIter.next();
12430                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12431                            selectionFound = true;
12432                            break;
12433                        }
12434                    }
12435
12436                    // the selection criteria wasn't found in this filter's set; this filter
12437                    // is not a potential match
12438                    if (!selectionFound) {
12439                        intentIter.remove();
12440                    }
12441                }
12442            }
12443        }
12444
12445        private boolean isProtectedAction(ActivityIntentInfo filter) {
12446            final Iterator<String> actionsIter = filter.actionsIterator();
12447            while (actionsIter != null && actionsIter.hasNext()) {
12448                final String filterAction = actionsIter.next();
12449                if (PROTECTED_ACTIONS.contains(filterAction)) {
12450                    return true;
12451                }
12452            }
12453            return false;
12454        }
12455
12456        /**
12457         * Adjusts the priority of the given intent filter according to policy.
12458         * <p>
12459         * <ul>
12460         * <li>The priority for non privileged applications is capped to '0'</li>
12461         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12462         * <li>The priority for unbundled updates to privileged applications is capped to the
12463         *      priority defined on the system partition</li>
12464         * </ul>
12465         * <p>
12466         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12467         * allowed to obtain any priority on any action.
12468         */
12469        private void adjustPriority(
12470                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12471            // nothing to do; priority is fine as-is
12472            if (intent.getPriority() <= 0) {
12473                return;
12474            }
12475
12476            final ActivityInfo activityInfo = intent.activity.info;
12477            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12478
12479            final boolean privilegedApp =
12480                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12481            if (!privilegedApp) {
12482                // non-privileged applications can never define a priority >0
12483                if (DEBUG_FILTERS) {
12484                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12485                            + " package: " + applicationInfo.packageName
12486                            + " activity: " + intent.activity.className
12487                            + " origPrio: " + intent.getPriority());
12488                }
12489                intent.setPriority(0);
12490                return;
12491            }
12492
12493            if (systemActivities == null) {
12494                // the system package is not disabled; we're parsing the system partition
12495                if (isProtectedAction(intent)) {
12496                    if (mDeferProtectedFilters) {
12497                        // We can't deal with these just yet. No component should ever obtain a
12498                        // >0 priority for a protected actions, with ONE exception -- the setup
12499                        // wizard. The setup wizard, however, cannot be known until we're able to
12500                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12501                        // until all intent filters have been processed. Chicken, meet egg.
12502                        // Let the filter temporarily have a high priority and rectify the
12503                        // priorities after all system packages have been scanned.
12504                        mProtectedFilters.add(intent);
12505                        if (DEBUG_FILTERS) {
12506                            Slog.i(TAG, "Protected action; save for later;"
12507                                    + " package: " + applicationInfo.packageName
12508                                    + " activity: " + intent.activity.className
12509                                    + " origPrio: " + intent.getPriority());
12510                        }
12511                        return;
12512                    } else {
12513                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12514                            Slog.i(TAG, "No setup wizard;"
12515                                + " All protected intents capped to priority 0");
12516                        }
12517                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12518                            if (DEBUG_FILTERS) {
12519                                Slog.i(TAG, "Found setup wizard;"
12520                                    + " allow priority " + intent.getPriority() + ";"
12521                                    + " package: " + intent.activity.info.packageName
12522                                    + " activity: " + intent.activity.className
12523                                    + " priority: " + intent.getPriority());
12524                            }
12525                            // setup wizard gets whatever it wants
12526                            return;
12527                        }
12528                        if (DEBUG_FILTERS) {
12529                            Slog.i(TAG, "Protected action; cap priority to 0;"
12530                                    + " package: " + intent.activity.info.packageName
12531                                    + " activity: " + intent.activity.className
12532                                    + " origPrio: " + intent.getPriority());
12533                        }
12534                        intent.setPriority(0);
12535                        return;
12536                    }
12537                }
12538                // privileged apps on the system image get whatever priority they request
12539                return;
12540            }
12541
12542            // privileged app unbundled update ... try to find the same activity
12543            final PackageParser.Activity foundActivity =
12544                    findMatchingActivity(systemActivities, activityInfo);
12545            if (foundActivity == null) {
12546                // this is a new activity; it cannot obtain >0 priority
12547                if (DEBUG_FILTERS) {
12548                    Slog.i(TAG, "New activity; cap priority to 0;"
12549                            + " package: " + applicationInfo.packageName
12550                            + " activity: " + intent.activity.className
12551                            + " origPrio: " + intent.getPriority());
12552                }
12553                intent.setPriority(0);
12554                return;
12555            }
12556
12557            // found activity, now check for filter equivalence
12558
12559            // a shallow copy is enough; we modify the list, not its contents
12560            final List<ActivityIntentInfo> intentListCopy =
12561                    new ArrayList<>(foundActivity.intents);
12562            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12563
12564            // find matching action subsets
12565            final Iterator<String> actionsIterator = intent.actionsIterator();
12566            if (actionsIterator != null) {
12567                getIntentListSubset(
12568                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12569                if (intentListCopy.size() == 0) {
12570                    // no more intents to match; we're not equivalent
12571                    if (DEBUG_FILTERS) {
12572                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12573                                + " package: " + applicationInfo.packageName
12574                                + " activity: " + intent.activity.className
12575                                + " origPrio: " + intent.getPriority());
12576                    }
12577                    intent.setPriority(0);
12578                    return;
12579                }
12580            }
12581
12582            // find matching category subsets
12583            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12584            if (categoriesIterator != null) {
12585                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12586                        categoriesIterator);
12587                if (intentListCopy.size() == 0) {
12588                    // no more intents to match; we're not equivalent
12589                    if (DEBUG_FILTERS) {
12590                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12591                                + " package: " + applicationInfo.packageName
12592                                + " activity: " + intent.activity.className
12593                                + " origPrio: " + intent.getPriority());
12594                    }
12595                    intent.setPriority(0);
12596                    return;
12597                }
12598            }
12599
12600            // find matching schemes subsets
12601            final Iterator<String> schemesIterator = intent.schemesIterator();
12602            if (schemesIterator != null) {
12603                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12604                        schemesIterator);
12605                if (intentListCopy.size() == 0) {
12606                    // no more intents to match; we're not equivalent
12607                    if (DEBUG_FILTERS) {
12608                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12609                                + " package: " + applicationInfo.packageName
12610                                + " activity: " + intent.activity.className
12611                                + " origPrio: " + intent.getPriority());
12612                    }
12613                    intent.setPriority(0);
12614                    return;
12615                }
12616            }
12617
12618            // find matching authorities subsets
12619            final Iterator<IntentFilter.AuthorityEntry>
12620                    authoritiesIterator = intent.authoritiesIterator();
12621            if (authoritiesIterator != null) {
12622                getIntentListSubset(intentListCopy,
12623                        new AuthoritiesIterGenerator(),
12624                        authoritiesIterator);
12625                if (intentListCopy.size() == 0) {
12626                    // no more intents to match; we're not equivalent
12627                    if (DEBUG_FILTERS) {
12628                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12629                                + " package: " + applicationInfo.packageName
12630                                + " activity: " + intent.activity.className
12631                                + " origPrio: " + intent.getPriority());
12632                    }
12633                    intent.setPriority(0);
12634                    return;
12635                }
12636            }
12637
12638            // we found matching filter(s); app gets the max priority of all intents
12639            int cappedPriority = 0;
12640            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12641                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12642            }
12643            if (intent.getPriority() > cappedPriority) {
12644                if (DEBUG_FILTERS) {
12645                    Slog.i(TAG, "Found matching filter(s);"
12646                            + " cap priority to " + cappedPriority + ";"
12647                            + " package: " + applicationInfo.packageName
12648                            + " activity: " + intent.activity.className
12649                            + " origPrio: " + intent.getPriority());
12650                }
12651                intent.setPriority(cappedPriority);
12652                return;
12653            }
12654            // all this for nothing; the requested priority was <= what was on the system
12655        }
12656
12657        public final void addActivity(PackageParser.Activity a, String type) {
12658            mActivities.put(a.getComponentName(), a);
12659            if (DEBUG_SHOW_INFO)
12660                Log.v(
12661                TAG, "  " + type + " " +
12662                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12663            if (DEBUG_SHOW_INFO)
12664                Log.v(TAG, "    Class=" + a.info.name);
12665            final int NI = a.intents.size();
12666            for (int j=0; j<NI; j++) {
12667                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12668                if ("activity".equals(type)) {
12669                    final PackageSetting ps =
12670                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12671                    final List<PackageParser.Activity> systemActivities =
12672                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12673                    adjustPriority(systemActivities, intent);
12674                }
12675                if (DEBUG_SHOW_INFO) {
12676                    Log.v(TAG, "    IntentFilter:");
12677                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12678                }
12679                if (!intent.debugCheck()) {
12680                    Log.w(TAG, "==> For Activity " + a.info.name);
12681                }
12682                addFilter(intent);
12683            }
12684        }
12685
12686        public final void removeActivity(PackageParser.Activity a, String type) {
12687            mActivities.remove(a.getComponentName());
12688            if (DEBUG_SHOW_INFO) {
12689                Log.v(TAG, "  " + type + " "
12690                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12691                                : a.info.name) + ":");
12692                Log.v(TAG, "    Class=" + a.info.name);
12693            }
12694            final int NI = a.intents.size();
12695            for (int j=0; j<NI; j++) {
12696                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12697                if (DEBUG_SHOW_INFO) {
12698                    Log.v(TAG, "    IntentFilter:");
12699                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12700                }
12701                removeFilter(intent);
12702            }
12703        }
12704
12705        @Override
12706        protected boolean allowFilterResult(
12707                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12708            ActivityInfo filterAi = filter.activity.info;
12709            for (int i=dest.size()-1; i>=0; i--) {
12710                ActivityInfo destAi = dest.get(i).activityInfo;
12711                if (destAi.name == filterAi.name
12712                        && destAi.packageName == filterAi.packageName) {
12713                    return false;
12714                }
12715            }
12716            return true;
12717        }
12718
12719        @Override
12720        protected ActivityIntentInfo[] newArray(int size) {
12721            return new ActivityIntentInfo[size];
12722        }
12723
12724        @Override
12725        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12726            if (!sUserManager.exists(userId)) return true;
12727            PackageParser.Package p = filter.activity.owner;
12728            if (p != null) {
12729                PackageSetting ps = (PackageSetting)p.mExtras;
12730                if (ps != null) {
12731                    // System apps are never considered stopped for purposes of
12732                    // filtering, because there may be no way for the user to
12733                    // actually re-launch them.
12734                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12735                            && ps.getStopped(userId);
12736                }
12737            }
12738            return false;
12739        }
12740
12741        @Override
12742        protected boolean isPackageForFilter(String packageName,
12743                PackageParser.ActivityIntentInfo info) {
12744            return packageName.equals(info.activity.owner.packageName);
12745        }
12746
12747        @Override
12748        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12749                int match, int userId) {
12750            if (!sUserManager.exists(userId)) return null;
12751            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12752                return null;
12753            }
12754            final PackageParser.Activity activity = info.activity;
12755            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12756            if (ps == null) {
12757                return null;
12758            }
12759            final PackageUserState userState = ps.readUserState(userId);
12760            ActivityInfo ai =
12761                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12762            if (ai == null) {
12763                return null;
12764            }
12765            final boolean matchExplicitlyVisibleOnly =
12766                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12767            final boolean matchVisibleToInstantApp =
12768                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12769            final boolean componentVisible =
12770                    matchVisibleToInstantApp
12771                    && info.isVisibleToInstantApp()
12772                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12773            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12774            // throw out filters that aren't visible to ephemeral apps
12775            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12776                return null;
12777            }
12778            // throw out instant app filters if we're not explicitly requesting them
12779            if (!matchInstantApp && userState.instantApp) {
12780                return null;
12781            }
12782            // throw out instant app filters if updates are available; will trigger
12783            // instant app resolution
12784            if (userState.instantApp && ps.isUpdateAvailable()) {
12785                return null;
12786            }
12787            final ResolveInfo res = new ResolveInfo();
12788            res.activityInfo = ai;
12789            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12790                res.filter = info;
12791            }
12792            if (info != null) {
12793                res.handleAllWebDataURI = info.handleAllWebDataURI();
12794            }
12795            res.priority = info.getPriority();
12796            res.preferredOrder = activity.owner.mPreferredOrder;
12797            //System.out.println("Result: " + res.activityInfo.className +
12798            //                   " = " + res.priority);
12799            res.match = match;
12800            res.isDefault = info.hasDefault;
12801            res.labelRes = info.labelRes;
12802            res.nonLocalizedLabel = info.nonLocalizedLabel;
12803            if (userNeedsBadging(userId)) {
12804                res.noResourceId = true;
12805            } else {
12806                res.icon = info.icon;
12807            }
12808            res.iconResourceId = info.icon;
12809            res.system = res.activityInfo.applicationInfo.isSystemApp();
12810            res.isInstantAppAvailable = userState.instantApp;
12811            return res;
12812        }
12813
12814        @Override
12815        protected void sortResults(List<ResolveInfo> results) {
12816            Collections.sort(results, mResolvePrioritySorter);
12817        }
12818
12819        @Override
12820        protected void dumpFilter(PrintWriter out, String prefix,
12821                PackageParser.ActivityIntentInfo filter) {
12822            out.print(prefix); out.print(
12823                    Integer.toHexString(System.identityHashCode(filter.activity)));
12824                    out.print(' ');
12825                    filter.activity.printComponentShortName(out);
12826                    out.print(" filter ");
12827                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12828        }
12829
12830        @Override
12831        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12832            return filter.activity;
12833        }
12834
12835        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12836            PackageParser.Activity activity = (PackageParser.Activity)label;
12837            out.print(prefix); out.print(
12838                    Integer.toHexString(System.identityHashCode(activity)));
12839                    out.print(' ');
12840                    activity.printComponentShortName(out);
12841            if (count > 1) {
12842                out.print(" ("); out.print(count); out.print(" filters)");
12843            }
12844            out.println();
12845        }
12846
12847        // Keys are String (activity class name), values are Activity.
12848        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12849                = new ArrayMap<ComponentName, PackageParser.Activity>();
12850        private int mFlags;
12851    }
12852
12853    private final class ServiceIntentResolver
12854            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12855        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12856                boolean defaultOnly, int userId) {
12857            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12858            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12859        }
12860
12861        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12862                int userId) {
12863            if (!sUserManager.exists(userId)) return null;
12864            mFlags = flags;
12865            return super.queryIntent(intent, resolvedType,
12866                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12867                    userId);
12868        }
12869
12870        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12871                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12872            if (!sUserManager.exists(userId)) return null;
12873            if (packageServices == null) {
12874                return null;
12875            }
12876            mFlags = flags;
12877            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12878            final int N = packageServices.size();
12879            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12880                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12881
12882            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12883            for (int i = 0; i < N; ++i) {
12884                intentFilters = packageServices.get(i).intents;
12885                if (intentFilters != null && intentFilters.size() > 0) {
12886                    PackageParser.ServiceIntentInfo[] array =
12887                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12888                    intentFilters.toArray(array);
12889                    listCut.add(array);
12890                }
12891            }
12892            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12893        }
12894
12895        public final void addService(PackageParser.Service s) {
12896            mServices.put(s.getComponentName(), s);
12897            if (DEBUG_SHOW_INFO) {
12898                Log.v(TAG, "  "
12899                        + (s.info.nonLocalizedLabel != null
12900                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12901                Log.v(TAG, "    Class=" + s.info.name);
12902            }
12903            final int NI = s.intents.size();
12904            int j;
12905            for (j=0; j<NI; j++) {
12906                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12907                if (DEBUG_SHOW_INFO) {
12908                    Log.v(TAG, "    IntentFilter:");
12909                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12910                }
12911                if (!intent.debugCheck()) {
12912                    Log.w(TAG, "==> For Service " + s.info.name);
12913                }
12914                addFilter(intent);
12915            }
12916        }
12917
12918        public final void removeService(PackageParser.Service s) {
12919            mServices.remove(s.getComponentName());
12920            if (DEBUG_SHOW_INFO) {
12921                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12922                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12923                Log.v(TAG, "    Class=" + s.info.name);
12924            }
12925            final int NI = s.intents.size();
12926            int j;
12927            for (j=0; j<NI; j++) {
12928                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12929                if (DEBUG_SHOW_INFO) {
12930                    Log.v(TAG, "    IntentFilter:");
12931                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12932                }
12933                removeFilter(intent);
12934            }
12935        }
12936
12937        @Override
12938        protected boolean allowFilterResult(
12939                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12940            ServiceInfo filterSi = filter.service.info;
12941            for (int i=dest.size()-1; i>=0; i--) {
12942                ServiceInfo destAi = dest.get(i).serviceInfo;
12943                if (destAi.name == filterSi.name
12944                        && destAi.packageName == filterSi.packageName) {
12945                    return false;
12946                }
12947            }
12948            return true;
12949        }
12950
12951        @Override
12952        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12953            return new PackageParser.ServiceIntentInfo[size];
12954        }
12955
12956        @Override
12957        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12958            if (!sUserManager.exists(userId)) return true;
12959            PackageParser.Package p = filter.service.owner;
12960            if (p != null) {
12961                PackageSetting ps = (PackageSetting)p.mExtras;
12962                if (ps != null) {
12963                    // System apps are never considered stopped for purposes of
12964                    // filtering, because there may be no way for the user to
12965                    // actually re-launch them.
12966                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12967                            && ps.getStopped(userId);
12968                }
12969            }
12970            return false;
12971        }
12972
12973        @Override
12974        protected boolean isPackageForFilter(String packageName,
12975                PackageParser.ServiceIntentInfo info) {
12976            return packageName.equals(info.service.owner.packageName);
12977        }
12978
12979        @Override
12980        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12981                int match, int userId) {
12982            if (!sUserManager.exists(userId)) return null;
12983            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12984            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12985                return null;
12986            }
12987            final PackageParser.Service service = info.service;
12988            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12989            if (ps == null) {
12990                return null;
12991            }
12992            final PackageUserState userState = ps.readUserState(userId);
12993            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12994                    userState, userId);
12995            if (si == null) {
12996                return null;
12997            }
12998            final boolean matchVisibleToInstantApp =
12999                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13000            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13001            // throw out filters that aren't visible to ephemeral apps
13002            if (matchVisibleToInstantApp
13003                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13004                return null;
13005            }
13006            // throw out ephemeral filters if we're not explicitly requesting them
13007            if (!isInstantApp && userState.instantApp) {
13008                return null;
13009            }
13010            // throw out instant app filters if updates are available; will trigger
13011            // instant app resolution
13012            if (userState.instantApp && ps.isUpdateAvailable()) {
13013                return null;
13014            }
13015            final ResolveInfo res = new ResolveInfo();
13016            res.serviceInfo = si;
13017            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13018                res.filter = filter;
13019            }
13020            res.priority = info.getPriority();
13021            res.preferredOrder = service.owner.mPreferredOrder;
13022            res.match = match;
13023            res.isDefault = info.hasDefault;
13024            res.labelRes = info.labelRes;
13025            res.nonLocalizedLabel = info.nonLocalizedLabel;
13026            res.icon = info.icon;
13027            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13028            return res;
13029        }
13030
13031        @Override
13032        protected void sortResults(List<ResolveInfo> results) {
13033            Collections.sort(results, mResolvePrioritySorter);
13034        }
13035
13036        @Override
13037        protected void dumpFilter(PrintWriter out, String prefix,
13038                PackageParser.ServiceIntentInfo filter) {
13039            out.print(prefix); out.print(
13040                    Integer.toHexString(System.identityHashCode(filter.service)));
13041                    out.print(' ');
13042                    filter.service.printComponentShortName(out);
13043                    out.print(" filter ");
13044                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13045                    if (filter.service.info.permission != null) {
13046                        out.print(" permission "); out.println(filter.service.info.permission);
13047                    } else {
13048                        out.println();
13049                    }
13050        }
13051
13052        @Override
13053        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13054            return filter.service;
13055        }
13056
13057        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13058            PackageParser.Service service = (PackageParser.Service)label;
13059            out.print(prefix); out.print(
13060                    Integer.toHexString(System.identityHashCode(service)));
13061                    out.print(' ');
13062                    service.printComponentShortName(out);
13063            if (count > 1) {
13064                out.print(" ("); out.print(count); out.print(" filters)");
13065            }
13066            out.println();
13067        }
13068
13069//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13070//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13071//            final List<ResolveInfo> retList = Lists.newArrayList();
13072//            while (i.hasNext()) {
13073//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13074//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13075//                    retList.add(resolveInfo);
13076//                }
13077//            }
13078//            return retList;
13079//        }
13080
13081        // Keys are String (activity class name), values are Activity.
13082        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13083                = new ArrayMap<ComponentName, PackageParser.Service>();
13084        private int mFlags;
13085    }
13086
13087    private final class ProviderIntentResolver
13088            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13089        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13090                boolean defaultOnly, int userId) {
13091            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13092            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13093        }
13094
13095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13096                int userId) {
13097            if (!sUserManager.exists(userId))
13098                return null;
13099            mFlags = flags;
13100            return super.queryIntent(intent, resolvedType,
13101                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13102                    userId);
13103        }
13104
13105        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13106                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13107            if (!sUserManager.exists(userId))
13108                return null;
13109            if (packageProviders == null) {
13110                return null;
13111            }
13112            mFlags = flags;
13113            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13114            final int N = packageProviders.size();
13115            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13116                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13117
13118            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13119            for (int i = 0; i < N; ++i) {
13120                intentFilters = packageProviders.get(i).intents;
13121                if (intentFilters != null && intentFilters.size() > 0) {
13122                    PackageParser.ProviderIntentInfo[] array =
13123                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13124                    intentFilters.toArray(array);
13125                    listCut.add(array);
13126                }
13127            }
13128            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13129        }
13130
13131        public final void addProvider(PackageParser.Provider p) {
13132            if (mProviders.containsKey(p.getComponentName())) {
13133                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13134                return;
13135            }
13136
13137            mProviders.put(p.getComponentName(), p);
13138            if (DEBUG_SHOW_INFO) {
13139                Log.v(TAG, "  "
13140                        + (p.info.nonLocalizedLabel != null
13141                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13142                Log.v(TAG, "    Class=" + p.info.name);
13143            }
13144            final int NI = p.intents.size();
13145            int j;
13146            for (j = 0; j < NI; j++) {
13147                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13148                if (DEBUG_SHOW_INFO) {
13149                    Log.v(TAG, "    IntentFilter:");
13150                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13151                }
13152                if (!intent.debugCheck()) {
13153                    Log.w(TAG, "==> For Provider " + p.info.name);
13154                }
13155                addFilter(intent);
13156            }
13157        }
13158
13159        public final void removeProvider(PackageParser.Provider p) {
13160            mProviders.remove(p.getComponentName());
13161            if (DEBUG_SHOW_INFO) {
13162                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13163                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13164                Log.v(TAG, "    Class=" + p.info.name);
13165            }
13166            final int NI = p.intents.size();
13167            int j;
13168            for (j = 0; j < NI; j++) {
13169                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13170                if (DEBUG_SHOW_INFO) {
13171                    Log.v(TAG, "    IntentFilter:");
13172                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13173                }
13174                removeFilter(intent);
13175            }
13176        }
13177
13178        @Override
13179        protected boolean allowFilterResult(
13180                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13181            ProviderInfo filterPi = filter.provider.info;
13182            for (int i = dest.size() - 1; i >= 0; i--) {
13183                ProviderInfo destPi = dest.get(i).providerInfo;
13184                if (destPi.name == filterPi.name
13185                        && destPi.packageName == filterPi.packageName) {
13186                    return false;
13187                }
13188            }
13189            return true;
13190        }
13191
13192        @Override
13193        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13194            return new PackageParser.ProviderIntentInfo[size];
13195        }
13196
13197        @Override
13198        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13199            if (!sUserManager.exists(userId))
13200                return true;
13201            PackageParser.Package p = filter.provider.owner;
13202            if (p != null) {
13203                PackageSetting ps = (PackageSetting) p.mExtras;
13204                if (ps != null) {
13205                    // System apps are never considered stopped for purposes of
13206                    // filtering, because there may be no way for the user to
13207                    // actually re-launch them.
13208                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13209                            && ps.getStopped(userId);
13210                }
13211            }
13212            return false;
13213        }
13214
13215        @Override
13216        protected boolean isPackageForFilter(String packageName,
13217                PackageParser.ProviderIntentInfo info) {
13218            return packageName.equals(info.provider.owner.packageName);
13219        }
13220
13221        @Override
13222        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13223                int match, int userId) {
13224            if (!sUserManager.exists(userId))
13225                return null;
13226            final PackageParser.ProviderIntentInfo info = filter;
13227            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13228                return null;
13229            }
13230            final PackageParser.Provider provider = info.provider;
13231            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13232            if (ps == null) {
13233                return null;
13234            }
13235            final PackageUserState userState = ps.readUserState(userId);
13236            final boolean matchVisibleToInstantApp =
13237                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13238            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13239            // throw out filters that aren't visible to instant applications
13240            if (matchVisibleToInstantApp
13241                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13242                return null;
13243            }
13244            // throw out instant application filters if we're not explicitly requesting them
13245            if (!isInstantApp && userState.instantApp) {
13246                return null;
13247            }
13248            // throw out instant application filters if updates are available; will trigger
13249            // instant application resolution
13250            if (userState.instantApp && ps.isUpdateAvailable()) {
13251                return null;
13252            }
13253            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13254                    userState, userId);
13255            if (pi == null) {
13256                return null;
13257            }
13258            final ResolveInfo res = new ResolveInfo();
13259            res.providerInfo = pi;
13260            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13261                res.filter = filter;
13262            }
13263            res.priority = info.getPriority();
13264            res.preferredOrder = provider.owner.mPreferredOrder;
13265            res.match = match;
13266            res.isDefault = info.hasDefault;
13267            res.labelRes = info.labelRes;
13268            res.nonLocalizedLabel = info.nonLocalizedLabel;
13269            res.icon = info.icon;
13270            res.system = res.providerInfo.applicationInfo.isSystemApp();
13271            return res;
13272        }
13273
13274        @Override
13275        protected void sortResults(List<ResolveInfo> results) {
13276            Collections.sort(results, mResolvePrioritySorter);
13277        }
13278
13279        @Override
13280        protected void dumpFilter(PrintWriter out, String prefix,
13281                PackageParser.ProviderIntentInfo filter) {
13282            out.print(prefix);
13283            out.print(
13284                    Integer.toHexString(System.identityHashCode(filter.provider)));
13285            out.print(' ');
13286            filter.provider.printComponentShortName(out);
13287            out.print(" filter ");
13288            out.println(Integer.toHexString(System.identityHashCode(filter)));
13289        }
13290
13291        @Override
13292        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13293            return filter.provider;
13294        }
13295
13296        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13297            PackageParser.Provider provider = (PackageParser.Provider)label;
13298            out.print(prefix); out.print(
13299                    Integer.toHexString(System.identityHashCode(provider)));
13300                    out.print(' ');
13301                    provider.printComponentShortName(out);
13302            if (count > 1) {
13303                out.print(" ("); out.print(count); out.print(" filters)");
13304            }
13305            out.println();
13306        }
13307
13308        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13309                = new ArrayMap<ComponentName, PackageParser.Provider>();
13310        private int mFlags;
13311    }
13312
13313    static final class InstantAppIntentResolver
13314            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13315            AuxiliaryResolveInfo.AuxiliaryFilter> {
13316        /**
13317         * The result that has the highest defined order. Ordering applies on a
13318         * per-package basis. Mapping is from package name to Pair of order and
13319         * EphemeralResolveInfo.
13320         * <p>
13321         * NOTE: This is implemented as a field variable for convenience and efficiency.
13322         * By having a field variable, we're able to track filter ordering as soon as
13323         * a non-zero order is defined. Otherwise, multiple loops across the result set
13324         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13325         * this needs to be contained entirely within {@link #filterResults}.
13326         */
13327        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13328
13329        @Override
13330        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13331            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13332        }
13333
13334        @Override
13335        protected boolean isPackageForFilter(String packageName,
13336                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13337            return true;
13338        }
13339
13340        @Override
13341        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13342                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13343            if (!sUserManager.exists(userId)) {
13344                return null;
13345            }
13346            final String packageName = responseObj.resolveInfo.getPackageName();
13347            final Integer order = responseObj.getOrder();
13348            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13349                    mOrderResult.get(packageName);
13350            // ordering is enabled and this item's order isn't high enough
13351            if (lastOrderResult != null && lastOrderResult.first >= order) {
13352                return null;
13353            }
13354            final InstantAppResolveInfo res = responseObj.resolveInfo;
13355            if (order > 0) {
13356                // non-zero order, enable ordering
13357                mOrderResult.put(packageName, new Pair<>(order, res));
13358            }
13359            return responseObj;
13360        }
13361
13362        @Override
13363        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13364            // only do work if ordering is enabled [most of the time it won't be]
13365            if (mOrderResult.size() == 0) {
13366                return;
13367            }
13368            int resultSize = results.size();
13369            for (int i = 0; i < resultSize; i++) {
13370                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13371                final String packageName = info.getPackageName();
13372                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13373                if (savedInfo == null) {
13374                    // package doesn't having ordering
13375                    continue;
13376                }
13377                if (savedInfo.second == info) {
13378                    // circled back to the highest ordered item; remove from order list
13379                    mOrderResult.remove(packageName);
13380                    if (mOrderResult.size() == 0) {
13381                        // no more ordered items
13382                        break;
13383                    }
13384                    continue;
13385                }
13386                // item has a worse order, remove it from the result list
13387                results.remove(i);
13388                resultSize--;
13389                i--;
13390            }
13391        }
13392    }
13393
13394    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13395            new Comparator<ResolveInfo>() {
13396        public int compare(ResolveInfo r1, ResolveInfo r2) {
13397            int v1 = r1.priority;
13398            int v2 = r2.priority;
13399            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13400            if (v1 != v2) {
13401                return (v1 > v2) ? -1 : 1;
13402            }
13403            v1 = r1.preferredOrder;
13404            v2 = r2.preferredOrder;
13405            if (v1 != v2) {
13406                return (v1 > v2) ? -1 : 1;
13407            }
13408            if (r1.isDefault != r2.isDefault) {
13409                return r1.isDefault ? -1 : 1;
13410            }
13411            v1 = r1.match;
13412            v2 = r2.match;
13413            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13414            if (v1 != v2) {
13415                return (v1 > v2) ? -1 : 1;
13416            }
13417            if (r1.system != r2.system) {
13418                return r1.system ? -1 : 1;
13419            }
13420            if (r1.activityInfo != null) {
13421                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13422            }
13423            if (r1.serviceInfo != null) {
13424                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13425            }
13426            if (r1.providerInfo != null) {
13427                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13428            }
13429            return 0;
13430        }
13431    };
13432
13433    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13434            new Comparator<ProviderInfo>() {
13435        public int compare(ProviderInfo p1, ProviderInfo p2) {
13436            final int v1 = p1.initOrder;
13437            final int v2 = p2.initOrder;
13438            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13439        }
13440    };
13441
13442    @Override
13443    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13444            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13445            final int[] userIds, int[] instantUserIds) {
13446        mHandler.post(new Runnable() {
13447            @Override
13448            public void run() {
13449                try {
13450                    final IActivityManager am = ActivityManager.getService();
13451                    if (am == null) return;
13452                    final int[] resolvedUserIds;
13453                    if (userIds == null) {
13454                        resolvedUserIds = am.getRunningUserIds();
13455                    } else {
13456                        resolvedUserIds = userIds;
13457                    }
13458                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13459                            resolvedUserIds, false);
13460                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13461                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13462                                instantUserIds, true);
13463                    }
13464                } catch (RemoteException ex) {
13465                }
13466            }
13467        });
13468    }
13469
13470    @Override
13471    public void notifyPackageAdded(String packageName) {
13472        final PackageListObserver[] observers;
13473        synchronized (mPackages) {
13474            if (mPackageListObservers.size() == 0) {
13475                return;
13476            }
13477            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13478        }
13479        for (int i = observers.length - 1; i >= 0; --i) {
13480            observers[i].onPackageAdded(packageName);
13481        }
13482    }
13483
13484    @Override
13485    public void notifyPackageRemoved(String packageName) {
13486        final PackageListObserver[] observers;
13487        synchronized (mPackages) {
13488            if (mPackageListObservers.size() == 0) {
13489                return;
13490            }
13491            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13492        }
13493        for (int i = observers.length - 1; i >= 0; --i) {
13494            observers[i].onPackageRemoved(packageName);
13495        }
13496    }
13497
13498    /**
13499     * Sends a broadcast for the given action.
13500     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13501     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13502     * the system and applications allowed to see instant applications to receive package
13503     * lifecycle events for instant applications.
13504     */
13505    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13506            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13507            int[] userIds, boolean isInstantApp)
13508                    throws RemoteException {
13509        for (int id : userIds) {
13510            final Intent intent = new Intent(action,
13511                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13512            final String[] requiredPermissions =
13513                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13514            if (extras != null) {
13515                intent.putExtras(extras);
13516            }
13517            if (targetPkg != null) {
13518                intent.setPackage(targetPkg);
13519            }
13520            // Modify the UID when posting to other users
13521            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13522            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13523                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13524                intent.putExtra(Intent.EXTRA_UID, uid);
13525            }
13526            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13527            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13528            if (DEBUG_BROADCASTS) {
13529                RuntimeException here = new RuntimeException("here");
13530                here.fillInStackTrace();
13531                Slog.d(TAG, "Sending to user " + id + ": "
13532                        + intent.toShortString(false, true, false, false)
13533                        + " " + intent.getExtras(), here);
13534            }
13535            am.broadcastIntent(null, intent, null, finishedReceiver,
13536                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13537                    null, finishedReceiver != null, false, id);
13538        }
13539    }
13540
13541    /**
13542     * Check if the external storage media is available. This is true if there
13543     * is a mounted external storage medium or if the external storage is
13544     * emulated.
13545     */
13546    private boolean isExternalMediaAvailable() {
13547        return mMediaMounted || Environment.isExternalStorageEmulated();
13548    }
13549
13550    @Override
13551    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13552        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13553            return null;
13554        }
13555        if (!isExternalMediaAvailable()) {
13556                // If the external storage is no longer mounted at this point,
13557                // the caller may not have been able to delete all of this
13558                // packages files and can not delete any more.  Bail.
13559            return null;
13560        }
13561        synchronized (mPackages) {
13562            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13563            if (lastPackage != null) {
13564                pkgs.remove(lastPackage);
13565            }
13566            if (pkgs.size() > 0) {
13567                return pkgs.get(0);
13568            }
13569        }
13570        return null;
13571    }
13572
13573    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13574        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13575                userId, andCode ? 1 : 0, packageName);
13576        if (mSystemReady) {
13577            msg.sendToTarget();
13578        } else {
13579            if (mPostSystemReadyMessages == null) {
13580                mPostSystemReadyMessages = new ArrayList<>();
13581            }
13582            mPostSystemReadyMessages.add(msg);
13583        }
13584    }
13585
13586    void startCleaningPackages() {
13587        // reader
13588        if (!isExternalMediaAvailable()) {
13589            return;
13590        }
13591        synchronized (mPackages) {
13592            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13593                return;
13594            }
13595        }
13596        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13597        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13598        IActivityManager am = ActivityManager.getService();
13599        if (am != null) {
13600            int dcsUid = -1;
13601            synchronized (mPackages) {
13602                if (!mDefaultContainerWhitelisted) {
13603                    mDefaultContainerWhitelisted = true;
13604                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13605                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13606                }
13607            }
13608            try {
13609                if (dcsUid > 0) {
13610                    am.backgroundWhitelistUid(dcsUid);
13611                }
13612                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13613                        UserHandle.USER_SYSTEM);
13614            } catch (RemoteException e) {
13615            }
13616        }
13617    }
13618
13619    /**
13620     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13621     * it is acting on behalf on an enterprise or the user).
13622     *
13623     * Note that the ordering of the conditionals in this method is important. The checks we perform
13624     * are as follows, in this order:
13625     *
13626     * 1) If the install is being performed by a system app, we can trust the app to have set the
13627     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13628     *    what it is.
13629     * 2) If the install is being performed by a device or profile owner app, the install reason
13630     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13631     *    set the install reason correctly. If the app targets an older SDK version where install
13632     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13633     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13634     * 3) In all other cases, the install is being performed by a regular app that is neither part
13635     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13636     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13637     *    set to enterprise policy and if so, change it to unknown instead.
13638     */
13639    private int fixUpInstallReason(String installerPackageName, int installerUid,
13640            int installReason) {
13641        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13642                == PERMISSION_GRANTED) {
13643            // If the install is being performed by a system app, we trust that app to have set the
13644            // install reason correctly.
13645            return installReason;
13646        }
13647        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13648                UserHandle.getUserId(installerUid));
13649        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13650            // If the install is being performed by a device or profile owner, the install
13651            // reason should be enterprise policy.
13652            return PackageManager.INSTALL_REASON_POLICY;
13653        }
13654
13655
13656        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13657            // If the install is being performed by a regular app (i.e. neither system app nor
13658            // device or profile owner), we have no reason to believe that the app is acting on
13659            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13660            // change it to unknown instead.
13661            return PackageManager.INSTALL_REASON_UNKNOWN;
13662        }
13663
13664        // If the install is being performed by a regular app and the install reason was set to any
13665        // value but enterprise policy, leave the install reason unchanged.
13666        return installReason;
13667    }
13668
13669    /**
13670     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13671     * install commit.
13672     */
13673    void earlyBindToDefContainer() {
13674        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13675    }
13676
13677    void installStage(String packageName, File stagedDir,
13678            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13679            String installerPackageName, int installerUid, UserHandle user,
13680            PackageParser.SigningDetails signingDetails) {
13681        if (DEBUG_INSTANT) {
13682            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13683                Slog.d(TAG, "Ephemeral install of " + packageName);
13684            }
13685        }
13686        final VerificationInfo verificationInfo = new VerificationInfo(
13687                sessionParams.originatingUri, sessionParams.referrerUri,
13688                sessionParams.originatingUid, installerUid);
13689
13690        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13691
13692        final Message msg = mHandler.obtainMessage(INIT_COPY);
13693        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13694                sessionParams.installReason);
13695        final InstallParams params = new InstallParams(origin, null, observer,
13696                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13697                verificationInfo, user, sessionParams.abiOverride,
13698                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13699        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13700        msg.obj = params;
13701
13702        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13703                System.identityHashCode(msg.obj));
13704        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13705                System.identityHashCode(msg.obj));
13706
13707        mHandler.sendMessage(msg);
13708    }
13709
13710    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13711            int userId) {
13712        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13713        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13714        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13715        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13716        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13717                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13718
13719        // Send a session commit broadcast
13720        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13721        info.installReason = pkgSetting.getInstallReason(userId);
13722        info.appPackageName = packageName;
13723        sendSessionCommitBroadcast(info, userId);
13724    }
13725
13726    @Override
13727    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13728            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13729        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13730            return;
13731        }
13732        Bundle extras = new Bundle(1);
13733        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13734        final int uid = UserHandle.getUid(
13735                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13736        extras.putInt(Intent.EXTRA_UID, uid);
13737
13738        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13739                packageName, extras, 0, null, null, userIds, instantUserIds);
13740        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13741            mHandler.post(() -> {
13742                        for (int userId : userIds) {
13743                            sendBootCompletedBroadcastToSystemApp(
13744                                    packageName, includeStopped, userId);
13745                        }
13746                    }
13747            );
13748        }
13749    }
13750
13751    /**
13752     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13753     * automatically without needing an explicit launch.
13754     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13755     */
13756    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13757            int userId) {
13758        // If user is not running, the app didn't miss any broadcast
13759        if (!mUserManagerInternal.isUserRunning(userId)) {
13760            return;
13761        }
13762        final IActivityManager am = ActivityManager.getService();
13763        try {
13764            // Deliver LOCKED_BOOT_COMPLETED first
13765            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13766                    .setPackage(packageName);
13767            if (includeStopped) {
13768                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13769            }
13770            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13771            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13772                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13773
13774            // Deliver BOOT_COMPLETED only if user is unlocked
13775            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13776                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13777                if (includeStopped) {
13778                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13779                }
13780                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13781                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13782            }
13783        } catch (RemoteException e) {
13784            throw e.rethrowFromSystemServer();
13785        }
13786    }
13787
13788    @Override
13789    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13790            int userId) {
13791        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13792        PackageSetting pkgSetting;
13793        final int callingUid = Binder.getCallingUid();
13794        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13795                true /* requireFullPermission */, true /* checkShell */,
13796                "setApplicationHiddenSetting for user " + userId);
13797
13798        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13799            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13800            return false;
13801        }
13802
13803        long callingId = Binder.clearCallingIdentity();
13804        try {
13805            boolean sendAdded = false;
13806            boolean sendRemoved = false;
13807            // writer
13808            synchronized (mPackages) {
13809                pkgSetting = mSettings.mPackages.get(packageName);
13810                if (pkgSetting == null) {
13811                    return false;
13812                }
13813                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13814                    return false;
13815                }
13816                // Do not allow "android" is being disabled
13817                if ("android".equals(packageName)) {
13818                    Slog.w(TAG, "Cannot hide package: android");
13819                    return false;
13820                }
13821                // Cannot hide static shared libs as they are considered
13822                // a part of the using app (emulating static linking). Also
13823                // static libs are installed always on internal storage.
13824                PackageParser.Package pkg = mPackages.get(packageName);
13825                if (pkg != null && pkg.staticSharedLibName != null) {
13826                    Slog.w(TAG, "Cannot hide package: " + packageName
13827                            + " providing static shared library: "
13828                            + pkg.staticSharedLibName);
13829                    return false;
13830                }
13831                // Only allow protected packages to hide themselves.
13832                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13833                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13834                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13835                    return false;
13836                }
13837
13838                if (pkgSetting.getHidden(userId) != hidden) {
13839                    pkgSetting.setHidden(hidden, userId);
13840                    mSettings.writePackageRestrictionsLPr(userId);
13841                    if (hidden) {
13842                        sendRemoved = true;
13843                    } else {
13844                        sendAdded = true;
13845                    }
13846                }
13847            }
13848            if (sendAdded) {
13849                sendPackageAddedForUser(packageName, pkgSetting, userId);
13850                return true;
13851            }
13852            if (sendRemoved) {
13853                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13854                        "hiding pkg");
13855                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13856                return true;
13857            }
13858        } finally {
13859            Binder.restoreCallingIdentity(callingId);
13860        }
13861        return false;
13862    }
13863
13864    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13865            int userId) {
13866        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13867        info.removedPackage = packageName;
13868        info.installerPackageName = pkgSetting.installerPackageName;
13869        info.removedUsers = new int[] {userId};
13870        info.broadcastUsers = new int[] {userId};
13871        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13872        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13873    }
13874
13875    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13876            PersistableBundle launcherExtras) {
13877        if (pkgList.length > 0) {
13878            Bundle extras = new Bundle(1);
13879            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13880            if (launcherExtras != null) {
13881                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13882                        new Bundle(launcherExtras.deepCopy()));
13883            }
13884            sendPackageBroadcast(
13885                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13886                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13887                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13888                    new int[] {userId}, null);
13889        }
13890    }
13891
13892    /**
13893     * Returns true if application is not found or there was an error. Otherwise it returns
13894     * the hidden state of the package for the given user.
13895     */
13896    @Override
13897    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13898        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13899        final int callingUid = Binder.getCallingUid();
13900        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13901                true /* requireFullPermission */, false /* checkShell */,
13902                "getApplicationHidden for user " + userId);
13903        PackageSetting ps;
13904        long callingId = Binder.clearCallingIdentity();
13905        try {
13906            // writer
13907            synchronized (mPackages) {
13908                ps = mSettings.mPackages.get(packageName);
13909                if (ps == null) {
13910                    return true;
13911                }
13912                if (filterAppAccessLPr(ps, callingUid, userId)) {
13913                    return true;
13914                }
13915                return ps.getHidden(userId);
13916            }
13917        } finally {
13918            Binder.restoreCallingIdentity(callingId);
13919        }
13920    }
13921
13922    /**
13923     * @hide
13924     */
13925    @Override
13926    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13927            int installReason) {
13928        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13929                null);
13930        PackageSetting pkgSetting;
13931        final int callingUid = Binder.getCallingUid();
13932        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13933                true /* requireFullPermission */, true /* checkShell */,
13934                "installExistingPackage for user " + userId);
13935        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13936            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13937        }
13938
13939        long callingId = Binder.clearCallingIdentity();
13940        try {
13941            boolean installed = false;
13942            final boolean instantApp =
13943                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13944            final boolean fullApp =
13945                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13946
13947            // writer
13948            synchronized (mPackages) {
13949                pkgSetting = mSettings.mPackages.get(packageName);
13950                if (pkgSetting == null) {
13951                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13952                }
13953                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13954                    // only allow the existing package to be used if it's installed as a full
13955                    // application for at least one user
13956                    boolean installAllowed = false;
13957                    for (int checkUserId : sUserManager.getUserIds()) {
13958                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13959                        if (installAllowed) {
13960                            break;
13961                        }
13962                    }
13963                    if (!installAllowed) {
13964                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13965                    }
13966                }
13967                if (!pkgSetting.getInstalled(userId)) {
13968                    pkgSetting.setInstalled(true, userId);
13969                    pkgSetting.setHidden(false, userId);
13970                    pkgSetting.setInstallReason(installReason, userId);
13971                    mSettings.writePackageRestrictionsLPr(userId);
13972                    mSettings.writeKernelMappingLPr(pkgSetting);
13973                    installed = true;
13974                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13975                    // upgrade app from instant to full; we don't allow app downgrade
13976                    installed = true;
13977                }
13978                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13979            }
13980
13981            if (installed) {
13982                if (pkgSetting.pkg != null) {
13983                    synchronized (mInstallLock) {
13984                        // We don't need to freeze for a brand new install
13985                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13986                    }
13987                }
13988                sendPackageAddedForUser(packageName, pkgSetting, userId);
13989                synchronized (mPackages) {
13990                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13991                }
13992            }
13993        } finally {
13994            Binder.restoreCallingIdentity(callingId);
13995        }
13996
13997        return PackageManager.INSTALL_SUCCEEDED;
13998    }
13999
14000    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14001            boolean instantApp, boolean fullApp) {
14002        // no state specified; do nothing
14003        if (!instantApp && !fullApp) {
14004            return;
14005        }
14006        if (userId != UserHandle.USER_ALL) {
14007            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14008                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14009            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14010                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14011            }
14012        } else {
14013            for (int currentUserId : sUserManager.getUserIds()) {
14014                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14015                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14016                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14017                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14018                }
14019            }
14020        }
14021    }
14022
14023    boolean isUserRestricted(int userId, String restrictionKey) {
14024        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14025        if (restrictions.getBoolean(restrictionKey, false)) {
14026            Log.w(TAG, "User is restricted: " + restrictionKey);
14027            return true;
14028        }
14029        return false;
14030    }
14031
14032    @Override
14033    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14034            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14035            String callingPackage, int userId) {
14036        try {
14037            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14038        } catch (SecurityException e) {
14039            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14040                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14041                            + Manifest.permission.MANAGE_USERS);
14042        }
14043        final int callingUid = Binder.getCallingUid();
14044        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14045                true /* requireFullPermission */, true /* checkShell */,
14046                "setPackagesSuspended for user " + userId);
14047        if (callingUid != Process.ROOT_UID &&
14048                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14049            throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not"
14050                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14051        }
14052        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14053                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14054            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14055                    + userId + " has an active DO or PO");
14056        }
14057        if (ArrayUtils.isEmpty(packageNames)) {
14058            return packageNames;
14059        }
14060
14061        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14062        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14063        final long callingId = Binder.clearCallingIdentity();
14064        try {
14065            synchronized (mPackages) {
14066                for (int i = 0; i < packageNames.length; i++) {
14067                    final String packageName = packageNames[i];
14068                    if (callingPackage.equals(packageName)) {
14069                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14070                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14071                        unactionedPackages.add(packageName);
14072                        continue;
14073                    }
14074                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14075                    if (pkgSetting == null
14076                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14077                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14078                                + ". Skipping suspending/un-suspending.");
14079                        unactionedPackages.add(packageName);
14080                        continue;
14081                    }
14082                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14083                        unactionedPackages.add(packageName);
14084                        continue;
14085                    }
14086                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14087                            launcherExtras, userId);
14088                    changedPackagesList.add(packageName);
14089                }
14090            }
14091        } finally {
14092            Binder.restoreCallingIdentity(callingId);
14093        }
14094        if (!changedPackagesList.isEmpty()) {
14095            final String[] changedPackages = changedPackagesList.toArray(
14096                    new String[changedPackagesList.size()]);
14097            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14098            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14099            synchronized (mPackages) {
14100                scheduleWritePackageRestrictionsLocked(userId);
14101            }
14102        }
14103        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14104    }
14105
14106    @Override
14107    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14108        final int callingUid = Binder.getCallingUid();
14109        if (getPackageUid(packageName, 0, userId) != callingUid) {
14110            throw new SecurityException("Calling package " + packageName
14111                    + " does not belong to calling uid " + callingUid);
14112        }
14113        synchronized (mPackages) {
14114            final PackageSetting ps = mSettings.mPackages.get(packageName);
14115            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14116                throw new IllegalArgumentException("Unknown target package: " + packageName);
14117            }
14118            final PackageUserState packageUserState = ps.readUserState(userId);
14119            if (packageUserState.suspended) {
14120                return packageUserState.suspendedAppExtras;
14121            }
14122            return null;
14123        }
14124    }
14125
14126    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14127            PersistableBundle appExtras, int userId) {
14128        final String action;
14129        final Bundle intentExtras = new Bundle();
14130        if (suspended) {
14131            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14132            if (appExtras != null) {
14133                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14134                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14135            }
14136        } else {
14137            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14138        }
14139        mHandler.post(new Runnable() {
14140            @Override
14141            public void run() {
14142                try {
14143                    final IActivityManager am = ActivityManager.getService();
14144                    if (am == null) {
14145                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14146                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14147                        return;
14148                    }
14149                    final int[] targetUserIds = new int[] {userId};
14150                    for (String packageName : affectedPackages) {
14151                        doSendBroadcast(am, action, null, intentExtras,
14152                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14153                                targetUserIds, false);
14154                    }
14155                } catch (RemoteException ex) {
14156                    // Shouldn't happen as AMS is in the same process.
14157                }
14158            }
14159        });
14160    }
14161
14162    @Override
14163    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14164        final int callingUid = Binder.getCallingUid();
14165        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14166                true /* requireFullPermission */, false /* checkShell */,
14167                "isPackageSuspendedForUser for user " + userId);
14168        synchronized (mPackages) {
14169            final PackageSetting ps = mSettings.mPackages.get(packageName);
14170            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14171                throw new IllegalArgumentException("Unknown target package: " + packageName);
14172            }
14173            return ps.getSuspended(userId);
14174        }
14175    }
14176
14177    void onSuspendingPackageRemoved(String packageName, int removedForUser) {
14178        final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14179                : new int[] {removedForUser};
14180        for (int userId : userIds) {
14181            List<String> affectedPackages = new ArrayList<>();
14182            synchronized (mPackages) {
14183                for (PackageSetting ps : mSettings.mPackages.values()) {
14184                    final PackageUserState pus = ps.readUserState(userId);
14185                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14186                        ps.setSuspended(false, null, null, null, null, userId);
14187                        affectedPackages.add(ps.name);
14188                    }
14189                }
14190            }
14191            if (!affectedPackages.isEmpty()) {
14192                final String[] packageArray = affectedPackages.toArray(
14193                        new String[affectedPackages.size()]);
14194                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14195                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14196            }
14197        }
14198    }
14199
14200    @GuardedBy("mPackages")
14201    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14202        if (isPackageDeviceAdmin(packageName, userId)) {
14203            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14204                    + "\": has an active device admin");
14205            return false;
14206        }
14207
14208        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14209        if (packageName.equals(activeLauncherPackageName)) {
14210            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14211                    + "\": contains the active launcher");
14212            return false;
14213        }
14214
14215        if (packageName.equals(mRequiredInstallerPackage)) {
14216            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14217                    + "\": required for package installation");
14218            return false;
14219        }
14220
14221        if (packageName.equals(mRequiredUninstallerPackage)) {
14222            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14223                    + "\": required for package uninstallation");
14224            return false;
14225        }
14226
14227        if (packageName.equals(mRequiredVerifierPackage)) {
14228            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14229                    + "\": required for package verification");
14230            return false;
14231        }
14232
14233        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14234            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14235                    + "\": is the default dialer");
14236            return false;
14237        }
14238
14239        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14240            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14241                    + "\": protected package");
14242            return false;
14243        }
14244
14245        // Cannot suspend static shared libs as they are considered
14246        // a part of the using app (emulating static linking). Also
14247        // static libs are installed always on internal storage.
14248        PackageParser.Package pkg = mPackages.get(packageName);
14249        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14250            Slog.w(TAG, "Cannot suspend package: " + packageName
14251                    + " providing static shared library: "
14252                    + pkg.staticSharedLibName);
14253            return false;
14254        }
14255
14256        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14257            Slog.w(TAG, "Cannot suspend package: " + packageName);
14258            return false;
14259        }
14260
14261        return true;
14262    }
14263
14264    private String getActiveLauncherPackageName(int userId) {
14265        Intent intent = new Intent(Intent.ACTION_MAIN);
14266        intent.addCategory(Intent.CATEGORY_HOME);
14267        ResolveInfo resolveInfo = resolveIntent(
14268                intent,
14269                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14270                PackageManager.MATCH_DEFAULT_ONLY,
14271                userId);
14272
14273        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14274    }
14275
14276    private String getDefaultDialerPackageName(int userId) {
14277        synchronized (mPackages) {
14278            return mSettings.getDefaultDialerPackageNameLPw(userId);
14279        }
14280    }
14281
14282    @Override
14283    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14284        mContext.enforceCallingOrSelfPermission(
14285                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14286                "Only package verification agents can verify applications");
14287
14288        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14289        final PackageVerificationResponse response = new PackageVerificationResponse(
14290                verificationCode, Binder.getCallingUid());
14291        msg.arg1 = id;
14292        msg.obj = response;
14293        mHandler.sendMessage(msg);
14294    }
14295
14296    @Override
14297    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14298            long millisecondsToDelay) {
14299        mContext.enforceCallingOrSelfPermission(
14300                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14301                "Only package verification agents can extend verification timeouts");
14302
14303        final PackageVerificationState state = mPendingVerification.get(id);
14304        final PackageVerificationResponse response = new PackageVerificationResponse(
14305                verificationCodeAtTimeout, Binder.getCallingUid());
14306
14307        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14308            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14309        }
14310        if (millisecondsToDelay < 0) {
14311            millisecondsToDelay = 0;
14312        }
14313        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14314                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14315            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14316        }
14317
14318        if ((state != null) && !state.timeoutExtended()) {
14319            state.extendTimeout();
14320
14321            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14322            msg.arg1 = id;
14323            msg.obj = response;
14324            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14325        }
14326    }
14327
14328    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14329            int verificationCode, UserHandle user) {
14330        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14331        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14332        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14333        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14334        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14335
14336        mContext.sendBroadcastAsUser(intent, user,
14337                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14338    }
14339
14340    private ComponentName matchComponentForVerifier(String packageName,
14341            List<ResolveInfo> receivers) {
14342        ActivityInfo targetReceiver = null;
14343
14344        final int NR = receivers.size();
14345        for (int i = 0; i < NR; i++) {
14346            final ResolveInfo info = receivers.get(i);
14347            if (info.activityInfo == null) {
14348                continue;
14349            }
14350
14351            if (packageName.equals(info.activityInfo.packageName)) {
14352                targetReceiver = info.activityInfo;
14353                break;
14354            }
14355        }
14356
14357        if (targetReceiver == null) {
14358            return null;
14359        }
14360
14361        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14362    }
14363
14364    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14365            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14366        if (pkgInfo.verifiers.length == 0) {
14367            return null;
14368        }
14369
14370        final int N = pkgInfo.verifiers.length;
14371        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14372        for (int i = 0; i < N; i++) {
14373            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14374
14375            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14376                    receivers);
14377            if (comp == null) {
14378                continue;
14379            }
14380
14381            final int verifierUid = getUidForVerifier(verifierInfo);
14382            if (verifierUid == -1) {
14383                continue;
14384            }
14385
14386            if (DEBUG_VERIFY) {
14387                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14388                        + " with the correct signature");
14389            }
14390            sufficientVerifiers.add(comp);
14391            verificationState.addSufficientVerifier(verifierUid);
14392        }
14393
14394        return sufficientVerifiers;
14395    }
14396
14397    private int getUidForVerifier(VerifierInfo verifierInfo) {
14398        synchronized (mPackages) {
14399            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14400            if (pkg == null) {
14401                return -1;
14402            } else if (pkg.mSigningDetails.signatures.length != 1) {
14403                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14404                        + " has more than one signature; ignoring");
14405                return -1;
14406            }
14407
14408            /*
14409             * If the public key of the package's signature does not match
14410             * our expected public key, then this is a different package and
14411             * we should skip.
14412             */
14413
14414            final byte[] expectedPublicKey;
14415            try {
14416                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14417                final PublicKey publicKey = verifierSig.getPublicKey();
14418                expectedPublicKey = publicKey.getEncoded();
14419            } catch (CertificateException e) {
14420                return -1;
14421            }
14422
14423            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14424
14425            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14426                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14427                        + " does not have the expected public key; ignoring");
14428                return -1;
14429            }
14430
14431            return pkg.applicationInfo.uid;
14432        }
14433    }
14434
14435    @Override
14436    public void finishPackageInstall(int token, boolean didLaunch) {
14437        enforceSystemOrRoot("Only the system is allowed to finish installs");
14438
14439        if (DEBUG_INSTALL) {
14440            Slog.v(TAG, "BM finishing package install for " + token);
14441        }
14442        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14443
14444        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14445        mHandler.sendMessage(msg);
14446    }
14447
14448    /**
14449     * Get the verification agent timeout.  Used for both the APK verifier and the
14450     * intent filter verifier.
14451     *
14452     * @return verification timeout in milliseconds
14453     */
14454    private long getVerificationTimeout() {
14455        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14456                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14457                DEFAULT_VERIFICATION_TIMEOUT);
14458    }
14459
14460    /**
14461     * Get the default verification agent response code.
14462     *
14463     * @return default verification response code
14464     */
14465    private int getDefaultVerificationResponse(UserHandle user) {
14466        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14467            return PackageManager.VERIFICATION_REJECT;
14468        }
14469        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14470                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14471                DEFAULT_VERIFICATION_RESPONSE);
14472    }
14473
14474    /**
14475     * Check whether or not package verification has been enabled.
14476     *
14477     * @return true if verification should be performed
14478     */
14479    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14480        if (!DEFAULT_VERIFY_ENABLE) {
14481            return false;
14482        }
14483
14484        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14485
14486        // Check if installing from ADB
14487        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14488            // Do not run verification in a test harness environment
14489            if (ActivityManager.isRunningInTestHarness()) {
14490                return false;
14491            }
14492            if (ensureVerifyAppsEnabled) {
14493                return true;
14494            }
14495            // Check if the developer does not want package verification for ADB installs
14496            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14497                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14498                return false;
14499            }
14500        } else {
14501            // only when not installed from ADB, skip verification for instant apps when
14502            // the installer and verifier are the same.
14503            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14504                if (mInstantAppInstallerActivity != null
14505                        && mInstantAppInstallerActivity.packageName.equals(
14506                                mRequiredVerifierPackage)) {
14507                    try {
14508                        mContext.getSystemService(AppOpsManager.class)
14509                                .checkPackage(installerUid, mRequiredVerifierPackage);
14510                        if (DEBUG_VERIFY) {
14511                            Slog.i(TAG, "disable verification for instant app");
14512                        }
14513                        return false;
14514                    } catch (SecurityException ignore) { }
14515                }
14516            }
14517        }
14518
14519        if (ensureVerifyAppsEnabled) {
14520            return true;
14521        }
14522
14523        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14524                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14525    }
14526
14527    @Override
14528    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14529            throws RemoteException {
14530        mContext.enforceCallingOrSelfPermission(
14531                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14532                "Only intentfilter verification agents can verify applications");
14533
14534        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14535        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14536                Binder.getCallingUid(), verificationCode, failedDomains);
14537        msg.arg1 = id;
14538        msg.obj = response;
14539        mHandler.sendMessage(msg);
14540    }
14541
14542    @Override
14543    public int getIntentVerificationStatus(String packageName, int userId) {
14544        final int callingUid = Binder.getCallingUid();
14545        if (UserHandle.getUserId(callingUid) != userId) {
14546            mContext.enforceCallingOrSelfPermission(
14547                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14548                    "getIntentVerificationStatus" + userId);
14549        }
14550        if (getInstantAppPackageName(callingUid) != null) {
14551            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14552        }
14553        synchronized (mPackages) {
14554            final PackageSetting ps = mSettings.mPackages.get(packageName);
14555            if (ps == null
14556                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14557                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14558            }
14559            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14560        }
14561    }
14562
14563    @Override
14564    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14565        mContext.enforceCallingOrSelfPermission(
14566                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14567
14568        boolean result = false;
14569        synchronized (mPackages) {
14570            final PackageSetting ps = mSettings.mPackages.get(packageName);
14571            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14572                return false;
14573            }
14574            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14575        }
14576        if (result) {
14577            scheduleWritePackageRestrictionsLocked(userId);
14578        }
14579        return result;
14580    }
14581
14582    @Override
14583    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14584            String packageName) {
14585        final int callingUid = Binder.getCallingUid();
14586        if (getInstantAppPackageName(callingUid) != null) {
14587            return ParceledListSlice.emptyList();
14588        }
14589        synchronized (mPackages) {
14590            final PackageSetting ps = mSettings.mPackages.get(packageName);
14591            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14592                return ParceledListSlice.emptyList();
14593            }
14594            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14595        }
14596    }
14597
14598    @Override
14599    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14600        if (TextUtils.isEmpty(packageName)) {
14601            return ParceledListSlice.emptyList();
14602        }
14603        final int callingUid = Binder.getCallingUid();
14604        final int callingUserId = UserHandle.getUserId(callingUid);
14605        synchronized (mPackages) {
14606            PackageParser.Package pkg = mPackages.get(packageName);
14607            if (pkg == null || pkg.activities == null) {
14608                return ParceledListSlice.emptyList();
14609            }
14610            if (pkg.mExtras == null) {
14611                return ParceledListSlice.emptyList();
14612            }
14613            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14614            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14615                return ParceledListSlice.emptyList();
14616            }
14617            final int count = pkg.activities.size();
14618            ArrayList<IntentFilter> result = new ArrayList<>();
14619            for (int n=0; n<count; n++) {
14620                PackageParser.Activity activity = pkg.activities.get(n);
14621                if (activity.intents != null && activity.intents.size() > 0) {
14622                    result.addAll(activity.intents);
14623                }
14624            }
14625            return new ParceledListSlice<>(result);
14626        }
14627    }
14628
14629    @Override
14630    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14631        mContext.enforceCallingOrSelfPermission(
14632                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14633        if (UserHandle.getCallingUserId() != userId) {
14634            mContext.enforceCallingOrSelfPermission(
14635                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14636        }
14637
14638        synchronized (mPackages) {
14639            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14640            if (packageName != null) {
14641                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14642                        packageName, userId);
14643            }
14644            return result;
14645        }
14646    }
14647
14648    @Override
14649    public String getDefaultBrowserPackageName(int userId) {
14650        if (UserHandle.getCallingUserId() != userId) {
14651            mContext.enforceCallingOrSelfPermission(
14652                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14653        }
14654        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14655            return null;
14656        }
14657        synchronized (mPackages) {
14658            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14659        }
14660    }
14661
14662    /**
14663     * Get the "allow unknown sources" setting.
14664     *
14665     * @return the current "allow unknown sources" setting
14666     */
14667    private int getUnknownSourcesSettings() {
14668        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14669                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14670                -1);
14671    }
14672
14673    @Override
14674    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14675        final int callingUid = Binder.getCallingUid();
14676        if (getInstantAppPackageName(callingUid) != null) {
14677            return;
14678        }
14679        // writer
14680        synchronized (mPackages) {
14681            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14682            if (targetPackageSetting == null
14683                    || filterAppAccessLPr(
14684                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14685                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14686            }
14687
14688            PackageSetting installerPackageSetting;
14689            if (installerPackageName != null) {
14690                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14691                if (installerPackageSetting == null) {
14692                    throw new IllegalArgumentException("Unknown installer package: "
14693                            + installerPackageName);
14694                }
14695            } else {
14696                installerPackageSetting = null;
14697            }
14698
14699            Signature[] callerSignature;
14700            Object obj = mSettings.getUserIdLPr(callingUid);
14701            if (obj != null) {
14702                if (obj instanceof SharedUserSetting) {
14703                    callerSignature =
14704                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14705                } else if (obj instanceof PackageSetting) {
14706                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14707                } else {
14708                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14709                }
14710            } else {
14711                throw new SecurityException("Unknown calling UID: " + callingUid);
14712            }
14713
14714            // Verify: can't set installerPackageName to a package that is
14715            // not signed with the same cert as the caller.
14716            if (installerPackageSetting != null) {
14717                if (compareSignatures(callerSignature,
14718                        installerPackageSetting.signatures.mSigningDetails.signatures)
14719                        != PackageManager.SIGNATURE_MATCH) {
14720                    throw new SecurityException(
14721                            "Caller does not have same cert as new installer package "
14722                            + installerPackageName);
14723                }
14724            }
14725
14726            // Verify: if target already has an installer package, it must
14727            // be signed with the same cert as the caller.
14728            if (targetPackageSetting.installerPackageName != null) {
14729                PackageSetting setting = mSettings.mPackages.get(
14730                        targetPackageSetting.installerPackageName);
14731                // If the currently set package isn't valid, then it's always
14732                // okay to change it.
14733                if (setting != null) {
14734                    if (compareSignatures(callerSignature,
14735                            setting.signatures.mSigningDetails.signatures)
14736                            != PackageManager.SIGNATURE_MATCH) {
14737                        throw new SecurityException(
14738                                "Caller does not have same cert as old installer package "
14739                                + targetPackageSetting.installerPackageName);
14740                    }
14741                }
14742            }
14743
14744            // Okay!
14745            targetPackageSetting.installerPackageName = installerPackageName;
14746            if (installerPackageName != null) {
14747                mSettings.mInstallerPackages.add(installerPackageName);
14748            }
14749            scheduleWriteSettingsLocked();
14750        }
14751    }
14752
14753    @Override
14754    public void setApplicationCategoryHint(String packageName, int categoryHint,
14755            String callerPackageName) {
14756        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14757            throw new SecurityException("Instant applications don't have access to this method");
14758        }
14759        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14760                callerPackageName);
14761        synchronized (mPackages) {
14762            PackageSetting ps = mSettings.mPackages.get(packageName);
14763            if (ps == null) {
14764                throw new IllegalArgumentException("Unknown target package " + packageName);
14765            }
14766            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14767                throw new IllegalArgumentException("Unknown target package " + packageName);
14768            }
14769            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14770                throw new IllegalArgumentException("Calling package " + callerPackageName
14771                        + " is not installer for " + packageName);
14772            }
14773
14774            if (ps.categoryHint != categoryHint) {
14775                ps.categoryHint = categoryHint;
14776                scheduleWriteSettingsLocked();
14777            }
14778        }
14779    }
14780
14781    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14782        // Queue up an async operation since the package installation may take a little while.
14783        mHandler.post(new Runnable() {
14784            public void run() {
14785                mHandler.removeCallbacks(this);
14786                 // Result object to be returned
14787                PackageInstalledInfo res = new PackageInstalledInfo();
14788                res.setReturnCode(currentStatus);
14789                res.uid = -1;
14790                res.pkg = null;
14791                res.removedInfo = null;
14792                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14793                    args.doPreInstall(res.returnCode);
14794                    synchronized (mInstallLock) {
14795                        installPackageTracedLI(args, res);
14796                    }
14797                    args.doPostInstall(res.returnCode, res.uid);
14798                }
14799
14800                // A restore should be performed at this point if (a) the install
14801                // succeeded, (b) the operation is not an update, and (c) the new
14802                // package has not opted out of backup participation.
14803                final boolean update = res.removedInfo != null
14804                        && res.removedInfo.removedPackage != null;
14805                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14806                boolean doRestore = !update
14807                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14808
14809                // Set up the post-install work request bookkeeping.  This will be used
14810                // and cleaned up by the post-install event handling regardless of whether
14811                // there's a restore pass performed.  Token values are >= 1.
14812                int token;
14813                if (mNextInstallToken < 0) mNextInstallToken = 1;
14814                token = mNextInstallToken++;
14815
14816                PostInstallData data = new PostInstallData(args, res);
14817                mRunningInstalls.put(token, data);
14818                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14819
14820                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14821                    // Pass responsibility to the Backup Manager.  It will perform a
14822                    // restore if appropriate, then pass responsibility back to the
14823                    // Package Manager to run the post-install observer callbacks
14824                    // and broadcasts.
14825                    IBackupManager bm = IBackupManager.Stub.asInterface(
14826                            ServiceManager.getService(Context.BACKUP_SERVICE));
14827                    if (bm != null) {
14828                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14829                                + " to BM for possible restore");
14830                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14831                        try {
14832                            // TODO: http://b/22388012
14833                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14834                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14835                            } else {
14836                                doRestore = false;
14837                            }
14838                        } catch (RemoteException e) {
14839                            // can't happen; the backup manager is local
14840                        } catch (Exception e) {
14841                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14842                            doRestore = false;
14843                        }
14844                    } else {
14845                        Slog.e(TAG, "Backup Manager not found!");
14846                        doRestore = false;
14847                    }
14848                }
14849
14850                if (!doRestore) {
14851                    // No restore possible, or the Backup Manager was mysteriously not
14852                    // available -- just fire the post-install work request directly.
14853                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14854
14855                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14856
14857                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14858                    mHandler.sendMessage(msg);
14859                }
14860            }
14861        });
14862    }
14863
14864    /**
14865     * Callback from PackageSettings whenever an app is first transitioned out of the
14866     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14867     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14868     * here whether the app is the target of an ongoing install, and only send the
14869     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14870     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14871     * handling.
14872     */
14873    void notifyFirstLaunch(final String packageName, final String installerPackage,
14874            final int userId) {
14875        // Serialize this with the rest of the install-process message chain.  In the
14876        // restore-at-install case, this Runnable will necessarily run before the
14877        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14878        // are coherent.  In the non-restore case, the app has already completed install
14879        // and been launched through some other means, so it is not in a problematic
14880        // state for observers to see the FIRST_LAUNCH signal.
14881        mHandler.post(new Runnable() {
14882            @Override
14883            public void run() {
14884                for (int i = 0; i < mRunningInstalls.size(); i++) {
14885                    final PostInstallData data = mRunningInstalls.valueAt(i);
14886                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14887                        continue;
14888                    }
14889                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14890                        // right package; but is it for the right user?
14891                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14892                            if (userId == data.res.newUsers[uIndex]) {
14893                                if (DEBUG_BACKUP) {
14894                                    Slog.i(TAG, "Package " + packageName
14895                                            + " being restored so deferring FIRST_LAUNCH");
14896                                }
14897                                return;
14898                            }
14899                        }
14900                    }
14901                }
14902                // didn't find it, so not being restored
14903                if (DEBUG_BACKUP) {
14904                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14905                }
14906                final boolean isInstantApp = isInstantApp(packageName, userId);
14907                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14908                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14909                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14910            }
14911        });
14912    }
14913
14914    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14915            int[] userIds, int[] instantUserIds) {
14916        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14917                installerPkg, null, userIds, instantUserIds);
14918    }
14919
14920    private abstract class HandlerParams {
14921        private static final int MAX_RETRIES = 4;
14922
14923        /**
14924         * Number of times startCopy() has been attempted and had a non-fatal
14925         * error.
14926         */
14927        private int mRetries = 0;
14928
14929        /** User handle for the user requesting the information or installation. */
14930        private final UserHandle mUser;
14931        String traceMethod;
14932        int traceCookie;
14933
14934        HandlerParams(UserHandle user) {
14935            mUser = user;
14936        }
14937
14938        UserHandle getUser() {
14939            return mUser;
14940        }
14941
14942        HandlerParams setTraceMethod(String traceMethod) {
14943            this.traceMethod = traceMethod;
14944            return this;
14945        }
14946
14947        HandlerParams setTraceCookie(int traceCookie) {
14948            this.traceCookie = traceCookie;
14949            return this;
14950        }
14951
14952        final boolean startCopy() {
14953            boolean res;
14954            try {
14955                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14956
14957                if (++mRetries > MAX_RETRIES) {
14958                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14959                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14960                    handleServiceError();
14961                    return false;
14962                } else {
14963                    handleStartCopy();
14964                    res = true;
14965                }
14966            } catch (RemoteException e) {
14967                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14968                mHandler.sendEmptyMessage(MCS_RECONNECT);
14969                res = false;
14970            }
14971            handleReturnCode();
14972            return res;
14973        }
14974
14975        final void serviceError() {
14976            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14977            handleServiceError();
14978            handleReturnCode();
14979        }
14980
14981        abstract void handleStartCopy() throws RemoteException;
14982        abstract void handleServiceError();
14983        abstract void handleReturnCode();
14984    }
14985
14986    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14987        for (File path : paths) {
14988            try {
14989                mcs.clearDirectory(path.getAbsolutePath());
14990            } catch (RemoteException e) {
14991            }
14992        }
14993    }
14994
14995    static class OriginInfo {
14996        /**
14997         * Location where install is coming from, before it has been
14998         * copied/renamed into place. This could be a single monolithic APK
14999         * file, or a cluster directory. This location may be untrusted.
15000         */
15001        final File file;
15002
15003        /**
15004         * Flag indicating that {@link #file} or {@link #cid} has already been
15005         * staged, meaning downstream users don't need to defensively copy the
15006         * contents.
15007         */
15008        final boolean staged;
15009
15010        /**
15011         * Flag indicating that {@link #file} or {@link #cid} is an already
15012         * installed app that is being moved.
15013         */
15014        final boolean existing;
15015
15016        final String resolvedPath;
15017        final File resolvedFile;
15018
15019        static OriginInfo fromNothing() {
15020            return new OriginInfo(null, false, false);
15021        }
15022
15023        static OriginInfo fromUntrustedFile(File file) {
15024            return new OriginInfo(file, false, false);
15025        }
15026
15027        static OriginInfo fromExistingFile(File file) {
15028            return new OriginInfo(file, false, true);
15029        }
15030
15031        static OriginInfo fromStagedFile(File file) {
15032            return new OriginInfo(file, true, false);
15033        }
15034
15035        private OriginInfo(File file, boolean staged, boolean existing) {
15036            this.file = file;
15037            this.staged = staged;
15038            this.existing = existing;
15039
15040            if (file != null) {
15041                resolvedPath = file.getAbsolutePath();
15042                resolvedFile = file;
15043            } else {
15044                resolvedPath = null;
15045                resolvedFile = null;
15046            }
15047        }
15048    }
15049
15050    static class MoveInfo {
15051        final int moveId;
15052        final String fromUuid;
15053        final String toUuid;
15054        final String packageName;
15055        final String dataAppName;
15056        final int appId;
15057        final String seinfo;
15058        final int targetSdkVersion;
15059
15060        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15061                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15062            this.moveId = moveId;
15063            this.fromUuid = fromUuid;
15064            this.toUuid = toUuid;
15065            this.packageName = packageName;
15066            this.dataAppName = dataAppName;
15067            this.appId = appId;
15068            this.seinfo = seinfo;
15069            this.targetSdkVersion = targetSdkVersion;
15070        }
15071    }
15072
15073    static class VerificationInfo {
15074        /** A constant used to indicate that a uid value is not present. */
15075        public static final int NO_UID = -1;
15076
15077        /** URI referencing where the package was downloaded from. */
15078        final Uri originatingUri;
15079
15080        /** HTTP referrer URI associated with the originatingURI. */
15081        final Uri referrer;
15082
15083        /** UID of the application that the install request originated from. */
15084        final int originatingUid;
15085
15086        /** UID of application requesting the install */
15087        final int installerUid;
15088
15089        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15090            this.originatingUri = originatingUri;
15091            this.referrer = referrer;
15092            this.originatingUid = originatingUid;
15093            this.installerUid = installerUid;
15094        }
15095    }
15096
15097    class InstallParams extends HandlerParams {
15098        final OriginInfo origin;
15099        final MoveInfo move;
15100        final IPackageInstallObserver2 observer;
15101        int installFlags;
15102        final String installerPackageName;
15103        final String volumeUuid;
15104        private InstallArgs mArgs;
15105        private int mRet;
15106        final String packageAbiOverride;
15107        final String[] grantedRuntimePermissions;
15108        final VerificationInfo verificationInfo;
15109        final PackageParser.SigningDetails signingDetails;
15110        final int installReason;
15111
15112        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15113                int installFlags, String installerPackageName, String volumeUuid,
15114                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15115                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15116            super(user);
15117            this.origin = origin;
15118            this.move = move;
15119            this.observer = observer;
15120            this.installFlags = installFlags;
15121            this.installerPackageName = installerPackageName;
15122            this.volumeUuid = volumeUuid;
15123            this.verificationInfo = verificationInfo;
15124            this.packageAbiOverride = packageAbiOverride;
15125            this.grantedRuntimePermissions = grantedPermissions;
15126            this.signingDetails = signingDetails;
15127            this.installReason = installReason;
15128        }
15129
15130        @Override
15131        public String toString() {
15132            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15133                    + " file=" + origin.file + "}";
15134        }
15135
15136        private int installLocationPolicy(PackageInfoLite pkgLite) {
15137            String packageName = pkgLite.packageName;
15138            int installLocation = pkgLite.installLocation;
15139            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15140            // reader
15141            synchronized (mPackages) {
15142                // Currently installed package which the new package is attempting to replace or
15143                // null if no such package is installed.
15144                PackageParser.Package installedPkg = mPackages.get(packageName);
15145                // Package which currently owns the data which the new package will own if installed.
15146                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15147                // will be null whereas dataOwnerPkg will contain information about the package
15148                // which was uninstalled while keeping its data.
15149                PackageParser.Package dataOwnerPkg = installedPkg;
15150                if (dataOwnerPkg  == null) {
15151                    PackageSetting ps = mSettings.mPackages.get(packageName);
15152                    if (ps != null) {
15153                        dataOwnerPkg = ps.pkg;
15154                    }
15155                }
15156
15157                if (dataOwnerPkg != null) {
15158                    // If installed, the package will get access to data left on the device by its
15159                    // predecessor. As a security measure, this is permited only if this is not a
15160                    // version downgrade or if the predecessor package is marked as debuggable and
15161                    // a downgrade is explicitly requested.
15162                    //
15163                    // On debuggable platform builds, downgrades are permitted even for
15164                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15165                    // not offer security guarantees and thus it's OK to disable some security
15166                    // mechanisms to make debugging/testing easier on those builds. However, even on
15167                    // debuggable builds downgrades of packages are permitted only if requested via
15168                    // installFlags. This is because we aim to keep the behavior of debuggable
15169                    // platform builds as close as possible to the behavior of non-debuggable
15170                    // platform builds.
15171                    final boolean downgradeRequested =
15172                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15173                    final boolean packageDebuggable =
15174                                (dataOwnerPkg.applicationInfo.flags
15175                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15176                    final boolean downgradePermitted =
15177                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15178                    if (!downgradePermitted) {
15179                        try {
15180                            checkDowngrade(dataOwnerPkg, pkgLite);
15181                        } catch (PackageManagerException e) {
15182                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15183                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15184                        }
15185                    }
15186                }
15187
15188                if (installedPkg != null) {
15189                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15190                        // Check for updated system application.
15191                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15192                            if (onSd) {
15193                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15194                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15195                            }
15196                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15197                        } else {
15198                            if (onSd) {
15199                                // Install flag overrides everything.
15200                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15201                            }
15202                            // If current upgrade specifies particular preference
15203                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15204                                // Application explicitly specified internal.
15205                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15206                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15207                                // App explictly prefers external. Let policy decide
15208                            } else {
15209                                // Prefer previous location
15210                                if (isExternal(installedPkg)) {
15211                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15212                                }
15213                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15214                            }
15215                        }
15216                    } else {
15217                        // Invalid install. Return error code
15218                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15219                    }
15220                }
15221            }
15222            // All the special cases have been taken care of.
15223            // Return result based on recommended install location.
15224            if (onSd) {
15225                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15226            }
15227            return pkgLite.recommendedInstallLocation;
15228        }
15229
15230        /*
15231         * Invoke remote method to get package information and install
15232         * location values. Override install location based on default
15233         * policy if needed and then create install arguments based
15234         * on the install location.
15235         */
15236        public void handleStartCopy() throws RemoteException {
15237            int ret = PackageManager.INSTALL_SUCCEEDED;
15238
15239            // If we're already staged, we've firmly committed to an install location
15240            if (origin.staged) {
15241                if (origin.file != null) {
15242                    installFlags |= PackageManager.INSTALL_INTERNAL;
15243                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15244                } else {
15245                    throw new IllegalStateException("Invalid stage location");
15246                }
15247            }
15248
15249            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15250            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15251            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15252            PackageInfoLite pkgLite = null;
15253
15254            if (onInt && onSd) {
15255                // Check if both bits are set.
15256                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15257                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15258            } else if (onSd && ephemeral) {
15259                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15260                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15261            } else {
15262                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15263                        packageAbiOverride);
15264
15265                if (DEBUG_INSTANT && ephemeral) {
15266                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15267                }
15268
15269                /*
15270                 * If we have too little free space, try to free cache
15271                 * before giving up.
15272                 */
15273                if (!origin.staged && pkgLite.recommendedInstallLocation
15274                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15275                    // TODO: focus freeing disk space on the target device
15276                    final StorageManager storage = StorageManager.from(mContext);
15277                    final long lowThreshold = storage.getStorageLowBytes(
15278                            Environment.getDataDirectory());
15279
15280                    final long sizeBytes = mContainerService.calculateInstalledSize(
15281                            origin.resolvedPath, packageAbiOverride);
15282
15283                    try {
15284                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15285                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15286                                installFlags, packageAbiOverride);
15287                    } catch (InstallerException e) {
15288                        Slog.w(TAG, "Failed to free cache", e);
15289                    }
15290
15291                    /*
15292                     * The cache free must have deleted the file we
15293                     * downloaded to install.
15294                     *
15295                     * TODO: fix the "freeCache" call to not delete
15296                     *       the file we care about.
15297                     */
15298                    if (pkgLite.recommendedInstallLocation
15299                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15300                        pkgLite.recommendedInstallLocation
15301                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15302                    }
15303                }
15304            }
15305
15306            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15307                int loc = pkgLite.recommendedInstallLocation;
15308                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15309                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15310                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15311                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15312                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15313                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15314                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15315                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15316                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15317                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15318                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15319                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15320                } else {
15321                    // Override with defaults if needed.
15322                    loc = installLocationPolicy(pkgLite);
15323                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15324                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15325                    } else if (!onSd && !onInt) {
15326                        // Override install location with flags
15327                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15328                            // Set the flag to install on external media.
15329                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15330                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15331                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15332                            if (DEBUG_INSTANT) {
15333                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15334                            }
15335                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15336                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15337                                    |PackageManager.INSTALL_INTERNAL);
15338                        } else {
15339                            // Make sure the flag for installing on external
15340                            // media is unset
15341                            installFlags |= PackageManager.INSTALL_INTERNAL;
15342                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15343                        }
15344                    }
15345                }
15346            }
15347
15348            final InstallArgs args = createInstallArgs(this);
15349            mArgs = args;
15350
15351            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15352                // TODO: http://b/22976637
15353                // Apps installed for "all" users use the device owner to verify the app
15354                UserHandle verifierUser = getUser();
15355                if (verifierUser == UserHandle.ALL) {
15356                    verifierUser = UserHandle.SYSTEM;
15357                }
15358
15359                /*
15360                 * Determine if we have any installed package verifiers. If we
15361                 * do, then we'll defer to them to verify the packages.
15362                 */
15363                final int requiredUid = mRequiredVerifierPackage == null ? -1
15364                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15365                                verifierUser.getIdentifier());
15366                final int installerUid =
15367                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15368                if (!origin.existing && requiredUid != -1
15369                        && isVerificationEnabled(
15370                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15371                    final Intent verification = new Intent(
15372                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15373                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15374                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15375                            PACKAGE_MIME_TYPE);
15376                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15377
15378                    // Query all live verifiers based on current user state
15379                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15380                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15381                            false /*allowDynamicSplits*/);
15382
15383                    if (DEBUG_VERIFY) {
15384                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15385                                + verification.toString() + " with " + pkgLite.verifiers.length
15386                                + " optional verifiers");
15387                    }
15388
15389                    final int verificationId = mPendingVerificationToken++;
15390
15391                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15392
15393                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15394                            installerPackageName);
15395
15396                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15397                            installFlags);
15398
15399                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15400                            pkgLite.packageName);
15401
15402                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15403                            pkgLite.versionCode);
15404
15405                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15406                            pkgLite.getLongVersionCode());
15407
15408                    if (verificationInfo != null) {
15409                        if (verificationInfo.originatingUri != null) {
15410                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15411                                    verificationInfo.originatingUri);
15412                        }
15413                        if (verificationInfo.referrer != null) {
15414                            verification.putExtra(Intent.EXTRA_REFERRER,
15415                                    verificationInfo.referrer);
15416                        }
15417                        if (verificationInfo.originatingUid >= 0) {
15418                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15419                                    verificationInfo.originatingUid);
15420                        }
15421                        if (verificationInfo.installerUid >= 0) {
15422                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15423                                    verificationInfo.installerUid);
15424                        }
15425                    }
15426
15427                    final PackageVerificationState verificationState = new PackageVerificationState(
15428                            requiredUid, args);
15429
15430                    mPendingVerification.append(verificationId, verificationState);
15431
15432                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15433                            receivers, verificationState);
15434
15435                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15436                    final long idleDuration = getVerificationTimeout();
15437
15438                    /*
15439                     * If any sufficient verifiers were listed in the package
15440                     * manifest, attempt to ask them.
15441                     */
15442                    if (sufficientVerifiers != null) {
15443                        final int N = sufficientVerifiers.size();
15444                        if (N == 0) {
15445                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15446                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15447                        } else {
15448                            for (int i = 0; i < N; i++) {
15449                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15450                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15451                                        verifierComponent.getPackageName(), idleDuration,
15452                                        verifierUser.getIdentifier(), false, "package verifier");
15453
15454                                final Intent sufficientIntent = new Intent(verification);
15455                                sufficientIntent.setComponent(verifierComponent);
15456                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15457                            }
15458                        }
15459                    }
15460
15461                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15462                            mRequiredVerifierPackage, receivers);
15463                    if (ret == PackageManager.INSTALL_SUCCEEDED
15464                            && mRequiredVerifierPackage != null) {
15465                        Trace.asyncTraceBegin(
15466                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15467                        /*
15468                         * Send the intent to the required verification agent,
15469                         * but only start the verification timeout after the
15470                         * target BroadcastReceivers have run.
15471                         */
15472                        verification.setComponent(requiredVerifierComponent);
15473                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15474                                mRequiredVerifierPackage, idleDuration,
15475                                verifierUser.getIdentifier(), false, "package verifier");
15476                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15477                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15478                                new BroadcastReceiver() {
15479                                    @Override
15480                                    public void onReceive(Context context, Intent intent) {
15481                                        final Message msg = mHandler
15482                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15483                                        msg.arg1 = verificationId;
15484                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15485                                    }
15486                                }, null, 0, null, null);
15487
15488                        /*
15489                         * We don't want the copy to proceed until verification
15490                         * succeeds, so null out this field.
15491                         */
15492                        mArgs = null;
15493                    }
15494                } else {
15495                    /*
15496                     * No package verification is enabled, so immediately start
15497                     * the remote call to initiate copy using temporary file.
15498                     */
15499                    ret = args.copyApk(mContainerService, true);
15500                }
15501            }
15502
15503            mRet = ret;
15504        }
15505
15506        @Override
15507        void handleReturnCode() {
15508            // If mArgs is null, then MCS couldn't be reached. When it
15509            // reconnects, it will try again to install. At that point, this
15510            // will succeed.
15511            if (mArgs != null) {
15512                processPendingInstall(mArgs, mRet);
15513            }
15514        }
15515
15516        @Override
15517        void handleServiceError() {
15518            mArgs = createInstallArgs(this);
15519            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15520        }
15521    }
15522
15523    private InstallArgs createInstallArgs(InstallParams params) {
15524        if (params.move != null) {
15525            return new MoveInstallArgs(params);
15526        } else {
15527            return new FileInstallArgs(params);
15528        }
15529    }
15530
15531    /**
15532     * Create args that describe an existing installed package. Typically used
15533     * when cleaning up old installs, or used as a move source.
15534     */
15535    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15536            String resourcePath, String[] instructionSets) {
15537        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15538    }
15539
15540    static abstract class InstallArgs {
15541        /** @see InstallParams#origin */
15542        final OriginInfo origin;
15543        /** @see InstallParams#move */
15544        final MoveInfo move;
15545
15546        final IPackageInstallObserver2 observer;
15547        // Always refers to PackageManager flags only
15548        final int installFlags;
15549        final String installerPackageName;
15550        final String volumeUuid;
15551        final UserHandle user;
15552        final String abiOverride;
15553        final String[] installGrantPermissions;
15554        /** If non-null, drop an async trace when the install completes */
15555        final String traceMethod;
15556        final int traceCookie;
15557        final PackageParser.SigningDetails signingDetails;
15558        final int installReason;
15559
15560        // The list of instruction sets supported by this app. This is currently
15561        // only used during the rmdex() phase to clean up resources. We can get rid of this
15562        // if we move dex files under the common app path.
15563        /* nullable */ String[] instructionSets;
15564
15565        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15566                int installFlags, String installerPackageName, String volumeUuid,
15567                UserHandle user, String[] instructionSets,
15568                String abiOverride, String[] installGrantPermissions,
15569                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15570                int installReason) {
15571            this.origin = origin;
15572            this.move = move;
15573            this.installFlags = installFlags;
15574            this.observer = observer;
15575            this.installerPackageName = installerPackageName;
15576            this.volumeUuid = volumeUuid;
15577            this.user = user;
15578            this.instructionSets = instructionSets;
15579            this.abiOverride = abiOverride;
15580            this.installGrantPermissions = installGrantPermissions;
15581            this.traceMethod = traceMethod;
15582            this.traceCookie = traceCookie;
15583            this.signingDetails = signingDetails;
15584            this.installReason = installReason;
15585        }
15586
15587        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15588        abstract int doPreInstall(int status);
15589
15590        /**
15591         * Rename package into final resting place. All paths on the given
15592         * scanned package should be updated to reflect the rename.
15593         */
15594        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15595        abstract int doPostInstall(int status, int uid);
15596
15597        /** @see PackageSettingBase#codePathString */
15598        abstract String getCodePath();
15599        /** @see PackageSettingBase#resourcePathString */
15600        abstract String getResourcePath();
15601
15602        // Need installer lock especially for dex file removal.
15603        abstract void cleanUpResourcesLI();
15604        abstract boolean doPostDeleteLI(boolean delete);
15605
15606        /**
15607         * Called before the source arguments are copied. This is used mostly
15608         * for MoveParams when it needs to read the source file to put it in the
15609         * destination.
15610         */
15611        int doPreCopy() {
15612            return PackageManager.INSTALL_SUCCEEDED;
15613        }
15614
15615        /**
15616         * Called after the source arguments are copied. This is used mostly for
15617         * MoveParams when it needs to read the source file to put it in the
15618         * destination.
15619         */
15620        int doPostCopy(int uid) {
15621            return PackageManager.INSTALL_SUCCEEDED;
15622        }
15623
15624        protected boolean isFwdLocked() {
15625            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15626        }
15627
15628        protected boolean isExternalAsec() {
15629            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15630        }
15631
15632        protected boolean isEphemeral() {
15633            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15634        }
15635
15636        UserHandle getUser() {
15637            return user;
15638        }
15639    }
15640
15641    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15642        if (!allCodePaths.isEmpty()) {
15643            if (instructionSets == null) {
15644                throw new IllegalStateException("instructionSet == null");
15645            }
15646            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15647            for (String codePath : allCodePaths) {
15648                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15649                    try {
15650                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15651                    } catch (InstallerException ignored) {
15652                    }
15653                }
15654            }
15655        }
15656    }
15657
15658    /**
15659     * Logic to handle installation of non-ASEC applications, including copying
15660     * and renaming logic.
15661     */
15662    class FileInstallArgs extends InstallArgs {
15663        private File codeFile;
15664        private File resourceFile;
15665
15666        // Example topology:
15667        // /data/app/com.example/base.apk
15668        // /data/app/com.example/split_foo.apk
15669        // /data/app/com.example/lib/arm/libfoo.so
15670        // /data/app/com.example/lib/arm64/libfoo.so
15671        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15672
15673        /** New install */
15674        FileInstallArgs(InstallParams params) {
15675            super(params.origin, params.move, params.observer, params.installFlags,
15676                    params.installerPackageName, params.volumeUuid,
15677                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15678                    params.grantedRuntimePermissions,
15679                    params.traceMethod, params.traceCookie, params.signingDetails,
15680                    params.installReason);
15681            if (isFwdLocked()) {
15682                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15683            }
15684        }
15685
15686        /** Existing install */
15687        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15688            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15689                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15690                    PackageManager.INSTALL_REASON_UNKNOWN);
15691            this.codeFile = (codePath != null) ? new File(codePath) : null;
15692            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15693        }
15694
15695        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15696            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15697            try {
15698                return doCopyApk(imcs, temp);
15699            } finally {
15700                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15701            }
15702        }
15703
15704        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15705            if (origin.staged) {
15706                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15707                codeFile = origin.file;
15708                resourceFile = origin.file;
15709                return PackageManager.INSTALL_SUCCEEDED;
15710            }
15711
15712            try {
15713                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15714                final File tempDir =
15715                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15716                codeFile = tempDir;
15717                resourceFile = tempDir;
15718            } catch (IOException e) {
15719                Slog.w(TAG, "Failed to create copy file: " + e);
15720                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15721            }
15722
15723            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15724                @Override
15725                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15726                    if (!FileUtils.isValidExtFilename(name)) {
15727                        throw new IllegalArgumentException("Invalid filename: " + name);
15728                    }
15729                    try {
15730                        final File file = new File(codeFile, name);
15731                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15732                                O_RDWR | O_CREAT, 0644);
15733                        Os.chmod(file.getAbsolutePath(), 0644);
15734                        return new ParcelFileDescriptor(fd);
15735                    } catch (ErrnoException e) {
15736                        throw new RemoteException("Failed to open: " + e.getMessage());
15737                    }
15738                }
15739            };
15740
15741            int ret = PackageManager.INSTALL_SUCCEEDED;
15742            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15743            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15744                Slog.e(TAG, "Failed to copy package");
15745                return ret;
15746            }
15747
15748            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15749            NativeLibraryHelper.Handle handle = null;
15750            try {
15751                handle = NativeLibraryHelper.Handle.create(codeFile);
15752                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15753                        abiOverride);
15754            } catch (IOException e) {
15755                Slog.e(TAG, "Copying native libraries failed", e);
15756                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15757            } finally {
15758                IoUtils.closeQuietly(handle);
15759            }
15760
15761            return ret;
15762        }
15763
15764        int doPreInstall(int status) {
15765            if (status != PackageManager.INSTALL_SUCCEEDED) {
15766                cleanUp();
15767            }
15768            return status;
15769        }
15770
15771        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15772            if (status != PackageManager.INSTALL_SUCCEEDED) {
15773                cleanUp();
15774                return false;
15775            }
15776
15777            final File targetDir = codeFile.getParentFile();
15778            final File beforeCodeFile = codeFile;
15779            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15780
15781            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15782            try {
15783                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15784            } catch (ErrnoException e) {
15785                Slog.w(TAG, "Failed to rename", e);
15786                return false;
15787            }
15788
15789            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15790                Slog.w(TAG, "Failed to restorecon");
15791                return false;
15792            }
15793
15794            // Reflect the rename internally
15795            codeFile = afterCodeFile;
15796            resourceFile = afterCodeFile;
15797
15798            // Reflect the rename in scanned details
15799            try {
15800                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15801            } catch (IOException e) {
15802                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15803                return false;
15804            }
15805            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15806                    afterCodeFile, pkg.baseCodePath));
15807            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15808                    afterCodeFile, pkg.splitCodePaths));
15809
15810            // Reflect the rename in app info
15811            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15812            pkg.setApplicationInfoCodePath(pkg.codePath);
15813            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15814            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15815            pkg.setApplicationInfoResourcePath(pkg.codePath);
15816            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15817            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15818
15819            return true;
15820        }
15821
15822        int doPostInstall(int status, int uid) {
15823            if (status != PackageManager.INSTALL_SUCCEEDED) {
15824                cleanUp();
15825            }
15826            return status;
15827        }
15828
15829        @Override
15830        String getCodePath() {
15831            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15832        }
15833
15834        @Override
15835        String getResourcePath() {
15836            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15837        }
15838
15839        private boolean cleanUp() {
15840            if (codeFile == null || !codeFile.exists()) {
15841                return false;
15842            }
15843
15844            removeCodePathLI(codeFile);
15845
15846            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15847                resourceFile.delete();
15848            }
15849
15850            return true;
15851        }
15852
15853        void cleanUpResourcesLI() {
15854            // Try enumerating all code paths before deleting
15855            List<String> allCodePaths = Collections.EMPTY_LIST;
15856            if (codeFile != null && codeFile.exists()) {
15857                try {
15858                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15859                    allCodePaths = pkg.getAllCodePaths();
15860                } catch (PackageParserException e) {
15861                    // Ignored; we tried our best
15862                }
15863            }
15864
15865            cleanUp();
15866            removeDexFiles(allCodePaths, instructionSets);
15867        }
15868
15869        boolean doPostDeleteLI(boolean delete) {
15870            // XXX err, shouldn't we respect the delete flag?
15871            cleanUpResourcesLI();
15872            return true;
15873        }
15874    }
15875
15876    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15877            PackageManagerException {
15878        if (copyRet < 0) {
15879            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15880                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15881                throw new PackageManagerException(copyRet, message);
15882            }
15883        }
15884    }
15885
15886    /**
15887     * Extract the StorageManagerService "container ID" from the full code path of an
15888     * .apk.
15889     */
15890    static String cidFromCodePath(String fullCodePath) {
15891        int eidx = fullCodePath.lastIndexOf("/");
15892        String subStr1 = fullCodePath.substring(0, eidx);
15893        int sidx = subStr1.lastIndexOf("/");
15894        return subStr1.substring(sidx+1, eidx);
15895    }
15896
15897    /**
15898     * Logic to handle movement of existing installed applications.
15899     */
15900    class MoveInstallArgs extends InstallArgs {
15901        private File codeFile;
15902        private File resourceFile;
15903
15904        /** New install */
15905        MoveInstallArgs(InstallParams params) {
15906            super(params.origin, params.move, params.observer, params.installFlags,
15907                    params.installerPackageName, params.volumeUuid,
15908                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15909                    params.grantedRuntimePermissions,
15910                    params.traceMethod, params.traceCookie, params.signingDetails,
15911                    params.installReason);
15912        }
15913
15914        int copyApk(IMediaContainerService imcs, boolean temp) {
15915            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15916                    + move.fromUuid + " to " + move.toUuid);
15917            synchronized (mInstaller) {
15918                try {
15919                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15920                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15921                } catch (InstallerException e) {
15922                    Slog.w(TAG, "Failed to move app", e);
15923                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15924                }
15925            }
15926
15927            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15928            resourceFile = codeFile;
15929            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15930
15931            return PackageManager.INSTALL_SUCCEEDED;
15932        }
15933
15934        int doPreInstall(int status) {
15935            if (status != PackageManager.INSTALL_SUCCEEDED) {
15936                cleanUp(move.toUuid);
15937            }
15938            return status;
15939        }
15940
15941        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15942            if (status != PackageManager.INSTALL_SUCCEEDED) {
15943                cleanUp(move.toUuid);
15944                return false;
15945            }
15946
15947            // Reflect the move in app info
15948            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15949            pkg.setApplicationInfoCodePath(pkg.codePath);
15950            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15951            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15952            pkg.setApplicationInfoResourcePath(pkg.codePath);
15953            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15954            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15955
15956            return true;
15957        }
15958
15959        int doPostInstall(int status, int uid) {
15960            if (status == PackageManager.INSTALL_SUCCEEDED) {
15961                cleanUp(move.fromUuid);
15962            } else {
15963                cleanUp(move.toUuid);
15964            }
15965            return status;
15966        }
15967
15968        @Override
15969        String getCodePath() {
15970            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15971        }
15972
15973        @Override
15974        String getResourcePath() {
15975            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15976        }
15977
15978        private boolean cleanUp(String volumeUuid) {
15979            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15980                    move.dataAppName);
15981            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15982            final int[] userIds = sUserManager.getUserIds();
15983            synchronized (mInstallLock) {
15984                // Clean up both app data and code
15985                // All package moves are frozen until finished
15986                for (int userId : userIds) {
15987                    try {
15988                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15989                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15990                    } catch (InstallerException e) {
15991                        Slog.w(TAG, String.valueOf(e));
15992                    }
15993                }
15994                removeCodePathLI(codeFile);
15995            }
15996            return true;
15997        }
15998
15999        void cleanUpResourcesLI() {
16000            throw new UnsupportedOperationException();
16001        }
16002
16003        boolean doPostDeleteLI(boolean delete) {
16004            throw new UnsupportedOperationException();
16005        }
16006    }
16007
16008    static String getAsecPackageName(String packageCid) {
16009        int idx = packageCid.lastIndexOf("-");
16010        if (idx == -1) {
16011            return packageCid;
16012        }
16013        return packageCid.substring(0, idx);
16014    }
16015
16016    // Utility method used to create code paths based on package name and available index.
16017    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16018        String idxStr = "";
16019        int idx = 1;
16020        // Fall back to default value of idx=1 if prefix is not
16021        // part of oldCodePath
16022        if (oldCodePath != null) {
16023            String subStr = oldCodePath;
16024            // Drop the suffix right away
16025            if (suffix != null && subStr.endsWith(suffix)) {
16026                subStr = subStr.substring(0, subStr.length() - suffix.length());
16027            }
16028            // If oldCodePath already contains prefix find out the
16029            // ending index to either increment or decrement.
16030            int sidx = subStr.lastIndexOf(prefix);
16031            if (sidx != -1) {
16032                subStr = subStr.substring(sidx + prefix.length());
16033                if (subStr != null) {
16034                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16035                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16036                    }
16037                    try {
16038                        idx = Integer.parseInt(subStr);
16039                        if (idx <= 1) {
16040                            idx++;
16041                        } else {
16042                            idx--;
16043                        }
16044                    } catch(NumberFormatException e) {
16045                    }
16046                }
16047            }
16048        }
16049        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16050        return prefix + idxStr;
16051    }
16052
16053    private File getNextCodePath(File targetDir, String packageName) {
16054        File result;
16055        SecureRandom random = new SecureRandom();
16056        byte[] bytes = new byte[16];
16057        do {
16058            random.nextBytes(bytes);
16059            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16060            result = new File(targetDir, packageName + "-" + suffix);
16061        } while (result.exists());
16062        return result;
16063    }
16064
16065    // Utility method that returns the relative package path with respect
16066    // to the installation directory. Like say for /data/data/com.test-1.apk
16067    // string com.test-1 is returned.
16068    static String deriveCodePathName(String codePath) {
16069        if (codePath == null) {
16070            return null;
16071        }
16072        final File codeFile = new File(codePath);
16073        final String name = codeFile.getName();
16074        if (codeFile.isDirectory()) {
16075            return name;
16076        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16077            final int lastDot = name.lastIndexOf('.');
16078            return name.substring(0, lastDot);
16079        } else {
16080            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16081            return null;
16082        }
16083    }
16084
16085    static class PackageInstalledInfo {
16086        String name;
16087        int uid;
16088        // The set of users that originally had this package installed.
16089        int[] origUsers;
16090        // The set of users that now have this package installed.
16091        int[] newUsers;
16092        PackageParser.Package pkg;
16093        int returnCode;
16094        String returnMsg;
16095        String installerPackageName;
16096        PackageRemovedInfo removedInfo;
16097        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16098
16099        public void setError(int code, String msg) {
16100            setReturnCode(code);
16101            setReturnMessage(msg);
16102            Slog.w(TAG, msg);
16103        }
16104
16105        public void setError(String msg, PackageParserException e) {
16106            setReturnCode(e.error);
16107            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16108            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16109            for (int i = 0; i < childCount; i++) {
16110                addedChildPackages.valueAt(i).setError(msg, e);
16111            }
16112            Slog.w(TAG, msg, e);
16113        }
16114
16115        public void setError(String msg, PackageManagerException e) {
16116            returnCode = e.error;
16117            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16118            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16119            for (int i = 0; i < childCount; i++) {
16120                addedChildPackages.valueAt(i).setError(msg, e);
16121            }
16122            Slog.w(TAG, msg, e);
16123        }
16124
16125        public void setReturnCode(int returnCode) {
16126            this.returnCode = returnCode;
16127            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16128            for (int i = 0; i < childCount; i++) {
16129                addedChildPackages.valueAt(i).returnCode = returnCode;
16130            }
16131        }
16132
16133        private void setReturnMessage(String returnMsg) {
16134            this.returnMsg = returnMsg;
16135            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16136            for (int i = 0; i < childCount; i++) {
16137                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16138            }
16139        }
16140
16141        // In some error cases we want to convey more info back to the observer
16142        String origPackage;
16143        String origPermission;
16144    }
16145
16146    /*
16147     * Install a non-existing package.
16148     */
16149    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16150            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16151            String volumeUuid, PackageInstalledInfo res, int installReason) {
16152        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16153
16154        // Remember this for later, in case we need to rollback this install
16155        String pkgName = pkg.packageName;
16156
16157        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16158
16159        synchronized(mPackages) {
16160            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16161            if (renamedPackage != null) {
16162                // A package with the same name is already installed, though
16163                // it has been renamed to an older name.  The package we
16164                // are trying to install should be installed as an update to
16165                // the existing one, but that has not been requested, so bail.
16166                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16167                        + " without first uninstalling package running as "
16168                        + renamedPackage);
16169                return;
16170            }
16171            if (mPackages.containsKey(pkgName)) {
16172                // Don't allow installation over an existing package with the same name.
16173                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16174                        + " without first uninstalling.");
16175                return;
16176            }
16177        }
16178
16179        try {
16180            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16181                    System.currentTimeMillis(), user);
16182
16183            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16184
16185            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16186                prepareAppDataAfterInstallLIF(newPackage);
16187
16188            } else {
16189                // Remove package from internal structures, but keep around any
16190                // data that might have already existed
16191                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16192                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16193            }
16194        } catch (PackageManagerException e) {
16195            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16196        }
16197
16198        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16199    }
16200
16201    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16202        try (DigestInputStream digestStream =
16203                new DigestInputStream(new FileInputStream(file), digest)) {
16204            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16205        }
16206    }
16207
16208    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16209            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16210            PackageInstalledInfo res, int installReason) {
16211        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16212
16213        final PackageParser.Package oldPackage;
16214        final PackageSetting ps;
16215        final String pkgName = pkg.packageName;
16216        final int[] allUsers;
16217        final int[] installedUsers;
16218
16219        synchronized(mPackages) {
16220            oldPackage = mPackages.get(pkgName);
16221            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16222
16223            // don't allow upgrade to target a release SDK from a pre-release SDK
16224            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16225                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16226            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16227                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16228            if (oldTargetsPreRelease
16229                    && !newTargetsPreRelease
16230                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16231                Slog.w(TAG, "Can't install package targeting released sdk");
16232                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16233                return;
16234            }
16235
16236            ps = mSettings.mPackages.get(pkgName);
16237
16238            // verify signatures are valid
16239            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16240            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16241                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16242                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16243                            "New package not signed by keys specified by upgrade-keysets: "
16244                                    + pkgName);
16245                    return;
16246                }
16247            } else {
16248
16249                // default to original signature matching
16250                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16251                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16252                                && !oldPackage.mSigningDetails.checkCapability(
16253                                        pkg.mSigningDetails,
16254                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16255                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16256                            "New package has a different signature: " + pkgName);
16257                    return;
16258                }
16259            }
16260
16261            // don't allow a system upgrade unless the upgrade hash matches
16262            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16263                byte[] digestBytes = null;
16264                try {
16265                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16266                    updateDigest(digest, new File(pkg.baseCodePath));
16267                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16268                        for (String path : pkg.splitCodePaths) {
16269                            updateDigest(digest, new File(path));
16270                        }
16271                    }
16272                    digestBytes = digest.digest();
16273                } catch (NoSuchAlgorithmException | IOException e) {
16274                    res.setError(INSTALL_FAILED_INVALID_APK,
16275                            "Could not compute hash: " + pkgName);
16276                    return;
16277                }
16278                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16279                    res.setError(INSTALL_FAILED_INVALID_APK,
16280                            "New package fails restrict-update check: " + pkgName);
16281                    return;
16282                }
16283                // retain upgrade restriction
16284                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16285            }
16286
16287            // Check for shared user id changes
16288            String invalidPackageName =
16289                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16290            if (invalidPackageName != null) {
16291                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16292                        "Package " + invalidPackageName + " tried to change user "
16293                                + oldPackage.mSharedUserId);
16294                return;
16295            }
16296
16297            // check if the new package supports all of the abis which the old package supports
16298            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16299            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16300            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16301                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16302                        "Update to package " + pkgName + " doesn't support multi arch");
16303                return;
16304            }
16305
16306            // In case of rollback, remember per-user/profile install state
16307            allUsers = sUserManager.getUserIds();
16308            installedUsers = ps.queryInstalledUsers(allUsers, true);
16309
16310            // don't allow an upgrade from full to ephemeral
16311            if (isInstantApp) {
16312                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16313                    for (int currentUser : allUsers) {
16314                        if (!ps.getInstantApp(currentUser)) {
16315                            // can't downgrade from full to instant
16316                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16317                                    + " for user: " + currentUser);
16318                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16319                            return;
16320                        }
16321                    }
16322                } else if (!ps.getInstantApp(user.getIdentifier())) {
16323                    // can't downgrade from full to instant
16324                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16325                            + " for user: " + user.getIdentifier());
16326                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16327                    return;
16328                }
16329            }
16330        }
16331
16332        // Update what is removed
16333        res.removedInfo = new PackageRemovedInfo(this);
16334        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16335        res.removedInfo.removedPackage = oldPackage.packageName;
16336        res.removedInfo.installerPackageName = ps.installerPackageName;
16337        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16338        res.removedInfo.isUpdate = true;
16339        res.removedInfo.origUsers = installedUsers;
16340        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16341        for (int i = 0; i < installedUsers.length; i++) {
16342            final int userId = installedUsers[i];
16343            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16344        }
16345
16346        final int childCount = (oldPackage.childPackages != null)
16347                ? oldPackage.childPackages.size() : 0;
16348        for (int i = 0; i < childCount; i++) {
16349            boolean childPackageUpdated = false;
16350            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16351            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16352            if (res.addedChildPackages != null) {
16353                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16354                if (childRes != null) {
16355                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16356                    childRes.removedInfo.removedPackage = childPkg.packageName;
16357                    if (childPs != null) {
16358                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16359                    }
16360                    childRes.removedInfo.isUpdate = true;
16361                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16362                    childPackageUpdated = true;
16363                }
16364            }
16365            if (!childPackageUpdated) {
16366                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16367                childRemovedRes.removedPackage = childPkg.packageName;
16368                if (childPs != null) {
16369                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16370                }
16371                childRemovedRes.isUpdate = false;
16372                childRemovedRes.dataRemoved = true;
16373                synchronized (mPackages) {
16374                    if (childPs != null) {
16375                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16376                    }
16377                }
16378                if (res.removedInfo.removedChildPackages == null) {
16379                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16380                }
16381                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16382            }
16383        }
16384
16385        boolean sysPkg = (isSystemApp(oldPackage));
16386        if (sysPkg) {
16387            // Set the system/privileged/oem/vendor/product flags as needed
16388            final boolean privileged =
16389                    (oldPackage.applicationInfo.privateFlags
16390                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16391            final boolean oem =
16392                    (oldPackage.applicationInfo.privateFlags
16393                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16394            final boolean vendor =
16395                    (oldPackage.applicationInfo.privateFlags
16396                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16397            final boolean product =
16398                    (oldPackage.applicationInfo.privateFlags
16399                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16400            final @ParseFlags int systemParseFlags = parseFlags;
16401            final @ScanFlags int systemScanFlags = scanFlags
16402                    | SCAN_AS_SYSTEM
16403                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16404                    | (oem ? SCAN_AS_OEM : 0)
16405                    | (vendor ? SCAN_AS_VENDOR : 0)
16406                    | (product ? SCAN_AS_PRODUCT : 0);
16407
16408            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16409                    user, allUsers, installerPackageName, res, installReason);
16410        } else {
16411            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16412                    user, allUsers, installerPackageName, res, installReason);
16413        }
16414    }
16415
16416    @Override
16417    public List<String> getPreviousCodePaths(String packageName) {
16418        final int callingUid = Binder.getCallingUid();
16419        final List<String> result = new ArrayList<>();
16420        if (getInstantAppPackageName(callingUid) != null) {
16421            return result;
16422        }
16423        final PackageSetting ps = mSettings.mPackages.get(packageName);
16424        if (ps != null
16425                && ps.oldCodePaths != null
16426                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16427            result.addAll(ps.oldCodePaths);
16428        }
16429        return result;
16430    }
16431
16432    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16433            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16434            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16435            String installerPackageName, PackageInstalledInfo res, int installReason) {
16436        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16437                + deletedPackage);
16438
16439        String pkgName = deletedPackage.packageName;
16440        boolean deletedPkg = true;
16441        boolean addedPkg = false;
16442        boolean updatedSettings = false;
16443        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16444        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16445                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16446
16447        final long origUpdateTime = (pkg.mExtras != null)
16448                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16449
16450        // First delete the existing package while retaining the data directory
16451        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16452                res.removedInfo, true, pkg)) {
16453            // If the existing package wasn't successfully deleted
16454            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16455            deletedPkg = false;
16456        } else {
16457            // Successfully deleted the old package; proceed with replace.
16458
16459            // If deleted package lived in a container, give users a chance to
16460            // relinquish resources before killing.
16461            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16462                if (DEBUG_INSTALL) {
16463                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16464                }
16465                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16466                final ArrayList<String> pkgList = new ArrayList<String>(1);
16467                pkgList.add(deletedPackage.applicationInfo.packageName);
16468                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16469            }
16470
16471            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16472                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16473
16474            try {
16475                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16476                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16477                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16478                        installReason);
16479
16480                // Update the in-memory copy of the previous code paths.
16481                PackageSetting ps = mSettings.mPackages.get(pkgName);
16482                if (!killApp) {
16483                    if (ps.oldCodePaths == null) {
16484                        ps.oldCodePaths = new ArraySet<>();
16485                    }
16486                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16487                    if (deletedPackage.splitCodePaths != null) {
16488                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16489                    }
16490                } else {
16491                    ps.oldCodePaths = null;
16492                }
16493                if (ps.childPackageNames != null) {
16494                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16495                        final String childPkgName = ps.childPackageNames.get(i);
16496                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16497                        childPs.oldCodePaths = ps.oldCodePaths;
16498                    }
16499                }
16500                prepareAppDataAfterInstallLIF(newPackage);
16501                addedPkg = true;
16502                mDexManager.notifyPackageUpdated(newPackage.packageName,
16503                        newPackage.baseCodePath, newPackage.splitCodePaths);
16504            } catch (PackageManagerException e) {
16505                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16506            }
16507        }
16508
16509        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16510            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16511
16512            // Revert all internal state mutations and added folders for the failed install
16513            if (addedPkg) {
16514                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16515                        res.removedInfo, true, null);
16516            }
16517
16518            // Restore the old package
16519            if (deletedPkg) {
16520                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16521                File restoreFile = new File(deletedPackage.codePath);
16522                // Parse old package
16523                boolean oldExternal = isExternal(deletedPackage);
16524                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16525                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16526                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16527                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16528                try {
16529                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16530                            null);
16531                } catch (PackageManagerException e) {
16532                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16533                            + e.getMessage());
16534                    return;
16535                }
16536
16537                synchronized (mPackages) {
16538                    // Ensure the installer package name up to date
16539                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16540
16541                    // Update permissions for restored package
16542                    mPermissionManager.updatePermissions(
16543                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16544                            mPermissionCallback);
16545
16546                    mSettings.writeLPr();
16547                }
16548
16549                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16550            }
16551        } else {
16552            synchronized (mPackages) {
16553                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16554                if (ps != null) {
16555                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16556                    if (res.removedInfo.removedChildPackages != null) {
16557                        final int childCount = res.removedInfo.removedChildPackages.size();
16558                        // Iterate in reverse as we may modify the collection
16559                        for (int i = childCount - 1; i >= 0; i--) {
16560                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16561                            if (res.addedChildPackages.containsKey(childPackageName)) {
16562                                res.removedInfo.removedChildPackages.removeAt(i);
16563                            } else {
16564                                PackageRemovedInfo childInfo = res.removedInfo
16565                                        .removedChildPackages.valueAt(i);
16566                                childInfo.removedForAllUsers = mPackages.get(
16567                                        childInfo.removedPackage) == null;
16568                            }
16569                        }
16570                    }
16571                }
16572            }
16573        }
16574    }
16575
16576    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16577            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16578            final @ScanFlags int scanFlags, UserHandle user,
16579            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16580            int installReason) {
16581        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16582                + ", old=" + deletedPackage);
16583
16584        final boolean disabledSystem;
16585
16586        // Remove existing system package
16587        removePackageLI(deletedPackage, true);
16588
16589        synchronized (mPackages) {
16590            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16591        }
16592        if (!disabledSystem) {
16593            // We didn't need to disable the .apk as a current system package,
16594            // which means we are replacing another update that is already
16595            // installed.  We need to make sure to delete the older one's .apk.
16596            res.removedInfo.args = createInstallArgsForExisting(0,
16597                    deletedPackage.applicationInfo.getCodePath(),
16598                    deletedPackage.applicationInfo.getResourcePath(),
16599                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16600        } else {
16601            res.removedInfo.args = null;
16602        }
16603
16604        // Successfully disabled the old package. Now proceed with re-installation
16605        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16606                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16607
16608        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16609        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16610                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16611
16612        PackageParser.Package newPackage = null;
16613        try {
16614            // Add the package to the internal data structures
16615            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16616
16617            // Set the update and install times
16618            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16619            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16620                    System.currentTimeMillis());
16621
16622            // Update the package dynamic state if succeeded
16623            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16624                // Now that the install succeeded make sure we remove data
16625                // directories for any child package the update removed.
16626                final int deletedChildCount = (deletedPackage.childPackages != null)
16627                        ? deletedPackage.childPackages.size() : 0;
16628                final int newChildCount = (newPackage.childPackages != null)
16629                        ? newPackage.childPackages.size() : 0;
16630                for (int i = 0; i < deletedChildCount; i++) {
16631                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16632                    boolean childPackageDeleted = true;
16633                    for (int j = 0; j < newChildCount; j++) {
16634                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16635                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16636                            childPackageDeleted = false;
16637                            break;
16638                        }
16639                    }
16640                    if (childPackageDeleted) {
16641                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16642                                deletedChildPkg.packageName);
16643                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16644                            PackageRemovedInfo removedChildRes = res.removedInfo
16645                                    .removedChildPackages.get(deletedChildPkg.packageName);
16646                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16647                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16648                        }
16649                    }
16650                }
16651
16652                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16653                        installReason);
16654                prepareAppDataAfterInstallLIF(newPackage);
16655
16656                mDexManager.notifyPackageUpdated(newPackage.packageName,
16657                            newPackage.baseCodePath, newPackage.splitCodePaths);
16658            }
16659        } catch (PackageManagerException e) {
16660            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16661            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16662        }
16663
16664        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16665            // Re installation failed. Restore old information
16666            // Remove new pkg information
16667            if (newPackage != null) {
16668                removeInstalledPackageLI(newPackage, true);
16669            }
16670            // Add back the old system package
16671            try {
16672                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16673            } catch (PackageManagerException e) {
16674                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16675            }
16676
16677            synchronized (mPackages) {
16678                if (disabledSystem) {
16679                    enableSystemPackageLPw(deletedPackage);
16680                }
16681
16682                // Ensure the installer package name up to date
16683                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16684
16685                // Update permissions for restored package
16686                mPermissionManager.updatePermissions(
16687                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16688                        mPermissionCallback);
16689
16690                mSettings.writeLPr();
16691            }
16692
16693            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16694                    + " after failed upgrade");
16695        }
16696    }
16697
16698    /**
16699     * Checks whether the parent or any of the child packages have a change shared
16700     * user. For a package to be a valid update the shred users of the parent and
16701     * the children should match. We may later support changing child shared users.
16702     * @param oldPkg The updated package.
16703     * @param newPkg The update package.
16704     * @return The shared user that change between the versions.
16705     */
16706    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16707            PackageParser.Package newPkg) {
16708        // Check parent shared user
16709        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16710            return newPkg.packageName;
16711        }
16712        // Check child shared users
16713        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16714        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16715        for (int i = 0; i < newChildCount; i++) {
16716            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16717            // If this child was present, did it have the same shared user?
16718            for (int j = 0; j < oldChildCount; j++) {
16719                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16720                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16721                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16722                    return newChildPkg.packageName;
16723                }
16724            }
16725        }
16726        return null;
16727    }
16728
16729    private void removeNativeBinariesLI(PackageSetting ps) {
16730        // Remove the lib path for the parent package
16731        if (ps != null) {
16732            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16733            // Remove the lib path for the child packages
16734            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16735            for (int i = 0; i < childCount; i++) {
16736                PackageSetting childPs = null;
16737                synchronized (mPackages) {
16738                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16739                }
16740                if (childPs != null) {
16741                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16742                            .legacyNativeLibraryPathString);
16743                }
16744            }
16745        }
16746    }
16747
16748    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16749        // Enable the parent package
16750        mSettings.enableSystemPackageLPw(pkg.packageName);
16751        // Enable the child packages
16752        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16753        for (int i = 0; i < childCount; i++) {
16754            PackageParser.Package childPkg = pkg.childPackages.get(i);
16755            mSettings.enableSystemPackageLPw(childPkg.packageName);
16756        }
16757    }
16758
16759    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16760            PackageParser.Package newPkg) {
16761        // Disable the parent package (parent always replaced)
16762        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16763        // Disable the child packages
16764        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16765        for (int i = 0; i < childCount; i++) {
16766            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16767            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16768            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16769        }
16770        return disabled;
16771    }
16772
16773    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16774            String installerPackageName) {
16775        // Enable the parent package
16776        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16777        // Enable the child packages
16778        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16779        for (int i = 0; i < childCount; i++) {
16780            PackageParser.Package childPkg = pkg.childPackages.get(i);
16781            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16782        }
16783    }
16784
16785    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16786            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16787        // Update the parent package setting
16788        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16789                res, user, installReason);
16790        // Update the child packages setting
16791        final int childCount = (newPackage.childPackages != null)
16792                ? newPackage.childPackages.size() : 0;
16793        for (int i = 0; i < childCount; i++) {
16794            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16795            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16796            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16797                    childRes.origUsers, childRes, user, installReason);
16798        }
16799    }
16800
16801    private void updateSettingsInternalLI(PackageParser.Package pkg,
16802            String installerPackageName, int[] allUsers, int[] installedForUsers,
16803            PackageInstalledInfo res, UserHandle user, int installReason) {
16804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16805
16806        final String pkgName = pkg.packageName;
16807
16808        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16809        synchronized (mPackages) {
16810// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16811            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16812                    mPermissionCallback);
16813            // For system-bundled packages, we assume that installing an upgraded version
16814            // of the package implies that the user actually wants to run that new code,
16815            // so we enable the package.
16816            PackageSetting ps = mSettings.mPackages.get(pkgName);
16817            final int userId = user.getIdentifier();
16818            if (ps != null) {
16819                if (isSystemApp(pkg)) {
16820                    if (DEBUG_INSTALL) {
16821                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16822                    }
16823                    // Enable system package for requested users
16824                    if (res.origUsers != null) {
16825                        for (int origUserId : res.origUsers) {
16826                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16827                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16828                                        origUserId, installerPackageName);
16829                            }
16830                        }
16831                    }
16832                    // Also convey the prior install/uninstall state
16833                    if (allUsers != null && installedForUsers != null) {
16834                        for (int currentUserId : allUsers) {
16835                            final boolean installed = ArrayUtils.contains(
16836                                    installedForUsers, currentUserId);
16837                            if (DEBUG_INSTALL) {
16838                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16839                            }
16840                            ps.setInstalled(installed, currentUserId);
16841                        }
16842                        // these install state changes will be persisted in the
16843                        // upcoming call to mSettings.writeLPr().
16844                    }
16845                }
16846                // It's implied that when a user requests installation, they want the app to be
16847                // installed and enabled.
16848                if (userId != UserHandle.USER_ALL) {
16849                    ps.setInstalled(true, userId);
16850                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16851                }
16852
16853                // When replacing an existing package, preserve the original install reason for all
16854                // users that had the package installed before.
16855                final Set<Integer> previousUserIds = new ArraySet<>();
16856                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16857                    final int installReasonCount = res.removedInfo.installReasons.size();
16858                    for (int i = 0; i < installReasonCount; i++) {
16859                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16860                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16861                        ps.setInstallReason(previousInstallReason, previousUserId);
16862                        previousUserIds.add(previousUserId);
16863                    }
16864                }
16865
16866                // Set install reason for users that are having the package newly installed.
16867                if (userId == UserHandle.USER_ALL) {
16868                    for (int currentUserId : sUserManager.getUserIds()) {
16869                        if (!previousUserIds.contains(currentUserId)) {
16870                            ps.setInstallReason(installReason, currentUserId);
16871                        }
16872                    }
16873                } else if (!previousUserIds.contains(userId)) {
16874                    ps.setInstallReason(installReason, userId);
16875                }
16876                mSettings.writeKernelMappingLPr(ps);
16877            }
16878            res.name = pkgName;
16879            res.uid = pkg.applicationInfo.uid;
16880            res.pkg = pkg;
16881            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16882            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16883            //to update install status
16884            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16885            mSettings.writeLPr();
16886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16887        }
16888
16889        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16890    }
16891
16892    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16893        try {
16894            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16895            installPackageLI(args, res);
16896        } finally {
16897            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16898        }
16899    }
16900
16901    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16902        final int installFlags = args.installFlags;
16903        final String installerPackageName = args.installerPackageName;
16904        final String volumeUuid = args.volumeUuid;
16905        final File tmpPackageFile = new File(args.getCodePath());
16906        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16907        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16908                || (args.volumeUuid != null));
16909        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16910        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16911        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16912        final boolean virtualPreload =
16913                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16914        boolean replace = false;
16915        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16916        if (args.move != null) {
16917            // moving a complete application; perform an initial scan on the new install location
16918            scanFlags |= SCAN_INITIAL;
16919        }
16920        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16921            scanFlags |= SCAN_DONT_KILL_APP;
16922        }
16923        if (instantApp) {
16924            scanFlags |= SCAN_AS_INSTANT_APP;
16925        }
16926        if (fullApp) {
16927            scanFlags |= SCAN_AS_FULL_APP;
16928        }
16929        if (virtualPreload) {
16930            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16931        }
16932
16933        // Result object to be returned
16934        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16935        res.installerPackageName = installerPackageName;
16936
16937        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16938
16939        // Sanity check
16940        if (instantApp && (forwardLocked || onExternal)) {
16941            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16942                    + " external=" + onExternal);
16943            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16944            return;
16945        }
16946
16947        // Retrieve PackageSettings and parse package
16948        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16949                | PackageParser.PARSE_ENFORCE_CODE
16950                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16951                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16952                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16953        PackageParser pp = new PackageParser();
16954        pp.setSeparateProcesses(mSeparateProcesses);
16955        pp.setDisplayMetrics(mMetrics);
16956        pp.setCallback(mPackageParserCallback);
16957
16958        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16959        final PackageParser.Package pkg;
16960        try {
16961            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16962            DexMetadataHelper.validatePackageDexMetadata(pkg);
16963        } catch (PackageParserException e) {
16964            res.setError("Failed parse during installPackageLI", e);
16965            return;
16966        } finally {
16967            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16968        }
16969
16970        // Instant apps have several additional install-time checks.
16971        if (instantApp) {
16972            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16973                Slog.w(TAG,
16974                        "Instant app package " + pkg.packageName + " does not target at least O");
16975                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16976                        "Instant app package must target at least O");
16977                return;
16978            }
16979            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16980                Slog.w(TAG, "Instant app package " + pkg.packageName
16981                        + " does not target targetSandboxVersion 2");
16982                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16983                        "Instant app package must use targetSandboxVersion 2");
16984                return;
16985            }
16986            if (pkg.mSharedUserId != null) {
16987                Slog.w(TAG, "Instant app package " + pkg.packageName
16988                        + " may not declare sharedUserId.");
16989                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16990                        "Instant app package may not declare a sharedUserId");
16991                return;
16992            }
16993        }
16994
16995        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16996            // Static shared libraries have synthetic package names
16997            renameStaticSharedLibraryPackage(pkg);
16998
16999            // No static shared libs on external storage
17000            if (onExternal) {
17001                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17002                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17003                        "Packages declaring static-shared libs cannot be updated");
17004                return;
17005            }
17006        }
17007
17008        // If we are installing a clustered package add results for the children
17009        if (pkg.childPackages != null) {
17010            synchronized (mPackages) {
17011                final int childCount = pkg.childPackages.size();
17012                for (int i = 0; i < childCount; i++) {
17013                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17014                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17015                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17016                    childRes.pkg = childPkg;
17017                    childRes.name = childPkg.packageName;
17018                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17019                    if (childPs != null) {
17020                        childRes.origUsers = childPs.queryInstalledUsers(
17021                                sUserManager.getUserIds(), true);
17022                    }
17023                    if ((mPackages.containsKey(childPkg.packageName))) {
17024                        childRes.removedInfo = new PackageRemovedInfo(this);
17025                        childRes.removedInfo.removedPackage = childPkg.packageName;
17026                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17027                    }
17028                    if (res.addedChildPackages == null) {
17029                        res.addedChildPackages = new ArrayMap<>();
17030                    }
17031                    res.addedChildPackages.put(childPkg.packageName, childRes);
17032                }
17033            }
17034        }
17035
17036        // If package doesn't declare API override, mark that we have an install
17037        // time CPU ABI override.
17038        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17039            pkg.cpuAbiOverride = args.abiOverride;
17040        }
17041
17042        String pkgName = res.name = pkg.packageName;
17043        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17044            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17045                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17046                return;
17047            }
17048        }
17049
17050        try {
17051            // either use what we've been given or parse directly from the APK
17052            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17053                pkg.setSigningDetails(args.signingDetails);
17054            } else {
17055                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17056            }
17057        } catch (PackageParserException e) {
17058            res.setError("Failed collect during installPackageLI", e);
17059            return;
17060        }
17061
17062        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17063                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17064            Slog.w(TAG, "Instant app package " + pkg.packageName
17065                    + " is not signed with at least APK Signature Scheme v2");
17066            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17067                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17068            return;
17069        }
17070
17071        // Get rid of all references to package scan path via parser.
17072        pp = null;
17073        String oldCodePath = null;
17074        boolean systemApp = false;
17075        synchronized (mPackages) {
17076            // Check if installing already existing package
17077            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17078                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17079                if (pkg.mOriginalPackages != null
17080                        && pkg.mOriginalPackages.contains(oldName)
17081                        && mPackages.containsKey(oldName)) {
17082                    // This package is derived from an original package,
17083                    // and this device has been updating from that original
17084                    // name.  We must continue using the original name, so
17085                    // rename the new package here.
17086                    pkg.setPackageName(oldName);
17087                    pkgName = pkg.packageName;
17088                    replace = true;
17089                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17090                            + oldName + " pkgName=" + pkgName);
17091                } else if (mPackages.containsKey(pkgName)) {
17092                    // This package, under its official name, already exists
17093                    // on the device; we should replace it.
17094                    replace = true;
17095                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17096                }
17097
17098                // Child packages are installed through the parent package
17099                if (pkg.parentPackage != null) {
17100                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17101                            "Package " + pkg.packageName + " is child of package "
17102                                    + pkg.parentPackage.parentPackage + ". Child packages "
17103                                    + "can be updated only through the parent package.");
17104                    return;
17105                }
17106
17107                if (replace) {
17108                    // Prevent apps opting out from runtime permissions
17109                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17110                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17111                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17112                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17113                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17114                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17115                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17116                                        + " doesn't support runtime permissions but the old"
17117                                        + " target SDK " + oldTargetSdk + " does.");
17118                        return;
17119                    }
17120                    // Prevent persistent apps from being updated
17121                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17122                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17123                                "Package " + oldPackage.packageName + " is a persistent app. "
17124                                        + "Persistent apps are not updateable.");
17125                        return;
17126                    }
17127                    // Prevent apps from downgrading their targetSandbox.
17128                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17129                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17130                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17131                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17132                                "Package " + pkg.packageName + " new target sandbox "
17133                                + newTargetSandbox + " is incompatible with the previous value of"
17134                                + oldTargetSandbox + ".");
17135                        return;
17136                    }
17137
17138                    // Prevent installing of child packages
17139                    if (oldPackage.parentPackage != null) {
17140                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17141                                "Package " + pkg.packageName + " is child of package "
17142                                        + oldPackage.parentPackage + ". Child packages "
17143                                        + "can be updated only through the parent package.");
17144                        return;
17145                    }
17146                }
17147            }
17148
17149            PackageSetting ps = mSettings.mPackages.get(pkgName);
17150            if (ps != null) {
17151                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17152
17153                // Static shared libs have same package with different versions where
17154                // we internally use a synthetic package name to allow multiple versions
17155                // of the same package, therefore we need to compare signatures against
17156                // the package setting for the latest library version.
17157                PackageSetting signatureCheckPs = ps;
17158                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17159                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17160                    if (libraryEntry != null) {
17161                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17162                    }
17163                }
17164
17165                // Quick sanity check that we're signed correctly if updating;
17166                // we'll check this again later when scanning, but we want to
17167                // bail early here before tripping over redefined permissions.
17168                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17169                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17170                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17171                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17172                                + pkg.packageName + " upgrade keys do not match the "
17173                                + "previously installed version");
17174                        return;
17175                    }
17176                } else {
17177                    try {
17178                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17179                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17180                        // We don't care about disabledPkgSetting on install for now.
17181                        final boolean compatMatch = verifySignatures(
17182                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17183                                compareRecover);
17184                        // The new KeySets will be re-added later in the scanning process.
17185                        if (compatMatch) {
17186                            synchronized (mPackages) {
17187                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17188                            }
17189                        }
17190                    } catch (PackageManagerException e) {
17191                        res.setError(e.error, e.getMessage());
17192                        return;
17193                    }
17194                }
17195
17196                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17197                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17198                    systemApp = (ps.pkg.applicationInfo.flags &
17199                            ApplicationInfo.FLAG_SYSTEM) != 0;
17200                }
17201                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17202            }
17203
17204            int N = pkg.permissions.size();
17205            for (int i = N-1; i >= 0; i--) {
17206                final PackageParser.Permission perm = pkg.permissions.get(i);
17207                final BasePermission bp =
17208                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17209
17210                // Don't allow anyone but the system to define ephemeral permissions.
17211                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17212                        && !systemApp) {
17213                    Slog.w(TAG, "Non-System package " + pkg.packageName
17214                            + " attempting to delcare ephemeral permission "
17215                            + perm.info.name + "; Removing ephemeral.");
17216                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17217                }
17218
17219                // Check whether the newly-scanned package wants to define an already-defined perm
17220                if (bp != null) {
17221                    // If the defining package is signed with our cert, it's okay.  This
17222                    // also includes the "updating the same package" case, of course.
17223                    // "updating same package" could also involve key-rotation.
17224                    final boolean sigsOk;
17225                    final String sourcePackageName = bp.getSourcePackageName();
17226                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17227                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17228                    if (sourcePackageName.equals(pkg.packageName)
17229                            && (ksms.shouldCheckUpgradeKeySetLocked(
17230                                    sourcePackageSetting, scanFlags))) {
17231                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17232                    } else {
17233
17234                        // in the event of signing certificate rotation, we need to see if the
17235                        // package's certificate has rotated from the current one, or if it is an
17236                        // older certificate with which the current is ok with sharing permissions
17237                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17238                                        pkg.mSigningDetails,
17239                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17240                            sigsOk = true;
17241                        } else if (pkg.mSigningDetails.checkCapability(
17242                                        sourcePackageSetting.signatures.mSigningDetails,
17243                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17244
17245                            // the scanned package checks out, has signing certificate rotation
17246                            // history, and is newer; bring it over
17247                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17248                            sigsOk = true;
17249                        } else {
17250                            sigsOk = false;
17251                        }
17252                    }
17253                    if (!sigsOk) {
17254                        // If the owning package is the system itself, we log but allow
17255                        // install to proceed; we fail the install on all other permission
17256                        // redefinitions.
17257                        if (!sourcePackageName.equals("android")) {
17258                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17259                                    + pkg.packageName + " attempting to redeclare permission "
17260                                    + perm.info.name + " already owned by " + sourcePackageName);
17261                            res.origPermission = perm.info.name;
17262                            res.origPackage = sourcePackageName;
17263                            return;
17264                        } else {
17265                            Slog.w(TAG, "Package " + pkg.packageName
17266                                    + " attempting to redeclare system permission "
17267                                    + perm.info.name + "; ignoring new declaration");
17268                            pkg.permissions.remove(i);
17269                        }
17270                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17271                        // Prevent apps to change protection level to dangerous from any other
17272                        // type as this would allow a privilege escalation where an app adds a
17273                        // normal/signature permission in other app's group and later redefines
17274                        // it as dangerous leading to the group auto-grant.
17275                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17276                                == PermissionInfo.PROTECTION_DANGEROUS) {
17277                            if (bp != null && !bp.isRuntime()) {
17278                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17279                                        + "non-runtime permission " + perm.info.name
17280                                        + " to runtime; keeping old protection level");
17281                                perm.info.protectionLevel = bp.getProtectionLevel();
17282                            }
17283                        }
17284                    }
17285                }
17286            }
17287        }
17288
17289        if (systemApp) {
17290            if (onExternal) {
17291                // Abort update; system app can't be replaced with app on sdcard
17292                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17293                        "Cannot install updates to system apps on sdcard");
17294                return;
17295            } else if (instantApp) {
17296                // Abort update; system app can't be replaced with an instant app
17297                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17298                        "Cannot update a system app with an instant app");
17299                return;
17300            }
17301        }
17302
17303        if (args.move != null) {
17304            // We did an in-place move, so dex is ready to roll
17305            scanFlags |= SCAN_NO_DEX;
17306            scanFlags |= SCAN_MOVE;
17307
17308            synchronized (mPackages) {
17309                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17310                if (ps == null) {
17311                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17312                            "Missing settings for moved package " + pkgName);
17313                }
17314
17315                // We moved the entire application as-is, so bring over the
17316                // previously derived ABI information.
17317                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17318                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17319            }
17320
17321        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17322            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17323            scanFlags |= SCAN_NO_DEX;
17324
17325            try {
17326                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17327                    args.abiOverride : pkg.cpuAbiOverride);
17328                final boolean extractNativeLibs = !pkg.isLibrary();
17329                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17330            } catch (PackageManagerException pme) {
17331                Slog.e(TAG, "Error deriving application ABI", pme);
17332                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17333                return;
17334            }
17335
17336            // Shared libraries for the package need to be updated.
17337            synchronized (mPackages) {
17338                try {
17339                    updateSharedLibrariesLPr(pkg, null);
17340                } catch (PackageManagerException e) {
17341                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17342                }
17343            }
17344        }
17345
17346        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17347            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17348            return;
17349        }
17350
17351        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17352            String apkPath = null;
17353            synchronized (mPackages) {
17354                // Note that if the attacker managed to skip verify setup, for example by tampering
17355                // with the package settings, upon reboot we will do full apk verification when
17356                // verity is not detected.
17357                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17358                if (ps != null && ps.isPrivileged()) {
17359                    apkPath = pkg.baseCodePath;
17360                }
17361            }
17362
17363            if (apkPath != null) {
17364                final VerityUtils.SetupResult result =
17365                        VerityUtils.generateApkVeritySetupData(apkPath);
17366                if (result.isOk()) {
17367                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17368                    FileDescriptor fd = result.getUnownedFileDescriptor();
17369                    try {
17370                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17371                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17372                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17373                    } catch (InstallerException | IOException | DigestException |
17374                             NoSuchAlgorithmException e) {
17375                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17376                                "Failed to set up verity: " + e);
17377                        return;
17378                    } finally {
17379                        IoUtils.closeQuietly(fd);
17380                    }
17381                } else if (result.isFailed()) {
17382                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17383                    return;
17384                } else {
17385                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17386                    // reboot.
17387                }
17388            }
17389        }
17390
17391        if (!instantApp) {
17392            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17393        } else {
17394            if (DEBUG_DOMAIN_VERIFICATION) {
17395                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17396            }
17397        }
17398
17399        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17400                "installPackageLI")) {
17401            if (replace) {
17402                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17403                    // Static libs have a synthetic package name containing the version
17404                    // and cannot be updated as an update would get a new package name,
17405                    // unless this is the exact same version code which is useful for
17406                    // development.
17407                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17408                    if (existingPkg != null &&
17409                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17410                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17411                                + "static-shared libs cannot be updated");
17412                        return;
17413                    }
17414                }
17415                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17416                        installerPackageName, res, args.installReason);
17417            } else {
17418                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17419                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17420            }
17421        }
17422
17423        // Prepare the application profiles for the new code paths.
17424        // This needs to be done before invoking dexopt so that any install-time profile
17425        // can be used for optimizations.
17426        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17427
17428        // Check whether we need to dexopt the app.
17429        //
17430        // NOTE: it is IMPORTANT to call dexopt:
17431        //   - after doRename which will sync the package data from PackageParser.Package and its
17432        //     corresponding ApplicationInfo.
17433        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17434        //     uid of the application (pkg.applicationInfo.uid).
17435        //     This update happens in place!
17436        //
17437        // We only need to dexopt if the package meets ALL of the following conditions:
17438        //   1) it is not forward locked.
17439        //   2) it is not on on an external ASEC container.
17440        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17441        //   4) it is not debuggable.
17442        //
17443        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17444        // complete, so we skip this step during installation. Instead, we'll take extra time
17445        // the first time the instant app starts. It's preferred to do it this way to provide
17446        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17447        // middle of running an instant app. The default behaviour can be overridden
17448        // via gservices.
17449        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17450                && !forwardLocked
17451                && !pkg.applicationInfo.isExternalAsec()
17452                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17453                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17454                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17455
17456        if (performDexopt) {
17457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17458            // Do not run PackageDexOptimizer through the local performDexOpt
17459            // method because `pkg` may not be in `mPackages` yet.
17460            //
17461            // Also, don't fail application installs if the dexopt step fails.
17462            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17463                    REASON_INSTALL,
17464                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17465                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17466            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17467                    null /* instructionSets */,
17468                    getOrCreateCompilerPackageStats(pkg),
17469                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17470                    dexoptOptions);
17471            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17472        }
17473
17474        // Notify BackgroundDexOptService that the package has been changed.
17475        // If this is an update of a package which used to fail to compile,
17476        // BackgroundDexOptService will remove it from its blacklist.
17477        // TODO: Layering violation
17478        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17479
17480        synchronized (mPackages) {
17481            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17482            if (ps != null) {
17483                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17484                ps.setUpdateAvailable(false /*updateAvailable*/);
17485            }
17486
17487            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17488            for (int i = 0; i < childCount; i++) {
17489                PackageParser.Package childPkg = pkg.childPackages.get(i);
17490                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17491                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17492                if (childPs != null) {
17493                    childRes.newUsers = childPs.queryInstalledUsers(
17494                            sUserManager.getUserIds(), true);
17495                }
17496            }
17497
17498            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17499                updateSequenceNumberLP(ps, res.newUsers);
17500                updateInstantAppInstallerLocked(pkgName);
17501            }
17502        }
17503    }
17504
17505    private void startIntentFilterVerifications(int userId, boolean replacing,
17506            PackageParser.Package pkg) {
17507        if (mIntentFilterVerifierComponent == null) {
17508            Slog.w(TAG, "No IntentFilter verification will not be done as "
17509                    + "there is no IntentFilterVerifier available!");
17510            return;
17511        }
17512
17513        final int verifierUid = getPackageUid(
17514                mIntentFilterVerifierComponent.getPackageName(),
17515                MATCH_DEBUG_TRIAGED_MISSING,
17516                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17517
17518        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17519        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17520        mHandler.sendMessage(msg);
17521
17522        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17523        for (int i = 0; i < childCount; i++) {
17524            PackageParser.Package childPkg = pkg.childPackages.get(i);
17525            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17526            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17527            mHandler.sendMessage(msg);
17528        }
17529    }
17530
17531    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17532            PackageParser.Package pkg) {
17533        int size = pkg.activities.size();
17534        if (size == 0) {
17535            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17536                    "No activity, so no need to verify any IntentFilter!");
17537            return;
17538        }
17539
17540        final boolean hasDomainURLs = hasDomainURLs(pkg);
17541        if (!hasDomainURLs) {
17542            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17543                    "No domain URLs, so no need to verify any IntentFilter!");
17544            return;
17545        }
17546
17547        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17548                + " if any IntentFilter from the " + size
17549                + " Activities needs verification ...");
17550
17551        int count = 0;
17552        final String packageName = pkg.packageName;
17553
17554        synchronized (mPackages) {
17555            // If this is a new install and we see that we've already run verification for this
17556            // package, we have nothing to do: it means the state was restored from backup.
17557            if (!replacing) {
17558                IntentFilterVerificationInfo ivi =
17559                        mSettings.getIntentFilterVerificationLPr(packageName);
17560                if (ivi != null) {
17561                    if (DEBUG_DOMAIN_VERIFICATION) {
17562                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17563                                + ivi.getStatusString());
17564                    }
17565                    return;
17566                }
17567            }
17568
17569            // If any filters need to be verified, then all need to be.
17570            boolean needToVerify = false;
17571            for (PackageParser.Activity a : pkg.activities) {
17572                for (ActivityIntentInfo filter : a.intents) {
17573                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17574                        if (DEBUG_DOMAIN_VERIFICATION) {
17575                            Slog.d(TAG,
17576                                    "Intent filter needs verification, so processing all filters");
17577                        }
17578                        needToVerify = true;
17579                        break;
17580                    }
17581                }
17582            }
17583
17584            if (needToVerify) {
17585                final int verificationId = mIntentFilterVerificationToken++;
17586                for (PackageParser.Activity a : pkg.activities) {
17587                    for (ActivityIntentInfo filter : a.intents) {
17588                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17589                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17590                                    "Verification needed for IntentFilter:" + filter.toString());
17591                            mIntentFilterVerifier.addOneIntentFilterVerification(
17592                                    verifierUid, userId, verificationId, filter, packageName);
17593                            count++;
17594                        }
17595                    }
17596                }
17597            }
17598        }
17599
17600        if (count > 0) {
17601            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17602                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17603                    +  " for userId:" + userId);
17604            mIntentFilterVerifier.startVerifications(userId);
17605        } else {
17606            if (DEBUG_DOMAIN_VERIFICATION) {
17607                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17608            }
17609        }
17610    }
17611
17612    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17613        final ComponentName cn  = filter.activity.getComponentName();
17614        final String packageName = cn.getPackageName();
17615
17616        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17617                packageName);
17618        if (ivi == null) {
17619            return true;
17620        }
17621        int status = ivi.getStatus();
17622        switch (status) {
17623            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17624            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17625                return true;
17626
17627            default:
17628                // Nothing to do
17629                return false;
17630        }
17631    }
17632
17633    private static boolean isMultiArch(ApplicationInfo info) {
17634        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17635    }
17636
17637    private static boolean isExternal(PackageParser.Package pkg) {
17638        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17639    }
17640
17641    private static boolean isExternal(PackageSetting ps) {
17642        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17643    }
17644
17645    private static boolean isSystemApp(PackageParser.Package pkg) {
17646        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17647    }
17648
17649    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17650        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17651    }
17652
17653    private static boolean isOemApp(PackageParser.Package pkg) {
17654        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17655    }
17656
17657    private static boolean isVendorApp(PackageParser.Package pkg) {
17658        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17659    }
17660
17661    private static boolean isProductApp(PackageParser.Package pkg) {
17662        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17663    }
17664
17665    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17666        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17667    }
17668
17669    private static boolean isSystemApp(PackageSetting ps) {
17670        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17671    }
17672
17673    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17674        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17675    }
17676
17677    private int packageFlagsToInstallFlags(PackageSetting ps) {
17678        int installFlags = 0;
17679        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17680            // This existing package was an external ASEC install when we have
17681            // the external flag without a UUID
17682            installFlags |= PackageManager.INSTALL_EXTERNAL;
17683        }
17684        if (ps.isForwardLocked()) {
17685            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17686        }
17687        return installFlags;
17688    }
17689
17690    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17691        if (isExternal(pkg)) {
17692            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17693                return mSettings.getExternalVersion();
17694            } else {
17695                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17696            }
17697        } else {
17698            return mSettings.getInternalVersion();
17699        }
17700    }
17701
17702    private void deleteTempPackageFiles() {
17703        final FilenameFilter filter = new FilenameFilter() {
17704            public boolean accept(File dir, String name) {
17705                return name.startsWith("vmdl") && name.endsWith(".tmp");
17706            }
17707        };
17708        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17709            file.delete();
17710        }
17711    }
17712
17713    @Override
17714    public void deletePackageAsUser(String packageName, int versionCode,
17715            IPackageDeleteObserver observer, int userId, int flags) {
17716        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17717                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17718    }
17719
17720    @Override
17721    public void deletePackageVersioned(VersionedPackage versionedPackage,
17722            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17723        final int callingUid = Binder.getCallingUid();
17724        mContext.enforceCallingOrSelfPermission(
17725                android.Manifest.permission.DELETE_PACKAGES, null);
17726        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17727        Preconditions.checkNotNull(versionedPackage);
17728        Preconditions.checkNotNull(observer);
17729        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17730                PackageManager.VERSION_CODE_HIGHEST,
17731                Long.MAX_VALUE, "versionCode must be >= -1");
17732
17733        final String packageName = versionedPackage.getPackageName();
17734        final long versionCode = versionedPackage.getLongVersionCode();
17735        final String internalPackageName;
17736        synchronized (mPackages) {
17737            // Normalize package name to handle renamed packages and static libs
17738            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17739        }
17740
17741        final int uid = Binder.getCallingUid();
17742        if (!isOrphaned(internalPackageName)
17743                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17744            try {
17745                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17746                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17747                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17748                observer.onUserActionRequired(intent);
17749            } catch (RemoteException re) {
17750            }
17751            return;
17752        }
17753        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17754        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17755        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17756            mContext.enforceCallingOrSelfPermission(
17757                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17758                    "deletePackage for user " + userId);
17759        }
17760
17761        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17762            try {
17763                observer.onPackageDeleted(packageName,
17764                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17765            } catch (RemoteException re) {
17766            }
17767            return;
17768        }
17769
17770        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17771            try {
17772                observer.onPackageDeleted(packageName,
17773                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17774            } catch (RemoteException re) {
17775            }
17776            return;
17777        }
17778
17779        if (DEBUG_REMOVE) {
17780            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17781                    + " deleteAllUsers: " + deleteAllUsers + " version="
17782                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17783                    ? "VERSION_CODE_HIGHEST" : versionCode));
17784        }
17785        // Queue up an async operation since the package deletion may take a little while.
17786        mHandler.post(new Runnable() {
17787            public void run() {
17788                mHandler.removeCallbacks(this);
17789                int returnCode;
17790                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17791                boolean doDeletePackage = true;
17792                if (ps != null) {
17793                    final boolean targetIsInstantApp =
17794                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17795                    doDeletePackage = !targetIsInstantApp
17796                            || canViewInstantApps;
17797                }
17798                if (doDeletePackage) {
17799                    if (!deleteAllUsers) {
17800                        returnCode = deletePackageX(internalPackageName, versionCode,
17801                                userId, deleteFlags);
17802                    } else {
17803                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17804                                internalPackageName, users);
17805                        // If nobody is blocking uninstall, proceed with delete for all users
17806                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17807                            returnCode = deletePackageX(internalPackageName, versionCode,
17808                                    userId, deleteFlags);
17809                        } else {
17810                            // Otherwise uninstall individually for users with blockUninstalls=false
17811                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17812                            for (int userId : users) {
17813                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17814                                    returnCode = deletePackageX(internalPackageName, versionCode,
17815                                            userId, userFlags);
17816                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17817                                        Slog.w(TAG, "Package delete failed for user " + userId
17818                                                + ", returnCode " + returnCode);
17819                                    }
17820                                }
17821                            }
17822                            // The app has only been marked uninstalled for certain users.
17823                            // We still need to report that delete was blocked
17824                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17825                        }
17826                    }
17827                } else {
17828                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17829                }
17830                try {
17831                    observer.onPackageDeleted(packageName, returnCode, null);
17832                } catch (RemoteException e) {
17833                    Log.i(TAG, "Observer no longer exists.");
17834                } //end catch
17835            } //end run
17836        });
17837    }
17838
17839    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17840        if (pkg.staticSharedLibName != null) {
17841            return pkg.manifestPackageName;
17842        }
17843        return pkg.packageName;
17844    }
17845
17846    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17847        // Handle renamed packages
17848        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17849        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17850
17851        // Is this a static library?
17852        LongSparseArray<SharedLibraryEntry> versionedLib =
17853                mStaticLibsByDeclaringPackage.get(packageName);
17854        if (versionedLib == null || versionedLib.size() <= 0) {
17855            return packageName;
17856        }
17857
17858        // Figure out which lib versions the caller can see
17859        LongSparseLongArray versionsCallerCanSee = null;
17860        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17861        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17862                && callingAppId != Process.ROOT_UID) {
17863            versionsCallerCanSee = new LongSparseLongArray();
17864            String libName = versionedLib.valueAt(0).info.getName();
17865            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17866            if (uidPackages != null) {
17867                for (String uidPackage : uidPackages) {
17868                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17869                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17870                    if (libIdx >= 0) {
17871                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17872                        versionsCallerCanSee.append(libVersion, libVersion);
17873                    }
17874                }
17875            }
17876        }
17877
17878        // Caller can see nothing - done
17879        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17880            return packageName;
17881        }
17882
17883        // Find the version the caller can see and the app version code
17884        SharedLibraryEntry highestVersion = null;
17885        final int versionCount = versionedLib.size();
17886        for (int i = 0; i < versionCount; i++) {
17887            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17888            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17889                    libEntry.info.getLongVersion()) < 0) {
17890                continue;
17891            }
17892            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17893            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17894                if (libVersionCode == versionCode) {
17895                    return libEntry.apk;
17896                }
17897            } else if (highestVersion == null) {
17898                highestVersion = libEntry;
17899            } else if (libVersionCode  > highestVersion.info
17900                    .getDeclaringPackage().getLongVersionCode()) {
17901                highestVersion = libEntry;
17902            }
17903        }
17904
17905        if (highestVersion != null) {
17906            return highestVersion.apk;
17907        }
17908
17909        return packageName;
17910    }
17911
17912    boolean isCallerVerifier(int callingUid) {
17913        final int callingUserId = UserHandle.getUserId(callingUid);
17914        return mRequiredVerifierPackage != null &&
17915                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17916    }
17917
17918    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17919        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17920              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17921            return true;
17922        }
17923        final int callingUserId = UserHandle.getUserId(callingUid);
17924        // If the caller installed the pkgName, then allow it to silently uninstall.
17925        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17926            return true;
17927        }
17928
17929        // Allow package verifier to silently uninstall.
17930        if (mRequiredVerifierPackage != null &&
17931                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17932            return true;
17933        }
17934
17935        // Allow package uninstaller to silently uninstall.
17936        if (mRequiredUninstallerPackage != null &&
17937                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17938            return true;
17939        }
17940
17941        // Allow storage manager to silently uninstall.
17942        if (mStorageManagerPackage != null &&
17943                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17944            return true;
17945        }
17946
17947        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17948        // uninstall for device owner provisioning.
17949        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17950                == PERMISSION_GRANTED) {
17951            return true;
17952        }
17953
17954        return false;
17955    }
17956
17957    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17958        int[] result = EMPTY_INT_ARRAY;
17959        for (int userId : userIds) {
17960            if (getBlockUninstallForUser(packageName, userId)) {
17961                result = ArrayUtils.appendInt(result, userId);
17962            }
17963        }
17964        return result;
17965    }
17966
17967    @Override
17968    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17969        final int callingUid = Binder.getCallingUid();
17970        if (getInstantAppPackageName(callingUid) != null
17971                && !isCallerSameApp(packageName, callingUid)) {
17972            return false;
17973        }
17974        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17975    }
17976
17977    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17978        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17979                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17980        try {
17981            if (dpm != null) {
17982                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17983                        /* callingUserOnly =*/ false);
17984                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17985                        : deviceOwnerComponentName.getPackageName();
17986                // Does the package contains the device owner?
17987                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17988                // this check is probably not needed, since DO should be registered as a device
17989                // admin on some user too. (Original bug for this: b/17657954)
17990                if (packageName.equals(deviceOwnerPackageName)) {
17991                    return true;
17992                }
17993                // Does it contain a device admin for any user?
17994                int[] users;
17995                if (userId == UserHandle.USER_ALL) {
17996                    users = sUserManager.getUserIds();
17997                } else {
17998                    users = new int[]{userId};
17999                }
18000                for (int i = 0; i < users.length; ++i) {
18001                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18002                        return true;
18003                    }
18004                }
18005            }
18006        } catch (RemoteException e) {
18007        }
18008        return false;
18009    }
18010
18011    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18012        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18013    }
18014
18015    /**
18016     *  This method is an internal method that could be get invoked either
18017     *  to delete an installed package or to clean up a failed installation.
18018     *  After deleting an installed package, a broadcast is sent to notify any
18019     *  listeners that the package has been removed. For cleaning up a failed
18020     *  installation, the broadcast is not necessary since the package's
18021     *  installation wouldn't have sent the initial broadcast either
18022     *  The key steps in deleting a package are
18023     *  deleting the package information in internal structures like mPackages,
18024     *  deleting the packages base directories through installd
18025     *  updating mSettings to reflect current status
18026     *  persisting settings for later use
18027     *  sending a broadcast if necessary
18028     */
18029    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18030        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18031        final boolean res;
18032
18033        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18034                ? UserHandle.USER_ALL : userId;
18035
18036        if (isPackageDeviceAdmin(packageName, removeUser)) {
18037            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18038            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18039        }
18040
18041        PackageSetting uninstalledPs = null;
18042        PackageParser.Package pkg = null;
18043
18044        // for the uninstall-updates case and restricted profiles, remember the per-
18045        // user handle installed state
18046        int[] allUsers;
18047        synchronized (mPackages) {
18048            uninstalledPs = mSettings.mPackages.get(packageName);
18049            if (uninstalledPs == null) {
18050                Slog.w(TAG, "Not removing non-existent package " + packageName);
18051                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18052            }
18053
18054            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18055                    && uninstalledPs.versionCode != versionCode) {
18056                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18057                        + uninstalledPs.versionCode + " != " + versionCode);
18058                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18059            }
18060
18061            // Static shared libs can be declared by any package, so let us not
18062            // allow removing a package if it provides a lib others depend on.
18063            pkg = mPackages.get(packageName);
18064
18065            allUsers = sUserManager.getUserIds();
18066
18067            if (pkg != null && pkg.staticSharedLibName != null) {
18068                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18069                        pkg.staticSharedLibVersion);
18070                if (libEntry != null) {
18071                    for (int currUserId : allUsers) {
18072                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18073                            continue;
18074                        }
18075                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18076                                libEntry.info, 0, currUserId);
18077                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18078                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18079                                    + " hosting lib " + libEntry.info.getName() + " version "
18080                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18081                                    + " for user " + currUserId);
18082                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18083                        }
18084                    }
18085                }
18086            }
18087
18088            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18089        }
18090
18091        final int freezeUser;
18092        if (isUpdatedSystemApp(uninstalledPs)
18093                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18094            // We're downgrading a system app, which will apply to all users, so
18095            // freeze them all during the downgrade
18096            freezeUser = UserHandle.USER_ALL;
18097        } else {
18098            freezeUser = removeUser;
18099        }
18100
18101        synchronized (mInstallLock) {
18102            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18103            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18104                    deleteFlags, "deletePackageX")) {
18105                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18106                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18107            }
18108            synchronized (mPackages) {
18109                if (res) {
18110                    if (pkg != null) {
18111                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18112                    }
18113                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18114                    updateInstantAppInstallerLocked(packageName);
18115                }
18116            }
18117        }
18118
18119        if (res) {
18120            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18121            info.sendPackageRemovedBroadcasts(killApp);
18122            info.sendSystemPackageUpdatedBroadcasts();
18123            info.sendSystemPackageAppearedBroadcasts();
18124        }
18125        // Force a gc here.
18126        Runtime.getRuntime().gc();
18127        // Delete the resources here after sending the broadcast to let
18128        // other processes clean up before deleting resources.
18129        if (info.args != null) {
18130            synchronized (mInstallLock) {
18131                info.args.doPostDeleteLI(true);
18132            }
18133        }
18134
18135        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18136    }
18137
18138    static class PackageRemovedInfo {
18139        final PackageSender packageSender;
18140        String removedPackage;
18141        String installerPackageName;
18142        int uid = -1;
18143        int removedAppId = -1;
18144        int[] origUsers;
18145        int[] removedUsers = null;
18146        int[] broadcastUsers = null;
18147        int[] instantUserIds = null;
18148        SparseArray<Integer> installReasons;
18149        boolean isRemovedPackageSystemUpdate = false;
18150        boolean isUpdate;
18151        boolean dataRemoved;
18152        boolean removedForAllUsers;
18153        boolean isStaticSharedLib;
18154        // Clean up resources deleted packages.
18155        InstallArgs args = null;
18156        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18157        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18158
18159        PackageRemovedInfo(PackageSender packageSender) {
18160            this.packageSender = packageSender;
18161        }
18162
18163        void sendPackageRemovedBroadcasts(boolean killApp) {
18164            sendPackageRemovedBroadcastInternal(killApp);
18165            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18166            for (int i = 0; i < childCount; i++) {
18167                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18168                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18169            }
18170        }
18171
18172        void sendSystemPackageUpdatedBroadcasts() {
18173            if (isRemovedPackageSystemUpdate) {
18174                sendSystemPackageUpdatedBroadcastsInternal();
18175                final int childCount = (removedChildPackages != null)
18176                        ? removedChildPackages.size() : 0;
18177                for (int i = 0; i < childCount; i++) {
18178                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18179                    if (childInfo.isRemovedPackageSystemUpdate) {
18180                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18181                    }
18182                }
18183            }
18184        }
18185
18186        void sendSystemPackageAppearedBroadcasts() {
18187            final int packageCount = (appearedChildPackages != null)
18188                    ? appearedChildPackages.size() : 0;
18189            for (int i = 0; i < packageCount; i++) {
18190                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18191                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18192                    true /*sendBootCompleted*/, false /*startReceiver*/,
18193                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18194            }
18195        }
18196
18197        private void sendSystemPackageUpdatedBroadcastsInternal() {
18198            Bundle extras = new Bundle(2);
18199            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18200            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18201            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18202                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18203            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18204                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18205            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18206                null, null, 0, removedPackage, null, null, null);
18207            if (installerPackageName != null) {
18208                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18209                        removedPackage, extras, 0 /*flags*/,
18210                        installerPackageName, null, null, null);
18211                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18212                        removedPackage, extras, 0 /*flags*/,
18213                        installerPackageName, null, null, null);
18214            }
18215        }
18216
18217        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18218            // Don't send static shared library removal broadcasts as these
18219            // libs are visible only the the apps that depend on them an one
18220            // cannot remove the library if it has a dependency.
18221            if (isStaticSharedLib) {
18222                return;
18223            }
18224            Bundle extras = new Bundle(2);
18225            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18226            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18227            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18228            if (isUpdate || isRemovedPackageSystemUpdate) {
18229                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18230            }
18231            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18232            if (removedPackage != null) {
18233                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18234                    removedPackage, extras, 0, null /*targetPackage*/, null,
18235                    broadcastUsers, instantUserIds);
18236                if (installerPackageName != null) {
18237                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18238                            removedPackage, extras, 0 /*flags*/,
18239                            installerPackageName, null, broadcastUsers, instantUserIds);
18240                }
18241                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18242                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18243                        removedPackage, extras,
18244                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18245                        null, null, broadcastUsers, instantUserIds);
18246                    packageSender.notifyPackageRemoved(removedPackage);
18247                }
18248            }
18249            if (removedAppId >= 0) {
18250                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18251                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18252                    null, null, broadcastUsers, instantUserIds);
18253            }
18254        }
18255
18256        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18257            removedUsers = userIds;
18258            if (removedUsers == null) {
18259                broadcastUsers = null;
18260                return;
18261            }
18262
18263            broadcastUsers = EMPTY_INT_ARRAY;
18264            instantUserIds = EMPTY_INT_ARRAY;
18265            for (int i = userIds.length - 1; i >= 0; --i) {
18266                final int userId = userIds[i];
18267                if (deletedPackageSetting.getInstantApp(userId)) {
18268                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18269                } else {
18270                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18271                }
18272            }
18273        }
18274    }
18275
18276    /*
18277     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18278     * flag is not set, the data directory is removed as well.
18279     * make sure this flag is set for partially installed apps. If not its meaningless to
18280     * delete a partially installed application.
18281     */
18282    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18283            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18284        String packageName = ps.name;
18285        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18286        // Retrieve object to delete permissions for shared user later on
18287        final PackageParser.Package deletedPkg;
18288        final PackageSetting deletedPs;
18289        // reader
18290        synchronized (mPackages) {
18291            deletedPkg = mPackages.get(packageName);
18292            deletedPs = mSettings.mPackages.get(packageName);
18293            if (outInfo != null) {
18294                outInfo.removedPackage = packageName;
18295                outInfo.installerPackageName = ps.installerPackageName;
18296                outInfo.isStaticSharedLib = deletedPkg != null
18297                        && deletedPkg.staticSharedLibName != null;
18298                outInfo.populateUsers(deletedPs == null ? null
18299                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18300            }
18301        }
18302
18303        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18304
18305        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18306            final PackageParser.Package resolvedPkg;
18307            if (deletedPkg != null) {
18308                resolvedPkg = deletedPkg;
18309            } else {
18310                // We don't have a parsed package when it lives on an ejected
18311                // adopted storage device, so fake something together
18312                resolvedPkg = new PackageParser.Package(ps.name);
18313                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18314            }
18315            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18316                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18317            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18318            if (outInfo != null) {
18319                outInfo.dataRemoved = true;
18320            }
18321            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18322        }
18323
18324        int removedAppId = -1;
18325
18326        // writer
18327        synchronized (mPackages) {
18328            boolean installedStateChanged = false;
18329            if (deletedPs != null) {
18330                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18331                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18332                    clearDefaultBrowserIfNeeded(packageName);
18333                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18334                    removedAppId = mSettings.removePackageLPw(packageName);
18335                    if (outInfo != null) {
18336                        outInfo.removedAppId = removedAppId;
18337                    }
18338                    mPermissionManager.updatePermissions(
18339                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18340                    if (deletedPs.sharedUser != null) {
18341                        // Remove permissions associated with package. Since runtime
18342                        // permissions are per user we have to kill the removed package
18343                        // or packages running under the shared user of the removed
18344                        // package if revoking the permissions requested only by the removed
18345                        // package is successful and this causes a change in gids.
18346                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18347                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18348                                    userId);
18349                            if (userIdToKill == UserHandle.USER_ALL
18350                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18351                                // If gids changed for this user, kill all affected packages.
18352                                mHandler.post(new Runnable() {
18353                                    @Override
18354                                    public void run() {
18355                                        // This has to happen with no lock held.
18356                                        killApplication(deletedPs.name, deletedPs.appId,
18357                                                KILL_APP_REASON_GIDS_CHANGED);
18358                                    }
18359                                });
18360                                break;
18361                            }
18362                        }
18363                    }
18364                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18365                }
18366                // make sure to preserve per-user disabled state if this removal was just
18367                // a downgrade of a system app to the factory package
18368                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18369                    if (DEBUG_REMOVE) {
18370                        Slog.d(TAG, "Propagating install state across downgrade");
18371                    }
18372                    for (int userId : allUserHandles) {
18373                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18374                        if (DEBUG_REMOVE) {
18375                            Slog.d(TAG, "    user " + userId + " => " + installed);
18376                        }
18377                        if (installed != ps.getInstalled(userId)) {
18378                            installedStateChanged = true;
18379                        }
18380                        ps.setInstalled(installed, userId);
18381                    }
18382                }
18383            }
18384            // can downgrade to reader
18385            if (writeSettings) {
18386                // Save settings now
18387                mSettings.writeLPr();
18388            }
18389            if (installedStateChanged) {
18390                mSettings.writeKernelMappingLPr(ps);
18391            }
18392        }
18393        if (removedAppId != -1) {
18394            // A user ID was deleted here. Go through all users and remove it
18395            // from KeyStore.
18396            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18397        }
18398    }
18399
18400    static boolean locationIsPrivileged(String path) {
18401        try {
18402            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18403            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18404            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18405            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18406            return path.startsWith(privilegedAppDir.getCanonicalPath())
18407                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18408                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18409                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18410        } catch (IOException e) {
18411            Slog.e(TAG, "Unable to access code path " + path);
18412        }
18413        return false;
18414    }
18415
18416    static boolean locationIsOem(String path) {
18417        try {
18418            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18419        } catch (IOException e) {
18420            Slog.e(TAG, "Unable to access code path " + path);
18421        }
18422        return false;
18423    }
18424
18425    static boolean locationIsVendor(String path) {
18426        try {
18427            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18428                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18429        } catch (IOException e) {
18430            Slog.e(TAG, "Unable to access code path " + path);
18431        }
18432        return false;
18433    }
18434
18435    static boolean locationIsProduct(String path) {
18436        try {
18437            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18438        } catch (IOException e) {
18439            Slog.e(TAG, "Unable to access code path " + path);
18440        }
18441        return false;
18442    }
18443
18444    /*
18445     * Tries to delete system package.
18446     */
18447    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18448            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18449            boolean writeSettings) {
18450        if (deletedPs.parentPackageName != null) {
18451            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18452            return false;
18453        }
18454
18455        final boolean applyUserRestrictions
18456                = (allUserHandles != null) && (outInfo.origUsers != null);
18457        final PackageSetting disabledPs;
18458        // Confirm if the system package has been updated
18459        // An updated system app can be deleted. This will also have to restore
18460        // the system pkg from system partition
18461        // reader
18462        synchronized (mPackages) {
18463            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18464        }
18465
18466        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18467                + " disabledPs=" + disabledPs);
18468
18469        if (disabledPs == null) {
18470            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18471            return false;
18472        } else if (DEBUG_REMOVE) {
18473            Slog.d(TAG, "Deleting system pkg from data partition");
18474        }
18475
18476        if (DEBUG_REMOVE) {
18477            if (applyUserRestrictions) {
18478                Slog.d(TAG, "Remembering install states:");
18479                for (int userId : allUserHandles) {
18480                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18481                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18482                }
18483            }
18484        }
18485
18486        // Delete the updated package
18487        outInfo.isRemovedPackageSystemUpdate = true;
18488        if (outInfo.removedChildPackages != null) {
18489            final int childCount = (deletedPs.childPackageNames != null)
18490                    ? deletedPs.childPackageNames.size() : 0;
18491            for (int i = 0; i < childCount; i++) {
18492                String childPackageName = deletedPs.childPackageNames.get(i);
18493                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18494                        .contains(childPackageName)) {
18495                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18496                            childPackageName);
18497                    if (childInfo != null) {
18498                        childInfo.isRemovedPackageSystemUpdate = true;
18499                    }
18500                }
18501            }
18502        }
18503
18504        if (disabledPs.versionCode < deletedPs.versionCode) {
18505            // Delete data for downgrades
18506            flags &= ~PackageManager.DELETE_KEEP_DATA;
18507        } else {
18508            // Preserve data by setting flag
18509            flags |= PackageManager.DELETE_KEEP_DATA;
18510        }
18511
18512        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18513                outInfo, writeSettings, disabledPs.pkg);
18514        if (!ret) {
18515            return false;
18516        }
18517
18518        // writer
18519        synchronized (mPackages) {
18520            // NOTE: The system package always needs to be enabled; even if it's for
18521            // a compressed stub. If we don't, installing the system package fails
18522            // during scan [scanning checks the disabled packages]. We will reverse
18523            // this later, after we've "installed" the stub.
18524            // Reinstate the old system package
18525            enableSystemPackageLPw(disabledPs.pkg);
18526            // Remove any native libraries from the upgraded package.
18527            removeNativeBinariesLI(deletedPs);
18528        }
18529
18530        // Install the system package
18531        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18532        try {
18533            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18534                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18535        } catch (PackageManagerException e) {
18536            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18537                    + e.getMessage());
18538            return false;
18539        } finally {
18540            if (disabledPs.pkg.isStub) {
18541                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18542            }
18543        }
18544        return true;
18545    }
18546
18547    /**
18548     * Installs a package that's already on the system partition.
18549     */
18550    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18551            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18552            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18553                    throws PackageManagerException {
18554        @ParseFlags int parseFlags =
18555                mDefParseFlags
18556                | PackageParser.PARSE_MUST_BE_APK
18557                | PackageParser.PARSE_IS_SYSTEM_DIR;
18558        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18559        if (isPrivileged || locationIsPrivileged(codePathString)) {
18560            scanFlags |= SCAN_AS_PRIVILEGED;
18561        }
18562        if (locationIsOem(codePathString)) {
18563            scanFlags |= SCAN_AS_OEM;
18564        }
18565        if (locationIsVendor(codePathString)) {
18566            scanFlags |= SCAN_AS_VENDOR;
18567        }
18568        if (locationIsProduct(codePathString)) {
18569            scanFlags |= SCAN_AS_PRODUCT;
18570        }
18571
18572        final File codePath = new File(codePathString);
18573        final PackageParser.Package pkg =
18574                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18575
18576        try {
18577            // update shared libraries for the newly re-installed system package
18578            updateSharedLibrariesLPr(pkg, null);
18579        } catch (PackageManagerException e) {
18580            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18581        }
18582
18583        prepareAppDataAfterInstallLIF(pkg);
18584
18585        // writer
18586        synchronized (mPackages) {
18587            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18588
18589            // Propagate the permissions state as we do not want to drop on the floor
18590            // runtime permissions. The update permissions method below will take
18591            // care of removing obsolete permissions and grant install permissions.
18592            if (origPermissionState != null) {
18593                ps.getPermissionsState().copyFrom(origPermissionState);
18594            }
18595            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18596                    mPermissionCallback);
18597
18598            final boolean applyUserRestrictions
18599                    = (allUserHandles != null) && (origUserHandles != null);
18600            if (applyUserRestrictions) {
18601                boolean installedStateChanged = false;
18602                if (DEBUG_REMOVE) {
18603                    Slog.d(TAG, "Propagating install state across reinstall");
18604                }
18605                for (int userId : allUserHandles) {
18606                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18607                    if (DEBUG_REMOVE) {
18608                        Slog.d(TAG, "    user " + userId + " => " + installed);
18609                    }
18610                    if (installed != ps.getInstalled(userId)) {
18611                        installedStateChanged = true;
18612                    }
18613                    ps.setInstalled(installed, userId);
18614
18615                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18616                }
18617                // Regardless of writeSettings we need to ensure that this restriction
18618                // state propagation is persisted
18619                mSettings.writeAllUsersPackageRestrictionsLPr();
18620                if (installedStateChanged) {
18621                    mSettings.writeKernelMappingLPr(ps);
18622                }
18623            }
18624            // can downgrade to reader here
18625            if (writeSettings) {
18626                mSettings.writeLPr();
18627            }
18628        }
18629        return pkg;
18630    }
18631
18632    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18633            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18634            PackageRemovedInfo outInfo, boolean writeSettings,
18635            PackageParser.Package replacingPackage) {
18636        synchronized (mPackages) {
18637            if (outInfo != null) {
18638                outInfo.uid = ps.appId;
18639            }
18640
18641            if (outInfo != null && outInfo.removedChildPackages != null) {
18642                final int childCount = (ps.childPackageNames != null)
18643                        ? ps.childPackageNames.size() : 0;
18644                for (int i = 0; i < childCount; i++) {
18645                    String childPackageName = ps.childPackageNames.get(i);
18646                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18647                    if (childPs == null) {
18648                        return false;
18649                    }
18650                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18651                            childPackageName);
18652                    if (childInfo != null) {
18653                        childInfo.uid = childPs.appId;
18654                    }
18655                }
18656            }
18657        }
18658
18659        // Delete package data from internal structures and also remove data if flag is set
18660        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18661
18662        // Delete the child packages data
18663        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18664        for (int i = 0; i < childCount; i++) {
18665            PackageSetting childPs;
18666            synchronized (mPackages) {
18667                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18668            }
18669            if (childPs != null) {
18670                PackageRemovedInfo childOutInfo = (outInfo != null
18671                        && outInfo.removedChildPackages != null)
18672                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18673                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18674                        && (replacingPackage != null
18675                        && !replacingPackage.hasChildPackage(childPs.name))
18676                        ? flags & ~DELETE_KEEP_DATA : flags;
18677                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18678                        deleteFlags, writeSettings);
18679            }
18680        }
18681
18682        // Delete application code and resources only for parent packages
18683        if (ps.parentPackageName == null) {
18684            if (deleteCodeAndResources && (outInfo != null)) {
18685                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18686                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18687                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18688            }
18689        }
18690
18691        return true;
18692    }
18693
18694    @Override
18695    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18696            int userId) {
18697        mContext.enforceCallingOrSelfPermission(
18698                android.Manifest.permission.DELETE_PACKAGES, null);
18699        synchronized (mPackages) {
18700            // Cannot block uninstall of static shared libs as they are
18701            // considered a part of the using app (emulating static linking).
18702            // Also static libs are installed always on internal storage.
18703            PackageParser.Package pkg = mPackages.get(packageName);
18704            if (pkg != null && pkg.staticSharedLibName != null) {
18705                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18706                        + " providing static shared library: " + pkg.staticSharedLibName);
18707                return false;
18708            }
18709            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18710            mSettings.writePackageRestrictionsLPr(userId);
18711        }
18712        return true;
18713    }
18714
18715    @Override
18716    public boolean getBlockUninstallForUser(String packageName, int userId) {
18717        synchronized (mPackages) {
18718            final PackageSetting ps = mSettings.mPackages.get(packageName);
18719            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18720                return false;
18721            }
18722            return mSettings.getBlockUninstallLPr(userId, packageName);
18723        }
18724    }
18725
18726    @Override
18727    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18728        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18729        synchronized (mPackages) {
18730            PackageSetting ps = mSettings.mPackages.get(packageName);
18731            if (ps == null) {
18732                Log.w(TAG, "Package doesn't exist: " + packageName);
18733                return false;
18734            }
18735            if (systemUserApp) {
18736                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18737            } else {
18738                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18739            }
18740            mSettings.writeLPr();
18741        }
18742        return true;
18743    }
18744
18745    /*
18746     * This method handles package deletion in general
18747     */
18748    private boolean deletePackageLIF(String packageName, UserHandle user,
18749            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18750            PackageRemovedInfo outInfo, boolean writeSettings,
18751            PackageParser.Package replacingPackage) {
18752        if (packageName == null) {
18753            Slog.w(TAG, "Attempt to delete null packageName.");
18754            return false;
18755        }
18756
18757        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18758
18759        PackageSetting ps;
18760        synchronized (mPackages) {
18761            ps = mSettings.mPackages.get(packageName);
18762            if (ps == null) {
18763                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18764                return false;
18765            }
18766
18767            if (ps.parentPackageName != null && (!isSystemApp(ps)
18768                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18769                if (DEBUG_REMOVE) {
18770                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18771                            + ((user == null) ? UserHandle.USER_ALL : user));
18772                }
18773                final int removedUserId = (user != null) ? user.getIdentifier()
18774                        : UserHandle.USER_ALL;
18775
18776                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18777                    return false;
18778                }
18779                markPackageUninstalledForUserLPw(ps, user);
18780                scheduleWritePackageRestrictionsLocked(user);
18781                return true;
18782            }
18783        }
18784
18785        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18786        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18787            onSuspendingPackageRemoved(packageName, userId);
18788        }
18789
18790
18791        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18792                && user.getIdentifier() != UserHandle.USER_ALL)) {
18793            // The caller is asking that the package only be deleted for a single
18794            // user.  To do this, we just mark its uninstalled state and delete
18795            // its data. If this is a system app, we only allow this to happen if
18796            // they have set the special DELETE_SYSTEM_APP which requests different
18797            // semantics than normal for uninstalling system apps.
18798            markPackageUninstalledForUserLPw(ps, user);
18799
18800            if (!isSystemApp(ps)) {
18801                // Do not uninstall the APK if an app should be cached
18802                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18803                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18804                    // Other user still have this package installed, so all
18805                    // we need to do is clear this user's data and save that
18806                    // it is uninstalled.
18807                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18808                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18809                        return false;
18810                    }
18811                    scheduleWritePackageRestrictionsLocked(user);
18812                    return true;
18813                } else {
18814                    // We need to set it back to 'installed' so the uninstall
18815                    // broadcasts will be sent correctly.
18816                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18817                    ps.setInstalled(true, user.getIdentifier());
18818                    mSettings.writeKernelMappingLPr(ps);
18819                }
18820            } else {
18821                // This is a system app, so we assume that the
18822                // other users still have this package installed, so all
18823                // we need to do is clear this user's data and save that
18824                // it is uninstalled.
18825                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18826                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18827                    return false;
18828                }
18829                scheduleWritePackageRestrictionsLocked(user);
18830                return true;
18831            }
18832        }
18833
18834        // If we are deleting a composite package for all users, keep track
18835        // of result for each child.
18836        if (ps.childPackageNames != null && outInfo != null) {
18837            synchronized (mPackages) {
18838                final int childCount = ps.childPackageNames.size();
18839                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18840                for (int i = 0; i < childCount; i++) {
18841                    String childPackageName = ps.childPackageNames.get(i);
18842                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18843                    childInfo.removedPackage = childPackageName;
18844                    childInfo.installerPackageName = ps.installerPackageName;
18845                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18846                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18847                    if (childPs != null) {
18848                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18849                    }
18850                }
18851            }
18852        }
18853
18854        boolean ret = false;
18855        if (isSystemApp(ps)) {
18856            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18857            // When an updated system application is deleted we delete the existing resources
18858            // as well and fall back to existing code in system partition
18859            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18860        } else {
18861            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18862            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18863                    outInfo, writeSettings, replacingPackage);
18864        }
18865
18866        // Take a note whether we deleted the package for all users
18867        if (outInfo != null) {
18868            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18869            if (outInfo.removedChildPackages != null) {
18870                synchronized (mPackages) {
18871                    final int childCount = outInfo.removedChildPackages.size();
18872                    for (int i = 0; i < childCount; i++) {
18873                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18874                        if (childInfo != null) {
18875                            childInfo.removedForAllUsers = mPackages.get(
18876                                    childInfo.removedPackage) == null;
18877                        }
18878                    }
18879                }
18880            }
18881            // If we uninstalled an update to a system app there may be some
18882            // child packages that appeared as they are declared in the system
18883            // app but were not declared in the update.
18884            if (isSystemApp(ps)) {
18885                synchronized (mPackages) {
18886                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18887                    final int childCount = (updatedPs.childPackageNames != null)
18888                            ? updatedPs.childPackageNames.size() : 0;
18889                    for (int i = 0; i < childCount; i++) {
18890                        String childPackageName = updatedPs.childPackageNames.get(i);
18891                        if (outInfo.removedChildPackages == null
18892                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18893                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18894                            if (childPs == null) {
18895                                continue;
18896                            }
18897                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18898                            installRes.name = childPackageName;
18899                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18900                            installRes.pkg = mPackages.get(childPackageName);
18901                            installRes.uid = childPs.pkg.applicationInfo.uid;
18902                            if (outInfo.appearedChildPackages == null) {
18903                                outInfo.appearedChildPackages = new ArrayMap<>();
18904                            }
18905                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18906                        }
18907                    }
18908                }
18909            }
18910        }
18911
18912        return ret;
18913    }
18914
18915    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18916        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18917                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18918        for (int nextUserId : userIds) {
18919            if (DEBUG_REMOVE) {
18920                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18921            }
18922            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18923                    false /*installed*/,
18924                    true /*stopped*/,
18925                    true /*notLaunched*/,
18926                    false /*hidden*/,
18927                    false /*suspended*/,
18928                    null, /*suspendingPackage*/
18929                    null, /*dialogMessage*/
18930                    null, /*suspendedAppExtras*/
18931                    null, /*suspendedLauncherExtras*/
18932                    false /*instantApp*/,
18933                    false /*virtualPreload*/,
18934                    null /*lastDisableAppCaller*/,
18935                    null /*enabledComponents*/,
18936                    null /*disabledComponents*/,
18937                    ps.readUserState(nextUserId).domainVerificationStatus,
18938                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18939                    null /*harmfulAppWarning*/);
18940        }
18941        mSettings.writeKernelMappingLPr(ps);
18942    }
18943
18944    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18945            PackageRemovedInfo outInfo) {
18946        final PackageParser.Package pkg;
18947        synchronized (mPackages) {
18948            pkg = mPackages.get(ps.name);
18949        }
18950
18951        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18952                : new int[] {userId};
18953        for (int nextUserId : userIds) {
18954            if (DEBUG_REMOVE) {
18955                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18956                        + nextUserId);
18957            }
18958
18959            destroyAppDataLIF(pkg, userId,
18960                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18961            destroyAppProfilesLIF(pkg, userId);
18962            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18963            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18964            schedulePackageCleaning(ps.name, nextUserId, false);
18965            synchronized (mPackages) {
18966                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18967                    scheduleWritePackageRestrictionsLocked(nextUserId);
18968                }
18969                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18970            }
18971        }
18972
18973        if (outInfo != null) {
18974            outInfo.removedPackage = ps.name;
18975            outInfo.installerPackageName = ps.installerPackageName;
18976            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18977            outInfo.removedAppId = ps.appId;
18978            outInfo.removedUsers = userIds;
18979            outInfo.broadcastUsers = userIds;
18980        }
18981
18982        return true;
18983    }
18984
18985    private final class ClearStorageConnection implements ServiceConnection {
18986        IMediaContainerService mContainerService;
18987
18988        @Override
18989        public void onServiceConnected(ComponentName name, IBinder service) {
18990            synchronized (this) {
18991                mContainerService = IMediaContainerService.Stub
18992                        .asInterface(Binder.allowBlocking(service));
18993                notifyAll();
18994            }
18995        }
18996
18997        @Override
18998        public void onServiceDisconnected(ComponentName name) {
18999        }
19000    }
19001
19002    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19003        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19004
19005        final boolean mounted;
19006        if (Environment.isExternalStorageEmulated()) {
19007            mounted = true;
19008        } else {
19009            final String status = Environment.getExternalStorageState();
19010
19011            mounted = status.equals(Environment.MEDIA_MOUNTED)
19012                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19013        }
19014
19015        if (!mounted) {
19016            return;
19017        }
19018
19019        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19020        int[] users;
19021        if (userId == UserHandle.USER_ALL) {
19022            users = sUserManager.getUserIds();
19023        } else {
19024            users = new int[] { userId };
19025        }
19026        final ClearStorageConnection conn = new ClearStorageConnection();
19027        if (mContext.bindServiceAsUser(
19028                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19029            try {
19030                for (int curUser : users) {
19031                    long timeout = SystemClock.uptimeMillis() + 5000;
19032                    synchronized (conn) {
19033                        long now;
19034                        while (conn.mContainerService == null &&
19035                                (now = SystemClock.uptimeMillis()) < timeout) {
19036                            try {
19037                                conn.wait(timeout - now);
19038                            } catch (InterruptedException e) {
19039                            }
19040                        }
19041                    }
19042                    if (conn.mContainerService == null) {
19043                        return;
19044                    }
19045
19046                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19047                    clearDirectory(conn.mContainerService,
19048                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19049                    if (allData) {
19050                        clearDirectory(conn.mContainerService,
19051                                userEnv.buildExternalStorageAppDataDirs(packageName));
19052                        clearDirectory(conn.mContainerService,
19053                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19054                    }
19055                }
19056            } finally {
19057                mContext.unbindService(conn);
19058            }
19059        }
19060    }
19061
19062    @Override
19063    public void clearApplicationProfileData(String packageName) {
19064        enforceSystemOrRoot("Only the system can clear all profile data");
19065
19066        final PackageParser.Package pkg;
19067        synchronized (mPackages) {
19068            pkg = mPackages.get(packageName);
19069        }
19070
19071        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19072            synchronized (mInstallLock) {
19073                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19074            }
19075        }
19076    }
19077
19078    @Override
19079    public void clearApplicationUserData(final String packageName,
19080            final IPackageDataObserver observer, final int userId) {
19081        mContext.enforceCallingOrSelfPermission(
19082                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19083
19084        final int callingUid = Binder.getCallingUid();
19085        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19086                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19087
19088        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19089        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19090        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19091            throw new SecurityException("Cannot clear data for a protected package: "
19092                    + packageName);
19093        }
19094        // Queue up an async operation since the package deletion may take a little while.
19095        mHandler.post(new Runnable() {
19096            public void run() {
19097                mHandler.removeCallbacks(this);
19098                final boolean succeeded;
19099                if (!filterApp) {
19100                    try (PackageFreezer freezer = freezePackage(packageName,
19101                            "clearApplicationUserData")) {
19102                        synchronized (mInstallLock) {
19103                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19104                        }
19105                        clearExternalStorageDataSync(packageName, userId, true);
19106                        synchronized (mPackages) {
19107                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19108                                    packageName, userId);
19109                        }
19110                    }
19111                    if (succeeded) {
19112                        // invoke DeviceStorageMonitor's update method to clear any notifications
19113                        DeviceStorageMonitorInternal dsm = LocalServices
19114                                .getService(DeviceStorageMonitorInternal.class);
19115                        if (dsm != null) {
19116                            dsm.checkMemory();
19117                        }
19118                    }
19119                } else {
19120                    succeeded = false;
19121                }
19122                if (observer != null) {
19123                    try {
19124                        observer.onRemoveCompleted(packageName, succeeded);
19125                    } catch (RemoteException e) {
19126                        Log.i(TAG, "Observer no longer exists.");
19127                    }
19128                } //end if observer
19129            } //end run
19130        });
19131    }
19132
19133    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19134        if (packageName == null) {
19135            Slog.w(TAG, "Attempt to delete null packageName.");
19136            return false;
19137        }
19138
19139        // Try finding details about the requested package
19140        PackageParser.Package pkg;
19141        synchronized (mPackages) {
19142            pkg = mPackages.get(packageName);
19143            if (pkg == null) {
19144                final PackageSetting ps = mSettings.mPackages.get(packageName);
19145                if (ps != null) {
19146                    pkg = ps.pkg;
19147                }
19148            }
19149
19150            if (pkg == null) {
19151                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19152                return false;
19153            }
19154
19155            PackageSetting ps = (PackageSetting) pkg.mExtras;
19156            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19157        }
19158
19159        clearAppDataLIF(pkg, userId,
19160                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19161
19162        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19163        removeKeystoreDataIfNeeded(userId, appId);
19164
19165        UserManagerInternal umInternal = getUserManagerInternal();
19166        final int flags;
19167        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19168            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19169        } else if (umInternal.isUserRunning(userId)) {
19170            flags = StorageManager.FLAG_STORAGE_DE;
19171        } else {
19172            flags = 0;
19173        }
19174        prepareAppDataContentsLIF(pkg, userId, flags);
19175
19176        return true;
19177    }
19178
19179    /**
19180     * Reverts user permission state changes (permissions and flags) in
19181     * all packages for a given user.
19182     *
19183     * @param userId The device user for which to do a reset.
19184     */
19185    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19186        final int packageCount = mPackages.size();
19187        for (int i = 0; i < packageCount; i++) {
19188            PackageParser.Package pkg = mPackages.valueAt(i);
19189            PackageSetting ps = (PackageSetting) pkg.mExtras;
19190            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19191        }
19192    }
19193
19194    private void resetNetworkPolicies(int userId) {
19195        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19196    }
19197
19198    /**
19199     * Reverts user permission state changes (permissions and flags).
19200     *
19201     * @param ps The package for which to reset.
19202     * @param userId The device user for which to do a reset.
19203     */
19204    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19205            final PackageSetting ps, final int userId) {
19206        if (ps.pkg == null) {
19207            return;
19208        }
19209
19210        // These are flags that can change base on user actions.
19211        final int userSettableMask = FLAG_PERMISSION_USER_SET
19212                | FLAG_PERMISSION_USER_FIXED
19213                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19214                | FLAG_PERMISSION_REVIEW_REQUIRED;
19215
19216        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19217                | FLAG_PERMISSION_POLICY_FIXED;
19218
19219        boolean writeInstallPermissions = false;
19220        boolean writeRuntimePermissions = false;
19221
19222        final int permissionCount = ps.pkg.requestedPermissions.size();
19223        for (int i = 0; i < permissionCount; i++) {
19224            final String permName = ps.pkg.requestedPermissions.get(i);
19225            final BasePermission bp =
19226                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19227            if (bp == null) {
19228                continue;
19229            }
19230
19231            // If shared user we just reset the state to which only this app contributed.
19232            if (ps.sharedUser != null) {
19233                boolean used = false;
19234                final int packageCount = ps.sharedUser.packages.size();
19235                for (int j = 0; j < packageCount; j++) {
19236                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19237                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19238                            && pkg.pkg.requestedPermissions.contains(permName)) {
19239                        used = true;
19240                        break;
19241                    }
19242                }
19243                if (used) {
19244                    continue;
19245                }
19246            }
19247
19248            final PermissionsState permissionsState = ps.getPermissionsState();
19249
19250            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19251
19252            // Always clear the user settable flags.
19253            final boolean hasInstallState =
19254                    permissionsState.getInstallPermissionState(permName) != null;
19255            // If permission review is enabled and this is a legacy app, mark the
19256            // permission as requiring a review as this is the initial state.
19257            int flags = 0;
19258            if (mSettings.mPermissions.mPermissionReviewRequired
19259                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19260                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19261            }
19262            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19263                if (hasInstallState) {
19264                    writeInstallPermissions = true;
19265                } else {
19266                    writeRuntimePermissions = true;
19267                }
19268            }
19269
19270            // Below is only runtime permission handling.
19271            if (!bp.isRuntime()) {
19272                continue;
19273            }
19274
19275            // Never clobber system or policy.
19276            if ((oldFlags & policyOrSystemFlags) != 0) {
19277                continue;
19278            }
19279
19280            // If this permission was granted by default, make sure it is.
19281            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19282                if (permissionsState.grantRuntimePermission(bp, userId)
19283                        != PERMISSION_OPERATION_FAILURE) {
19284                    writeRuntimePermissions = true;
19285                }
19286            // If permission review is enabled the permissions for a legacy apps
19287            // are represented as constantly granted runtime ones, so don't revoke.
19288            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19289                // Otherwise, reset the permission.
19290                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19291                switch (revokeResult) {
19292                    case PERMISSION_OPERATION_SUCCESS:
19293                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19294                        writeRuntimePermissions = true;
19295                        final int appId = ps.appId;
19296                        mHandler.post(new Runnable() {
19297                            @Override
19298                            public void run() {
19299                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19300                            }
19301                        });
19302                    } break;
19303                }
19304            }
19305        }
19306
19307        // Synchronously write as we are taking permissions away.
19308        if (writeRuntimePermissions) {
19309            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19310        }
19311
19312        // Synchronously write as we are taking permissions away.
19313        if (writeInstallPermissions) {
19314            mSettings.writeLPr();
19315        }
19316    }
19317
19318    /**
19319     * Remove entries from the keystore daemon. Will only remove it if the
19320     * {@code appId} is valid.
19321     */
19322    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19323        if (appId < 0) {
19324            return;
19325        }
19326
19327        final KeyStore keyStore = KeyStore.getInstance();
19328        if (keyStore != null) {
19329            if (userId == UserHandle.USER_ALL) {
19330                for (final int individual : sUserManager.getUserIds()) {
19331                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19332                }
19333            } else {
19334                keyStore.clearUid(UserHandle.getUid(userId, appId));
19335            }
19336        } else {
19337            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19338        }
19339    }
19340
19341    @Override
19342    public void deleteApplicationCacheFiles(final String packageName,
19343            final IPackageDataObserver observer) {
19344        final int userId = UserHandle.getCallingUserId();
19345        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19346    }
19347
19348    @Override
19349    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19350            final IPackageDataObserver observer) {
19351        final int callingUid = Binder.getCallingUid();
19352        if (mContext.checkCallingOrSelfPermission(
19353                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19354                != PackageManager.PERMISSION_GRANTED) {
19355            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19356            if (mContext.checkCallingOrSelfPermission(
19357                    android.Manifest.permission.DELETE_CACHE_FILES)
19358                    == PackageManager.PERMISSION_GRANTED) {
19359                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19360                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19361                        ", silently ignoring");
19362                return;
19363            }
19364            mContext.enforceCallingOrSelfPermission(
19365                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19366        }
19367        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19368                /* requireFullPermission= */ true, /* checkShell= */ false,
19369                "delete application cache files");
19370        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19371                android.Manifest.permission.ACCESS_INSTANT_APPS);
19372
19373        final PackageParser.Package pkg;
19374        synchronized (mPackages) {
19375            pkg = mPackages.get(packageName);
19376        }
19377
19378        // Queue up an async operation since the package deletion may take a little while.
19379        mHandler.post(new Runnable() {
19380            public void run() {
19381                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19382                boolean doClearData = true;
19383                if (ps != null) {
19384                    final boolean targetIsInstantApp =
19385                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19386                    doClearData = !targetIsInstantApp
19387                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19388                }
19389                if (doClearData) {
19390                    synchronized (mInstallLock) {
19391                        final int flags = StorageManager.FLAG_STORAGE_DE
19392                                | StorageManager.FLAG_STORAGE_CE;
19393                        // We're only clearing cache files, so we don't care if the
19394                        // app is unfrozen and still able to run
19395                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19396                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19397                    }
19398                    clearExternalStorageDataSync(packageName, userId, false);
19399                }
19400                if (observer != null) {
19401                    try {
19402                        observer.onRemoveCompleted(packageName, true);
19403                    } catch (RemoteException e) {
19404                        Log.i(TAG, "Observer no longer exists.");
19405                    }
19406                }
19407            }
19408        });
19409    }
19410
19411    @Override
19412    public void getPackageSizeInfo(final String packageName, int userHandle,
19413            final IPackageStatsObserver observer) {
19414        throw new UnsupportedOperationException(
19415                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19416    }
19417
19418    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19419        final PackageSetting ps;
19420        synchronized (mPackages) {
19421            ps = mSettings.mPackages.get(packageName);
19422            if (ps == null) {
19423                Slog.w(TAG, "Failed to find settings for " + packageName);
19424                return false;
19425            }
19426        }
19427
19428        final String[] packageNames = { packageName };
19429        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19430        final String[] codePaths = { ps.codePathString };
19431
19432        try {
19433            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19434                    ps.appId, ceDataInodes, codePaths, stats);
19435
19436            // For now, ignore code size of packages on system partition
19437            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19438                stats.codeSize = 0;
19439            }
19440
19441            // External clients expect these to be tracked separately
19442            stats.dataSize -= stats.cacheSize;
19443
19444        } catch (InstallerException e) {
19445            Slog.w(TAG, String.valueOf(e));
19446            return false;
19447        }
19448
19449        return true;
19450    }
19451
19452    private int getUidTargetSdkVersionLockedLPr(int uid) {
19453        Object obj = mSettings.getUserIdLPr(uid);
19454        if (obj instanceof SharedUserSetting) {
19455            final SharedUserSetting sus = (SharedUserSetting) obj;
19456            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19457            final Iterator<PackageSetting> it = sus.packages.iterator();
19458            while (it.hasNext()) {
19459                final PackageSetting ps = it.next();
19460                if (ps.pkg != null) {
19461                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19462                    if (v < vers) vers = v;
19463                }
19464            }
19465            return vers;
19466        } else if (obj instanceof PackageSetting) {
19467            final PackageSetting ps = (PackageSetting) obj;
19468            if (ps.pkg != null) {
19469                return ps.pkg.applicationInfo.targetSdkVersion;
19470            }
19471        }
19472        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19473    }
19474
19475    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19476        final PackageParser.Package p = mPackages.get(packageName);
19477        if (p != null) {
19478            return p.applicationInfo.targetSdkVersion;
19479        }
19480        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19481    }
19482
19483    @Override
19484    public void addPreferredActivity(IntentFilter filter, int match,
19485            ComponentName[] set, ComponentName activity, int userId) {
19486        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19487                "Adding preferred");
19488    }
19489
19490    private void addPreferredActivityInternal(IntentFilter filter, int match,
19491            ComponentName[] set, ComponentName activity, boolean always, int userId,
19492            String opname) {
19493        // writer
19494        int callingUid = Binder.getCallingUid();
19495        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19496                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19497        if (filter.countActions() == 0) {
19498            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19499            return;
19500        }
19501        synchronized (mPackages) {
19502            if (mContext.checkCallingOrSelfPermission(
19503                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19504                    != PackageManager.PERMISSION_GRANTED) {
19505                if (getUidTargetSdkVersionLockedLPr(callingUid)
19506                        < Build.VERSION_CODES.FROYO) {
19507                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19508                            + callingUid);
19509                    return;
19510                }
19511                mContext.enforceCallingOrSelfPermission(
19512                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19513            }
19514
19515            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19516            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19517                    + userId + ":");
19518            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19519            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19520            scheduleWritePackageRestrictionsLocked(userId);
19521            postPreferredActivityChangedBroadcast(userId);
19522        }
19523    }
19524
19525    private void postPreferredActivityChangedBroadcast(int userId) {
19526        mHandler.post(() -> {
19527            final IActivityManager am = ActivityManager.getService();
19528            if (am == null) {
19529                return;
19530            }
19531
19532            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19533            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19534            try {
19535                am.broadcastIntent(null, intent, null, null,
19536                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19537                        null, false, false, userId);
19538            } catch (RemoteException e) {
19539            }
19540        });
19541    }
19542
19543    @Override
19544    public void replacePreferredActivity(IntentFilter filter, int match,
19545            ComponentName[] set, ComponentName activity, int userId) {
19546        if (filter.countActions() != 1) {
19547            throw new IllegalArgumentException(
19548                    "replacePreferredActivity expects filter to have only 1 action.");
19549        }
19550        if (filter.countDataAuthorities() != 0
19551                || filter.countDataPaths() != 0
19552                || filter.countDataSchemes() > 1
19553                || filter.countDataTypes() != 0) {
19554            throw new IllegalArgumentException(
19555                    "replacePreferredActivity expects filter to have no data authorities, " +
19556                    "paths, or types; and at most one scheme.");
19557        }
19558
19559        final int callingUid = Binder.getCallingUid();
19560        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19561                true /* requireFullPermission */, false /* checkShell */,
19562                "replace preferred activity");
19563        synchronized (mPackages) {
19564            if (mContext.checkCallingOrSelfPermission(
19565                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19566                    != PackageManager.PERMISSION_GRANTED) {
19567                if (getUidTargetSdkVersionLockedLPr(callingUid)
19568                        < Build.VERSION_CODES.FROYO) {
19569                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19570                            + Binder.getCallingUid());
19571                    return;
19572                }
19573                mContext.enforceCallingOrSelfPermission(
19574                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19575            }
19576
19577            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19578            if (pir != null) {
19579                // Get all of the existing entries that exactly match this filter.
19580                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19581                if (existing != null && existing.size() == 1) {
19582                    PreferredActivity cur = existing.get(0);
19583                    if (DEBUG_PREFERRED) {
19584                        Slog.i(TAG, "Checking replace of preferred:");
19585                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19586                        if (!cur.mPref.mAlways) {
19587                            Slog.i(TAG, "  -- CUR; not mAlways!");
19588                        } else {
19589                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19590                            Slog.i(TAG, "  -- CUR: mSet="
19591                                    + Arrays.toString(cur.mPref.mSetComponents));
19592                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19593                            Slog.i(TAG, "  -- NEW: mMatch="
19594                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19595                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19596                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19597                        }
19598                    }
19599                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19600                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19601                            && cur.mPref.sameSet(set)) {
19602                        // Setting the preferred activity to what it happens to be already
19603                        if (DEBUG_PREFERRED) {
19604                            Slog.i(TAG, "Replacing with same preferred activity "
19605                                    + cur.mPref.mShortComponent + " for user "
19606                                    + userId + ":");
19607                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19608                        }
19609                        return;
19610                    }
19611                }
19612
19613                if (existing != null) {
19614                    if (DEBUG_PREFERRED) {
19615                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19616                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19617                    }
19618                    for (int i = 0; i < existing.size(); i++) {
19619                        PreferredActivity pa = existing.get(i);
19620                        if (DEBUG_PREFERRED) {
19621                            Slog.i(TAG, "Removing existing preferred activity "
19622                                    + pa.mPref.mComponent + ":");
19623                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19624                        }
19625                        pir.removeFilter(pa);
19626                    }
19627                }
19628            }
19629            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19630                    "Replacing preferred");
19631        }
19632    }
19633
19634    @Override
19635    public void clearPackagePreferredActivities(String packageName) {
19636        final int callingUid = Binder.getCallingUid();
19637        if (getInstantAppPackageName(callingUid) != null) {
19638            return;
19639        }
19640        // writer
19641        synchronized (mPackages) {
19642            PackageParser.Package pkg = mPackages.get(packageName);
19643            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19644                if (mContext.checkCallingOrSelfPermission(
19645                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19646                        != PackageManager.PERMISSION_GRANTED) {
19647                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19648                            < Build.VERSION_CODES.FROYO) {
19649                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19650                                + callingUid);
19651                        return;
19652                    }
19653                    mContext.enforceCallingOrSelfPermission(
19654                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19655                }
19656            }
19657            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19658            if (ps != null
19659                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19660                return;
19661            }
19662            int user = UserHandle.getCallingUserId();
19663            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19664                scheduleWritePackageRestrictionsLocked(user);
19665            }
19666        }
19667    }
19668
19669    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19670    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19671        ArrayList<PreferredActivity> removed = null;
19672        boolean changed = false;
19673        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19674            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19675            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19676            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19677                continue;
19678            }
19679            Iterator<PreferredActivity> it = pir.filterIterator();
19680            while (it.hasNext()) {
19681                PreferredActivity pa = it.next();
19682                // Mark entry for removal only if it matches the package name
19683                // and the entry is of type "always".
19684                if (packageName == null ||
19685                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19686                                && pa.mPref.mAlways)) {
19687                    if (removed == null) {
19688                        removed = new ArrayList<PreferredActivity>();
19689                    }
19690                    removed.add(pa);
19691                }
19692            }
19693            if (removed != null) {
19694                for (int j=0; j<removed.size(); j++) {
19695                    PreferredActivity pa = removed.get(j);
19696                    pir.removeFilter(pa);
19697                }
19698                changed = true;
19699            }
19700        }
19701        if (changed) {
19702            postPreferredActivityChangedBroadcast(userId);
19703        }
19704        return changed;
19705    }
19706
19707    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19708    private void clearIntentFilterVerificationsLPw(int userId) {
19709        final int packageCount = mPackages.size();
19710        for (int i = 0; i < packageCount; i++) {
19711            PackageParser.Package pkg = mPackages.valueAt(i);
19712            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19713        }
19714    }
19715
19716    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19717    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19718        if (userId == UserHandle.USER_ALL) {
19719            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19720                    sUserManager.getUserIds())) {
19721                for (int oneUserId : sUserManager.getUserIds()) {
19722                    scheduleWritePackageRestrictionsLocked(oneUserId);
19723                }
19724            }
19725        } else {
19726            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19727                scheduleWritePackageRestrictionsLocked(userId);
19728            }
19729        }
19730    }
19731
19732    /** Clears state for all users, and touches intent filter verification policy */
19733    void clearDefaultBrowserIfNeeded(String packageName) {
19734        for (int oneUserId : sUserManager.getUserIds()) {
19735            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19736        }
19737    }
19738
19739    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19740        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19741        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19742            if (packageName.equals(defaultBrowserPackageName)) {
19743                setDefaultBrowserPackageName(null, userId);
19744            }
19745        }
19746    }
19747
19748    @Override
19749    public void resetApplicationPreferences(int userId) {
19750        mContext.enforceCallingOrSelfPermission(
19751                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19752        final long identity = Binder.clearCallingIdentity();
19753        // writer
19754        try {
19755            synchronized (mPackages) {
19756                clearPackagePreferredActivitiesLPw(null, userId);
19757                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19758                // TODO: We have to reset the default SMS and Phone. This requires
19759                // significant refactoring to keep all default apps in the package
19760                // manager (cleaner but more work) or have the services provide
19761                // callbacks to the package manager to request a default app reset.
19762                applyFactoryDefaultBrowserLPw(userId);
19763                clearIntentFilterVerificationsLPw(userId);
19764                primeDomainVerificationsLPw(userId);
19765                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19766                scheduleWritePackageRestrictionsLocked(userId);
19767            }
19768            resetNetworkPolicies(userId);
19769        } finally {
19770            Binder.restoreCallingIdentity(identity);
19771        }
19772    }
19773
19774    @Override
19775    public int getPreferredActivities(List<IntentFilter> outFilters,
19776            List<ComponentName> outActivities, String packageName) {
19777        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19778            return 0;
19779        }
19780        int num = 0;
19781        final int userId = UserHandle.getCallingUserId();
19782        // reader
19783        synchronized (mPackages) {
19784            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19785            if (pir != null) {
19786                final Iterator<PreferredActivity> it = pir.filterIterator();
19787                while (it.hasNext()) {
19788                    final PreferredActivity pa = it.next();
19789                    if (packageName == null
19790                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19791                                    && pa.mPref.mAlways)) {
19792                        if (outFilters != null) {
19793                            outFilters.add(new IntentFilter(pa));
19794                        }
19795                        if (outActivities != null) {
19796                            outActivities.add(pa.mPref.mComponent);
19797                        }
19798                    }
19799                }
19800            }
19801        }
19802
19803        return num;
19804    }
19805
19806    @Override
19807    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19808            int userId) {
19809        int callingUid = Binder.getCallingUid();
19810        if (callingUid != Process.SYSTEM_UID) {
19811            throw new SecurityException(
19812                    "addPersistentPreferredActivity can only be run by the system");
19813        }
19814        if (filter.countActions() == 0) {
19815            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19816            return;
19817        }
19818        synchronized (mPackages) {
19819            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19820                    ":");
19821            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19822            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19823                    new PersistentPreferredActivity(filter, activity));
19824            scheduleWritePackageRestrictionsLocked(userId);
19825            postPreferredActivityChangedBroadcast(userId);
19826        }
19827    }
19828
19829    @Override
19830    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19831        int callingUid = Binder.getCallingUid();
19832        if (callingUid != Process.SYSTEM_UID) {
19833            throw new SecurityException(
19834                    "clearPackagePersistentPreferredActivities can only be run by the system");
19835        }
19836        ArrayList<PersistentPreferredActivity> removed = null;
19837        boolean changed = false;
19838        synchronized (mPackages) {
19839            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19840                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19841                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19842                        .valueAt(i);
19843                if (userId != thisUserId) {
19844                    continue;
19845                }
19846                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19847                while (it.hasNext()) {
19848                    PersistentPreferredActivity ppa = it.next();
19849                    // Mark entry for removal only if it matches the package name.
19850                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19851                        if (removed == null) {
19852                            removed = new ArrayList<PersistentPreferredActivity>();
19853                        }
19854                        removed.add(ppa);
19855                    }
19856                }
19857                if (removed != null) {
19858                    for (int j=0; j<removed.size(); j++) {
19859                        PersistentPreferredActivity ppa = removed.get(j);
19860                        ppir.removeFilter(ppa);
19861                    }
19862                    changed = true;
19863                }
19864            }
19865
19866            if (changed) {
19867                scheduleWritePackageRestrictionsLocked(userId);
19868                postPreferredActivityChangedBroadcast(userId);
19869            }
19870        }
19871    }
19872
19873    /**
19874     * Common machinery for picking apart a restored XML blob and passing
19875     * it to a caller-supplied functor to be applied to the running system.
19876     */
19877    private void restoreFromXml(XmlPullParser parser, int userId,
19878            String expectedStartTag, BlobXmlRestorer functor)
19879            throws IOException, XmlPullParserException {
19880        int type;
19881        while ((type = parser.next()) != XmlPullParser.START_TAG
19882                && type != XmlPullParser.END_DOCUMENT) {
19883        }
19884        if (type != XmlPullParser.START_TAG) {
19885            // oops didn't find a start tag?!
19886            if (DEBUG_BACKUP) {
19887                Slog.e(TAG, "Didn't find start tag during restore");
19888            }
19889            return;
19890        }
19891Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19892        // this is supposed to be TAG_PREFERRED_BACKUP
19893        if (!expectedStartTag.equals(parser.getName())) {
19894            if (DEBUG_BACKUP) {
19895                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19896            }
19897            return;
19898        }
19899
19900        // skip interfering stuff, then we're aligned with the backing implementation
19901        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19902Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19903        functor.apply(parser, userId);
19904    }
19905
19906    private interface BlobXmlRestorer {
19907        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19908    }
19909
19910    /**
19911     * Non-Binder method, support for the backup/restore mechanism: write the
19912     * full set of preferred activities in its canonical XML format.  Returns the
19913     * XML output as a byte array, or null if there is none.
19914     */
19915    @Override
19916    public byte[] getPreferredActivityBackup(int userId) {
19917        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19918            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19919        }
19920
19921        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19922        try {
19923            final XmlSerializer serializer = new FastXmlSerializer();
19924            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19925            serializer.startDocument(null, true);
19926            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19927
19928            synchronized (mPackages) {
19929                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19930            }
19931
19932            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19933            serializer.endDocument();
19934            serializer.flush();
19935        } catch (Exception e) {
19936            if (DEBUG_BACKUP) {
19937                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19938            }
19939            return null;
19940        }
19941
19942        return dataStream.toByteArray();
19943    }
19944
19945    @Override
19946    public void restorePreferredActivities(byte[] backup, int userId) {
19947        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19948            throw new SecurityException("Only the system may call restorePreferredActivities()");
19949        }
19950
19951        try {
19952            final XmlPullParser parser = Xml.newPullParser();
19953            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19954            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19955                    new BlobXmlRestorer() {
19956                        @Override
19957                        public void apply(XmlPullParser parser, int userId)
19958                                throws XmlPullParserException, IOException {
19959                            synchronized (mPackages) {
19960                                mSettings.readPreferredActivitiesLPw(parser, userId);
19961                            }
19962                        }
19963                    } );
19964        } catch (Exception e) {
19965            if (DEBUG_BACKUP) {
19966                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19967            }
19968        }
19969    }
19970
19971    /**
19972     * Non-Binder method, support for the backup/restore mechanism: write the
19973     * default browser (etc) settings in its canonical XML format.  Returns the default
19974     * browser XML representation as a byte array, or null if there is none.
19975     */
19976    @Override
19977    public byte[] getDefaultAppsBackup(int userId) {
19978        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19979            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19980        }
19981
19982        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19983        try {
19984            final XmlSerializer serializer = new FastXmlSerializer();
19985            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19986            serializer.startDocument(null, true);
19987            serializer.startTag(null, TAG_DEFAULT_APPS);
19988
19989            synchronized (mPackages) {
19990                mSettings.writeDefaultAppsLPr(serializer, userId);
19991            }
19992
19993            serializer.endTag(null, TAG_DEFAULT_APPS);
19994            serializer.endDocument();
19995            serializer.flush();
19996        } catch (Exception e) {
19997            if (DEBUG_BACKUP) {
19998                Slog.e(TAG, "Unable to write default apps for backup", e);
19999            }
20000            return null;
20001        }
20002
20003        return dataStream.toByteArray();
20004    }
20005
20006    @Override
20007    public void restoreDefaultApps(byte[] backup, int userId) {
20008        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20009            throw new SecurityException("Only the system may call restoreDefaultApps()");
20010        }
20011
20012        try {
20013            final XmlPullParser parser = Xml.newPullParser();
20014            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20015            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20016                    new BlobXmlRestorer() {
20017                        @Override
20018                        public void apply(XmlPullParser parser, int userId)
20019                                throws XmlPullParserException, IOException {
20020                            synchronized (mPackages) {
20021                                mSettings.readDefaultAppsLPw(parser, userId);
20022                            }
20023                        }
20024                    } );
20025        } catch (Exception e) {
20026            if (DEBUG_BACKUP) {
20027                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20028            }
20029        }
20030    }
20031
20032    @Override
20033    public byte[] getIntentFilterVerificationBackup(int userId) {
20034        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20035            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20036        }
20037
20038        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20039        try {
20040            final XmlSerializer serializer = new FastXmlSerializer();
20041            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20042            serializer.startDocument(null, true);
20043            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20044
20045            synchronized (mPackages) {
20046                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20047            }
20048
20049            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20050            serializer.endDocument();
20051            serializer.flush();
20052        } catch (Exception e) {
20053            if (DEBUG_BACKUP) {
20054                Slog.e(TAG, "Unable to write default apps for backup", e);
20055            }
20056            return null;
20057        }
20058
20059        return dataStream.toByteArray();
20060    }
20061
20062    @Override
20063    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20064        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20065            throw new SecurityException("Only the system may call restorePreferredActivities()");
20066        }
20067
20068        try {
20069            final XmlPullParser parser = Xml.newPullParser();
20070            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20071            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20072                    new BlobXmlRestorer() {
20073                        @Override
20074                        public void apply(XmlPullParser parser, int userId)
20075                                throws XmlPullParserException, IOException {
20076                            synchronized (mPackages) {
20077                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20078                                mSettings.writeLPr();
20079                            }
20080                        }
20081                    } );
20082        } catch (Exception e) {
20083            if (DEBUG_BACKUP) {
20084                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20085            }
20086        }
20087    }
20088
20089    @Override
20090    public byte[] getPermissionGrantBackup(int userId) {
20091        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20092            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20093        }
20094
20095        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20096        try {
20097            final XmlSerializer serializer = new FastXmlSerializer();
20098            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20099            serializer.startDocument(null, true);
20100            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20101
20102            synchronized (mPackages) {
20103                serializeRuntimePermissionGrantsLPr(serializer, userId);
20104            }
20105
20106            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20107            serializer.endDocument();
20108            serializer.flush();
20109        } catch (Exception e) {
20110            if (DEBUG_BACKUP) {
20111                Slog.e(TAG, "Unable to write default apps for backup", e);
20112            }
20113            return null;
20114        }
20115
20116        return dataStream.toByteArray();
20117    }
20118
20119    @Override
20120    public void restorePermissionGrants(byte[] backup, int userId) {
20121        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20122            throw new SecurityException("Only the system may call restorePermissionGrants()");
20123        }
20124
20125        try {
20126            final XmlPullParser parser = Xml.newPullParser();
20127            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20128            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20129                    new BlobXmlRestorer() {
20130                        @Override
20131                        public void apply(XmlPullParser parser, int userId)
20132                                throws XmlPullParserException, IOException {
20133                            synchronized (mPackages) {
20134                                processRestoredPermissionGrantsLPr(parser, userId);
20135                            }
20136                        }
20137                    } );
20138        } catch (Exception e) {
20139            if (DEBUG_BACKUP) {
20140                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20141            }
20142        }
20143    }
20144
20145    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20146            throws IOException {
20147        serializer.startTag(null, TAG_ALL_GRANTS);
20148
20149        final int N = mSettings.mPackages.size();
20150        for (int i = 0; i < N; i++) {
20151            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20152            boolean pkgGrantsKnown = false;
20153
20154            PermissionsState packagePerms = ps.getPermissionsState();
20155
20156            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20157                final int grantFlags = state.getFlags();
20158                // only look at grants that are not system/policy fixed
20159                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20160                    final boolean isGranted = state.isGranted();
20161                    // And only back up the user-twiddled state bits
20162                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20163                        final String packageName = mSettings.mPackages.keyAt(i);
20164                        if (!pkgGrantsKnown) {
20165                            serializer.startTag(null, TAG_GRANT);
20166                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20167                            pkgGrantsKnown = true;
20168                        }
20169
20170                        final boolean userSet =
20171                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20172                        final boolean userFixed =
20173                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20174                        final boolean revoke =
20175                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20176
20177                        serializer.startTag(null, TAG_PERMISSION);
20178                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20179                        if (isGranted) {
20180                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20181                        }
20182                        if (userSet) {
20183                            serializer.attribute(null, ATTR_USER_SET, "true");
20184                        }
20185                        if (userFixed) {
20186                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20187                        }
20188                        if (revoke) {
20189                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20190                        }
20191                        serializer.endTag(null, TAG_PERMISSION);
20192                    }
20193                }
20194            }
20195
20196            if (pkgGrantsKnown) {
20197                serializer.endTag(null, TAG_GRANT);
20198            }
20199        }
20200
20201        serializer.endTag(null, TAG_ALL_GRANTS);
20202    }
20203
20204    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20205            throws XmlPullParserException, IOException {
20206        String pkgName = null;
20207        int outerDepth = parser.getDepth();
20208        int type;
20209        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20210                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20211            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20212                continue;
20213            }
20214
20215            final String tagName = parser.getName();
20216            if (tagName.equals(TAG_GRANT)) {
20217                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20218                if (DEBUG_BACKUP) {
20219                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20220                }
20221            } else if (tagName.equals(TAG_PERMISSION)) {
20222
20223                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20224                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20225
20226                int newFlagSet = 0;
20227                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20228                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20229                }
20230                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20231                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20232                }
20233                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20234                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20235                }
20236                if (DEBUG_BACKUP) {
20237                    Slog.v(TAG, "  + Restoring grant:"
20238                            + " pkg=" + pkgName
20239                            + " perm=" + permName
20240                            + " granted=" + isGranted
20241                            + " bits=0x" + Integer.toHexString(newFlagSet));
20242                }
20243                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20244                if (ps != null) {
20245                    // Already installed so we apply the grant immediately
20246                    if (DEBUG_BACKUP) {
20247                        Slog.v(TAG, "        + already installed; applying");
20248                    }
20249                    PermissionsState perms = ps.getPermissionsState();
20250                    BasePermission bp =
20251                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20252                    if (bp != null) {
20253                        if (isGranted) {
20254                            perms.grantRuntimePermission(bp, userId);
20255                        }
20256                        if (newFlagSet != 0) {
20257                            perms.updatePermissionFlags(
20258                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20259                        }
20260                    }
20261                } else {
20262                    // Need to wait for post-restore install to apply the grant
20263                    if (DEBUG_BACKUP) {
20264                        Slog.v(TAG, "        - not yet installed; saving for later");
20265                    }
20266                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20267                            isGranted, newFlagSet, userId);
20268                }
20269            } else {
20270                PackageManagerService.reportSettingsProblem(Log.WARN,
20271                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20272                XmlUtils.skipCurrentTag(parser);
20273            }
20274        }
20275
20276        scheduleWriteSettingsLocked();
20277        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20278    }
20279
20280    @Override
20281    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20282            int sourceUserId, int targetUserId, int flags) {
20283        mContext.enforceCallingOrSelfPermission(
20284                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20285        int callingUid = Binder.getCallingUid();
20286        enforceOwnerRights(ownerPackage, callingUid);
20287        PackageManagerServiceUtils.enforceShellRestriction(
20288                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20289        if (intentFilter.countActions() == 0) {
20290            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20291            return;
20292        }
20293        synchronized (mPackages) {
20294            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20295                    ownerPackage, targetUserId, flags);
20296            CrossProfileIntentResolver resolver =
20297                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20298            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20299            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20300            if (existing != null) {
20301                int size = existing.size();
20302                for (int i = 0; i < size; i++) {
20303                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20304                        return;
20305                    }
20306                }
20307            }
20308            resolver.addFilter(newFilter);
20309            scheduleWritePackageRestrictionsLocked(sourceUserId);
20310        }
20311    }
20312
20313    @Override
20314    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20315        mContext.enforceCallingOrSelfPermission(
20316                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20317        final int callingUid = Binder.getCallingUid();
20318        enforceOwnerRights(ownerPackage, callingUid);
20319        PackageManagerServiceUtils.enforceShellRestriction(
20320                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20321        synchronized (mPackages) {
20322            CrossProfileIntentResolver resolver =
20323                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20324            ArraySet<CrossProfileIntentFilter> set =
20325                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20326            for (CrossProfileIntentFilter filter : set) {
20327                if (filter.getOwnerPackage().equals(ownerPackage)) {
20328                    resolver.removeFilter(filter);
20329                }
20330            }
20331            scheduleWritePackageRestrictionsLocked(sourceUserId);
20332        }
20333    }
20334
20335    // Enforcing that callingUid is owning pkg on userId
20336    private void enforceOwnerRights(String pkg, int callingUid) {
20337        // The system owns everything.
20338        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20339            return;
20340        }
20341        final int callingUserId = UserHandle.getUserId(callingUid);
20342        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20343        if (pi == null) {
20344            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20345                    + callingUserId);
20346        }
20347        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20348            throw new SecurityException("Calling uid " + callingUid
20349                    + " does not own package " + pkg);
20350        }
20351    }
20352
20353    @Override
20354    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20355        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20356            return null;
20357        }
20358        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20359    }
20360
20361    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20362        UserManagerService ums = UserManagerService.getInstance();
20363        if (ums != null) {
20364            final UserInfo parent = ums.getProfileParent(userId);
20365            final int launcherUid = (parent != null) ? parent.id : userId;
20366            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20367            if (launcherComponent != null) {
20368                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20369                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20370                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20371                        .setPackage(launcherComponent.getPackageName());
20372                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20373            }
20374        }
20375    }
20376
20377    /**
20378     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20379     * then reports the most likely home activity or null if there are more than one.
20380     */
20381    private ComponentName getDefaultHomeActivity(int userId) {
20382        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20383        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20384        if (cn != null) {
20385            return cn;
20386        }
20387
20388        // Find the launcher with the highest priority and return that component if there are no
20389        // other home activity with the same priority.
20390        int lastPriority = Integer.MIN_VALUE;
20391        ComponentName lastComponent = null;
20392        final int size = allHomeCandidates.size();
20393        for (int i = 0; i < size; i++) {
20394            final ResolveInfo ri = allHomeCandidates.get(i);
20395            if (ri.priority > lastPriority) {
20396                lastComponent = ri.activityInfo.getComponentName();
20397                lastPriority = ri.priority;
20398            } else if (ri.priority == lastPriority) {
20399                // Two components found with same priority.
20400                lastComponent = null;
20401            }
20402        }
20403        return lastComponent;
20404    }
20405
20406    private Intent getHomeIntent() {
20407        Intent intent = new Intent(Intent.ACTION_MAIN);
20408        intent.addCategory(Intent.CATEGORY_HOME);
20409        intent.addCategory(Intent.CATEGORY_DEFAULT);
20410        return intent;
20411    }
20412
20413    private IntentFilter getHomeFilter() {
20414        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20415        filter.addCategory(Intent.CATEGORY_HOME);
20416        filter.addCategory(Intent.CATEGORY_DEFAULT);
20417        return filter;
20418    }
20419
20420    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20421            int userId) {
20422        Intent intent  = getHomeIntent();
20423        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20424                PackageManager.GET_META_DATA, userId);
20425        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20426                true, false, false, userId);
20427
20428        allHomeCandidates.clear();
20429        if (list != null) {
20430            for (ResolveInfo ri : list) {
20431                allHomeCandidates.add(ri);
20432            }
20433        }
20434        return (preferred == null || preferred.activityInfo == null)
20435                ? null
20436                : new ComponentName(preferred.activityInfo.packageName,
20437                        preferred.activityInfo.name);
20438    }
20439
20440    @Override
20441    public void setHomeActivity(ComponentName comp, int userId) {
20442        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20443            return;
20444        }
20445        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20446        getHomeActivitiesAsUser(homeActivities, userId);
20447
20448        boolean found = false;
20449
20450        final int size = homeActivities.size();
20451        final ComponentName[] set = new ComponentName[size];
20452        for (int i = 0; i < size; i++) {
20453            final ResolveInfo candidate = homeActivities.get(i);
20454            final ActivityInfo info = candidate.activityInfo;
20455            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20456            set[i] = activityName;
20457            if (!found && activityName.equals(comp)) {
20458                found = true;
20459            }
20460        }
20461        if (!found) {
20462            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20463                    + userId);
20464        }
20465        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20466                set, comp, userId);
20467    }
20468
20469    private @Nullable String getSetupWizardPackageName() {
20470        final Intent intent = new Intent(Intent.ACTION_MAIN);
20471        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20472
20473        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20474                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20475                        | MATCH_DISABLED_COMPONENTS,
20476                UserHandle.myUserId());
20477        if (matches.size() == 1) {
20478            return matches.get(0).getComponentInfo().packageName;
20479        } else {
20480            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20481                    + ": matches=" + matches);
20482            return null;
20483        }
20484    }
20485
20486    private @Nullable String getStorageManagerPackageName() {
20487        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20488
20489        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20490                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20491                        | MATCH_DISABLED_COMPONENTS,
20492                UserHandle.myUserId());
20493        if (matches.size() == 1) {
20494            return matches.get(0).getComponentInfo().packageName;
20495        } else {
20496            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20497                    + matches.size() + ": matches=" + matches);
20498            return null;
20499        }
20500    }
20501
20502    @Override
20503    public String getSystemTextClassifierPackageName() {
20504        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20505    }
20506
20507    @Override
20508    public void setApplicationEnabledSetting(String appPackageName,
20509            int newState, int flags, int userId, String callingPackage) {
20510        if (!sUserManager.exists(userId)) return;
20511        if (callingPackage == null) {
20512            callingPackage = Integer.toString(Binder.getCallingUid());
20513        }
20514        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20515    }
20516
20517    @Override
20518    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20519        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20520        synchronized (mPackages) {
20521            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20522            if (pkgSetting != null) {
20523                pkgSetting.setUpdateAvailable(updateAvailable);
20524            }
20525        }
20526    }
20527
20528    @Override
20529    public void setComponentEnabledSetting(ComponentName componentName,
20530            int newState, int flags, int userId) {
20531        if (!sUserManager.exists(userId)) return;
20532        setEnabledSetting(componentName.getPackageName(),
20533                componentName.getClassName(), newState, flags, userId, null);
20534    }
20535
20536    private void setEnabledSetting(final String packageName, String className, int newState,
20537            final int flags, int userId, String callingPackage) {
20538        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20539              || newState == COMPONENT_ENABLED_STATE_ENABLED
20540              || newState == COMPONENT_ENABLED_STATE_DISABLED
20541              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20542              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20543            throw new IllegalArgumentException("Invalid new component state: "
20544                    + newState);
20545        }
20546        PackageSetting pkgSetting;
20547        final int callingUid = Binder.getCallingUid();
20548        final int permission;
20549        if (callingUid == Process.SYSTEM_UID) {
20550            permission = PackageManager.PERMISSION_GRANTED;
20551        } else {
20552            permission = mContext.checkCallingOrSelfPermission(
20553                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20554        }
20555        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20556                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20557        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20558        boolean sendNow = false;
20559        boolean isApp = (className == null);
20560        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20561        String componentName = isApp ? packageName : className;
20562        int packageUid = -1;
20563        ArrayList<String> components;
20564
20565        // reader
20566        synchronized (mPackages) {
20567            pkgSetting = mSettings.mPackages.get(packageName);
20568            if (pkgSetting == null) {
20569                if (!isCallerInstantApp) {
20570                    if (className == null) {
20571                        throw new IllegalArgumentException("Unknown package: " + packageName);
20572                    }
20573                    throw new IllegalArgumentException(
20574                            "Unknown component: " + packageName + "/" + className);
20575                } else {
20576                    // throw SecurityException to prevent leaking package information
20577                    throw new SecurityException(
20578                            "Attempt to change component state; "
20579                            + "pid=" + Binder.getCallingPid()
20580                            + ", uid=" + callingUid
20581                            + (className == null
20582                                    ? ", package=" + packageName
20583                                    : ", component=" + packageName + "/" + className));
20584                }
20585            }
20586        }
20587
20588        // Limit who can change which apps
20589        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20590            // Don't allow apps that don't have permission to modify other apps
20591            if (!allowedByPermission
20592                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20593                throw new SecurityException(
20594                        "Attempt to change component state; "
20595                        + "pid=" + Binder.getCallingPid()
20596                        + ", uid=" + callingUid
20597                        + (className == null
20598                                ? ", package=" + packageName
20599                                : ", component=" + packageName + "/" + className));
20600            }
20601            // Don't allow changing protected packages.
20602            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20603                throw new SecurityException("Cannot disable a protected package: " + packageName);
20604            }
20605        }
20606
20607        synchronized (mPackages) {
20608            if (callingUid == Process.SHELL_UID
20609                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20610                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20611                // unless it is a test package.
20612                int oldState = pkgSetting.getEnabled(userId);
20613                if (className == null
20614                        &&
20615                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20616                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20617                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20618                        &&
20619                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20620                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20621                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20622                    // ok
20623                } else {
20624                    throw new SecurityException(
20625                            "Shell cannot change component state for " + packageName + "/"
20626                                    + className + " to " + newState);
20627                }
20628            }
20629        }
20630        if (className == null) {
20631            // We're dealing with an application/package level state change
20632            synchronized (mPackages) {
20633                if (pkgSetting.getEnabled(userId) == newState) {
20634                    // Nothing to do
20635                    return;
20636                }
20637            }
20638            // If we're enabling a system stub, there's a little more work to do.
20639            // Prior to enabling the package, we need to decompress the APK(s) to the
20640            // data partition and then replace the version on the system partition.
20641            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20642            final boolean isSystemStub = deletedPkg.isStub
20643                    && deletedPkg.isSystem();
20644            if (isSystemStub
20645                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20646                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20647                final File codePath = decompressPackage(deletedPkg);
20648                if (codePath == null) {
20649                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20650                    return;
20651                }
20652                // TODO remove direct parsing of the package object during internal cleanup
20653                // of scan package
20654                // We need to call parse directly here for no other reason than we need
20655                // the new package in order to disable the old one [we use the information
20656                // for some internal optimization to optionally create a new package setting
20657                // object on replace]. However, we can't get the package from the scan
20658                // because the scan modifies live structures and we need to remove the
20659                // old [system] package from the system before a scan can be attempted.
20660                // Once scan is indempotent we can remove this parse and use the package
20661                // object we scanned, prior to adding it to package settings.
20662                final PackageParser pp = new PackageParser();
20663                pp.setSeparateProcesses(mSeparateProcesses);
20664                pp.setDisplayMetrics(mMetrics);
20665                pp.setCallback(mPackageParserCallback);
20666                final PackageParser.Package tmpPkg;
20667                try {
20668                    final @ParseFlags int parseFlags = mDefParseFlags
20669                            | PackageParser.PARSE_MUST_BE_APK
20670                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20671                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20672                } catch (PackageParserException e) {
20673                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20674                    return;
20675                }
20676                synchronized (mInstallLock) {
20677                    // Disable the stub and remove any package entries
20678                    removePackageLI(deletedPkg, true);
20679                    synchronized (mPackages) {
20680                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20681                    }
20682                    final PackageParser.Package pkg;
20683                    try (PackageFreezer freezer =
20684                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20685                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20686                                | PackageParser.PARSE_ENFORCE_CODE;
20687                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20688                                0 /*currentTime*/, null /*user*/);
20689                        prepareAppDataAfterInstallLIF(pkg);
20690                        synchronized (mPackages) {
20691                            try {
20692                                updateSharedLibrariesLPr(pkg, null);
20693                            } catch (PackageManagerException e) {
20694                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20695                            }
20696                            mPermissionManager.updatePermissions(
20697                                    pkg.packageName, pkg, true, mPackages.values(),
20698                                    mPermissionCallback);
20699                            mSettings.writeLPr();
20700                        }
20701                    } catch (PackageManagerException e) {
20702                        // Whoops! Something went wrong; try to roll back to the stub
20703                        Slog.w(TAG, "Failed to install compressed system package:"
20704                                + pkgSetting.name, e);
20705                        // Remove the failed install
20706                        removeCodePathLI(codePath);
20707
20708                        // Install the system package
20709                        try (PackageFreezer freezer =
20710                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20711                            synchronized (mPackages) {
20712                                // NOTE: The system package always needs to be enabled; even
20713                                // if it's for a compressed stub. If we don't, installing the
20714                                // system package fails during scan [scanning checks the disabled
20715                                // packages]. We will reverse this later, after we've "installed"
20716                                // the stub.
20717                                // This leaves us in a fragile state; the stub should never be
20718                                // enabled, so, cross your fingers and hope nothing goes wrong
20719                                // until we can disable the package later.
20720                                enableSystemPackageLPw(deletedPkg);
20721                            }
20722                            installPackageFromSystemLIF(deletedPkg.codePath,
20723                                    false /*isPrivileged*/, null /*allUserHandles*/,
20724                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20725                                    true /*writeSettings*/);
20726                        } catch (PackageManagerException pme) {
20727                            Slog.w(TAG, "Failed to restore system package:"
20728                                    + deletedPkg.packageName, pme);
20729                        } finally {
20730                            synchronized (mPackages) {
20731                                mSettings.disableSystemPackageLPw(
20732                                        deletedPkg.packageName, true /*replaced*/);
20733                                mSettings.writeLPr();
20734                            }
20735                        }
20736                        return;
20737                    }
20738                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20739                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20740                    mDexManager.notifyPackageUpdated(pkg.packageName,
20741                            pkg.baseCodePath, pkg.splitCodePaths);
20742                }
20743            }
20744            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20745                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20746                // Don't care about who enables an app.
20747                callingPackage = null;
20748            }
20749            synchronized (mPackages) {
20750                pkgSetting.setEnabled(newState, userId, callingPackage);
20751            }
20752        } else {
20753            synchronized (mPackages) {
20754                // We're dealing with a component level state change
20755                // First, verify that this is a valid class name.
20756                PackageParser.Package pkg = pkgSetting.pkg;
20757                if (pkg == null || !pkg.hasComponentClassName(className)) {
20758                    if (pkg != null &&
20759                            pkg.applicationInfo.targetSdkVersion >=
20760                                    Build.VERSION_CODES.JELLY_BEAN) {
20761                        throw new IllegalArgumentException("Component class " + className
20762                                + " does not exist in " + packageName);
20763                    } else {
20764                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20765                                + className + " does not exist in " + packageName);
20766                    }
20767                }
20768                switch (newState) {
20769                    case COMPONENT_ENABLED_STATE_ENABLED:
20770                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20771                            return;
20772                        }
20773                        break;
20774                    case COMPONENT_ENABLED_STATE_DISABLED:
20775                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20776                            return;
20777                        }
20778                        break;
20779                    case COMPONENT_ENABLED_STATE_DEFAULT:
20780                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20781                            return;
20782                        }
20783                        break;
20784                    default:
20785                        Slog.e(TAG, "Invalid new component state: " + newState);
20786                        return;
20787                }
20788            }
20789        }
20790        synchronized (mPackages) {
20791            scheduleWritePackageRestrictionsLocked(userId);
20792            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20793            final long callingId = Binder.clearCallingIdentity();
20794            try {
20795                updateInstantAppInstallerLocked(packageName);
20796            } finally {
20797                Binder.restoreCallingIdentity(callingId);
20798            }
20799            components = mPendingBroadcasts.get(userId, packageName);
20800            final boolean newPackage = components == null;
20801            if (newPackage) {
20802                components = new ArrayList<String>();
20803            }
20804            if (!components.contains(componentName)) {
20805                components.add(componentName);
20806            }
20807            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20808                sendNow = true;
20809                // Purge entry from pending broadcast list if another one exists already
20810                // since we are sending one right away.
20811                mPendingBroadcasts.remove(userId, packageName);
20812            } else {
20813                if (newPackage) {
20814                    mPendingBroadcasts.put(userId, packageName, components);
20815                }
20816                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20817                    // Schedule a message
20818                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20819                }
20820            }
20821        }
20822
20823        long callingId = Binder.clearCallingIdentity();
20824        try {
20825            if (sendNow) {
20826                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20827                sendPackageChangedBroadcast(packageName,
20828                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20829            }
20830        } finally {
20831            Binder.restoreCallingIdentity(callingId);
20832        }
20833    }
20834
20835    @Override
20836    public void flushPackageRestrictionsAsUser(int userId) {
20837        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20838            return;
20839        }
20840        if (!sUserManager.exists(userId)) {
20841            return;
20842        }
20843        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20844                false /* checkShell */, "flushPackageRestrictions");
20845        synchronized (mPackages) {
20846            mSettings.writePackageRestrictionsLPr(userId);
20847            mDirtyUsers.remove(userId);
20848            if (mDirtyUsers.isEmpty()) {
20849                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20850            }
20851        }
20852    }
20853
20854    private void sendPackageChangedBroadcast(String packageName,
20855            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20856        if (DEBUG_INSTALL)
20857            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20858                    + componentNames);
20859        Bundle extras = new Bundle(4);
20860        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20861        String nameList[] = new String[componentNames.size()];
20862        componentNames.toArray(nameList);
20863        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20864        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20865        extras.putInt(Intent.EXTRA_UID, packageUid);
20866        // If this is not reporting a change of the overall package, then only send it
20867        // to registered receivers.  We don't want to launch a swath of apps for every
20868        // little component state change.
20869        final int flags = !componentNames.contains(packageName)
20870                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20871        final int userId = UserHandle.getUserId(packageUid);
20872        final boolean isInstantApp = isInstantApp(packageName, userId);
20873        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20874        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20875        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20876                userIds, instantUserIds);
20877    }
20878
20879    @Override
20880    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20881        if (!sUserManager.exists(userId)) return;
20882        final int callingUid = Binder.getCallingUid();
20883        if (getInstantAppPackageName(callingUid) != null) {
20884            return;
20885        }
20886        final int permission = mContext.checkCallingOrSelfPermission(
20887                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20888        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20889        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20890                true /* requireFullPermission */, true /* checkShell */, "stop package");
20891        // writer
20892        synchronized (mPackages) {
20893            final PackageSetting ps = mSettings.mPackages.get(packageName);
20894            if (!filterAppAccessLPr(ps, callingUid, userId)
20895                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20896                            allowedByPermission, callingUid, userId)) {
20897                scheduleWritePackageRestrictionsLocked(userId);
20898            }
20899        }
20900    }
20901
20902    @Override
20903    public String getInstallerPackageName(String packageName) {
20904        final int callingUid = Binder.getCallingUid();
20905        synchronized (mPackages) {
20906            final PackageSetting ps = mSettings.mPackages.get(packageName);
20907            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20908                return null;
20909            }
20910            return mSettings.getInstallerPackageNameLPr(packageName);
20911        }
20912    }
20913
20914    public boolean isOrphaned(String packageName) {
20915        // reader
20916        synchronized (mPackages) {
20917            return mSettings.isOrphaned(packageName);
20918        }
20919    }
20920
20921    @Override
20922    public int getApplicationEnabledSetting(String packageName, int userId) {
20923        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20924        int callingUid = Binder.getCallingUid();
20925        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20926                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20927        // reader
20928        synchronized (mPackages) {
20929            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20930                return COMPONENT_ENABLED_STATE_DISABLED;
20931            }
20932            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20933        }
20934    }
20935
20936    @Override
20937    public int getComponentEnabledSetting(ComponentName component, int userId) {
20938        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20939        int callingUid = Binder.getCallingUid();
20940        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20941                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20942        synchronized (mPackages) {
20943            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20944                    component, TYPE_UNKNOWN, userId)) {
20945                return COMPONENT_ENABLED_STATE_DISABLED;
20946            }
20947            return mSettings.getComponentEnabledSettingLPr(component, userId);
20948        }
20949    }
20950
20951    @Override
20952    public void enterSafeMode() {
20953        enforceSystemOrRoot("Only the system can request entering safe mode");
20954
20955        if (!mSystemReady) {
20956            mSafeMode = true;
20957        }
20958    }
20959
20960    @Override
20961    public void systemReady() {
20962        enforceSystemOrRoot("Only the system can claim the system is ready");
20963
20964        mSystemReady = true;
20965        final ContentResolver resolver = mContext.getContentResolver();
20966        ContentObserver co = new ContentObserver(mHandler) {
20967            @Override
20968            public void onChange(boolean selfChange) {
20969                mWebInstantAppsDisabled =
20970                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20971                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20972            }
20973        };
20974        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20975                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20976                false, co, UserHandle.USER_SYSTEM);
20977        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20978                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20979        co.onChange(true);
20980
20981        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20982        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20983        // it is done.
20984        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20985            @Override
20986            public void onChange(boolean selfChange) {
20987                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20988                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20989                        oobEnabled == 1 ? "true" : "false");
20990            }
20991        };
20992        mContext.getContentResolver().registerContentObserver(
20993                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20994                UserHandle.USER_SYSTEM);
20995        // At boot, restore the value from the setting, which persists across reboot.
20996        privAppOobObserver.onChange(true);
20997
20998        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20999        // disabled after already being started.
21000        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21001                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21002
21003        // Read the compatibilty setting when the system is ready.
21004        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21005                mContext.getContentResolver(),
21006                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21007        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21008        if (DEBUG_SETTINGS) {
21009            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21010        }
21011
21012        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21013
21014        synchronized (mPackages) {
21015            // Verify that all of the preferred activity components actually
21016            // exist.  It is possible for applications to be updated and at
21017            // that point remove a previously declared activity component that
21018            // had been set as a preferred activity.  We try to clean this up
21019            // the next time we encounter that preferred activity, but it is
21020            // possible for the user flow to never be able to return to that
21021            // situation so here we do a sanity check to make sure we haven't
21022            // left any junk around.
21023            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21024            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21025                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21026                removed.clear();
21027                for (PreferredActivity pa : pir.filterSet()) {
21028                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21029                        removed.add(pa);
21030                    }
21031                }
21032                if (removed.size() > 0) {
21033                    for (int r=0; r<removed.size(); r++) {
21034                        PreferredActivity pa = removed.get(r);
21035                        Slog.w(TAG, "Removing dangling preferred activity: "
21036                                + pa.mPref.mComponent);
21037                        pir.removeFilter(pa);
21038                    }
21039                    mSettings.writePackageRestrictionsLPr(
21040                            mSettings.mPreferredActivities.keyAt(i));
21041                }
21042            }
21043
21044            for (int userId : UserManagerService.getInstance().getUserIds()) {
21045                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21046                    grantPermissionsUserIds = ArrayUtils.appendInt(
21047                            grantPermissionsUserIds, userId);
21048                }
21049            }
21050        }
21051        sUserManager.systemReady();
21052        // If we upgraded grant all default permissions before kicking off.
21053        for (int userId : grantPermissionsUserIds) {
21054            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21055        }
21056
21057        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21058            // If we did not grant default permissions, we preload from this the
21059            // default permission exceptions lazily to ensure we don't hit the
21060            // disk on a new user creation.
21061            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21062        }
21063
21064        // Now that we've scanned all packages, and granted any default
21065        // permissions, ensure permissions are updated. Beware of dragons if you
21066        // try optimizing this.
21067        synchronized (mPackages) {
21068            mPermissionManager.updateAllPermissions(
21069                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21070                    mPermissionCallback);
21071        }
21072
21073        // Kick off any messages waiting for system ready
21074        if (mPostSystemReadyMessages != null) {
21075            for (Message msg : mPostSystemReadyMessages) {
21076                msg.sendToTarget();
21077            }
21078            mPostSystemReadyMessages = null;
21079        }
21080
21081        // Watch for external volumes that come and go over time
21082        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21083        storage.registerListener(mStorageListener);
21084
21085        mInstallerService.systemReady();
21086        mPackageDexOptimizer.systemReady();
21087
21088        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21089                StorageManagerInternal.class);
21090        StorageManagerInternal.addExternalStoragePolicy(
21091                new StorageManagerInternal.ExternalStorageMountPolicy() {
21092            @Override
21093            public int getMountMode(int uid, String packageName) {
21094                if (Process.isIsolated(uid)) {
21095                    return Zygote.MOUNT_EXTERNAL_NONE;
21096                }
21097                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21098                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21099                }
21100                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21101                    return Zygote.MOUNT_EXTERNAL_READ;
21102                }
21103                return Zygote.MOUNT_EXTERNAL_WRITE;
21104            }
21105
21106            @Override
21107            public boolean hasExternalStorage(int uid, String packageName) {
21108                return true;
21109            }
21110        });
21111
21112        // Now that we're mostly running, clean up stale users and apps
21113        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21114        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21115
21116        mPermissionManager.systemReady();
21117
21118        if (mInstantAppResolverConnection != null) {
21119            mContext.registerReceiver(new BroadcastReceiver() {
21120                @Override
21121                public void onReceive(Context context, Intent intent) {
21122                    mInstantAppResolverConnection.optimisticBind();
21123                    mContext.unregisterReceiver(this);
21124                }
21125            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21126        }
21127    }
21128
21129    public void waitForAppDataPrepared() {
21130        if (mPrepareAppDataFuture == null) {
21131            return;
21132        }
21133        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21134        mPrepareAppDataFuture = null;
21135    }
21136
21137    @Override
21138    public boolean isSafeMode() {
21139        // allow instant applications
21140        return mSafeMode;
21141    }
21142
21143    @Override
21144    public boolean hasSystemUidErrors() {
21145        // allow instant applications
21146        return mHasSystemUidErrors;
21147    }
21148
21149    static String arrayToString(int[] array) {
21150        StringBuffer buf = new StringBuffer(128);
21151        buf.append('[');
21152        if (array != null) {
21153            for (int i=0; i<array.length; i++) {
21154                if (i > 0) buf.append(", ");
21155                buf.append(array[i]);
21156            }
21157        }
21158        buf.append(']');
21159        return buf.toString();
21160    }
21161
21162    @Override
21163    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21164            FileDescriptor err, String[] args, ShellCallback callback,
21165            ResultReceiver resultReceiver) {
21166        (new PackageManagerShellCommand(this)).exec(
21167                this, in, out, err, args, callback, resultReceiver);
21168    }
21169
21170    @Override
21171    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21172        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21173
21174        DumpState dumpState = new DumpState();
21175        boolean fullPreferred = false;
21176        boolean checkin = false;
21177
21178        String packageName = null;
21179        ArraySet<String> permissionNames = null;
21180
21181        int opti = 0;
21182        while (opti < args.length) {
21183            String opt = args[opti];
21184            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21185                break;
21186            }
21187            opti++;
21188
21189            if ("-a".equals(opt)) {
21190                // Right now we only know how to print all.
21191            } else if ("-h".equals(opt)) {
21192                pw.println("Package manager dump options:");
21193                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21194                pw.println("    --checkin: dump for a checkin");
21195                pw.println("    -f: print details of intent filters");
21196                pw.println("    -h: print this help");
21197                pw.println("  cmd may be one of:");
21198                pw.println("    l[ibraries]: list known shared libraries");
21199                pw.println("    f[eatures]: list device features");
21200                pw.println("    k[eysets]: print known keysets");
21201                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21202                pw.println("    perm[issions]: dump permissions");
21203                pw.println("    permission [name ...]: dump declaration and use of given permission");
21204                pw.println("    pref[erred]: print preferred package settings");
21205                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21206                pw.println("    prov[iders]: dump content providers");
21207                pw.println("    p[ackages]: dump installed packages");
21208                pw.println("    s[hared-users]: dump shared user IDs");
21209                pw.println("    m[essages]: print collected runtime messages");
21210                pw.println("    v[erifiers]: print package verifier info");
21211                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21212                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21213                pw.println("    version: print database version info");
21214                pw.println("    write: write current settings now");
21215                pw.println("    installs: details about install sessions");
21216                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21217                pw.println("    dexopt: dump dexopt state");
21218                pw.println("    compiler-stats: dump compiler statistics");
21219                pw.println("    service-permissions: dump permissions required by services");
21220                pw.println("    <package.name>: info about given package");
21221                return;
21222            } else if ("--checkin".equals(opt)) {
21223                checkin = true;
21224            } else if ("-f".equals(opt)) {
21225                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21226            } else if ("--proto".equals(opt)) {
21227                dumpProto(fd);
21228                return;
21229            } else {
21230                pw.println("Unknown argument: " + opt + "; use -h for help");
21231            }
21232        }
21233
21234        // Is the caller requesting to dump a particular piece of data?
21235        if (opti < args.length) {
21236            String cmd = args[opti];
21237            opti++;
21238            // Is this a package name?
21239            if ("android".equals(cmd) || cmd.contains(".")) {
21240                packageName = cmd;
21241                // When dumping a single package, we always dump all of its
21242                // filter information since the amount of data will be reasonable.
21243                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21244            } else if ("check-permission".equals(cmd)) {
21245                if (opti >= args.length) {
21246                    pw.println("Error: check-permission missing permission argument");
21247                    return;
21248                }
21249                String perm = args[opti];
21250                opti++;
21251                if (opti >= args.length) {
21252                    pw.println("Error: check-permission missing package argument");
21253                    return;
21254                }
21255
21256                String pkg = args[opti];
21257                opti++;
21258                int user = UserHandle.getUserId(Binder.getCallingUid());
21259                if (opti < args.length) {
21260                    try {
21261                        user = Integer.parseInt(args[opti]);
21262                    } catch (NumberFormatException e) {
21263                        pw.println("Error: check-permission user argument is not a number: "
21264                                + args[opti]);
21265                        return;
21266                    }
21267                }
21268
21269                // Normalize package name to handle renamed packages and static libs
21270                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21271
21272                pw.println(checkPermission(perm, pkg, user));
21273                return;
21274            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21275                dumpState.setDump(DumpState.DUMP_LIBS);
21276            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21277                dumpState.setDump(DumpState.DUMP_FEATURES);
21278            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21279                if (opti >= args.length) {
21280                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21281                            | DumpState.DUMP_SERVICE_RESOLVERS
21282                            | DumpState.DUMP_RECEIVER_RESOLVERS
21283                            | DumpState.DUMP_CONTENT_RESOLVERS);
21284                } else {
21285                    while (opti < args.length) {
21286                        String name = args[opti];
21287                        if ("a".equals(name) || "activity".equals(name)) {
21288                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21289                        } else if ("s".equals(name) || "service".equals(name)) {
21290                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21291                        } else if ("r".equals(name) || "receiver".equals(name)) {
21292                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21293                        } else if ("c".equals(name) || "content".equals(name)) {
21294                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21295                        } else {
21296                            pw.println("Error: unknown resolver table type: " + name);
21297                            return;
21298                        }
21299                        opti++;
21300                    }
21301                }
21302            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21303                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21304            } else if ("permission".equals(cmd)) {
21305                if (opti >= args.length) {
21306                    pw.println("Error: permission requires permission name");
21307                    return;
21308                }
21309                permissionNames = new ArraySet<>();
21310                while (opti < args.length) {
21311                    permissionNames.add(args[opti]);
21312                    opti++;
21313                }
21314                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21315                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21316            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21317                dumpState.setDump(DumpState.DUMP_PREFERRED);
21318            } else if ("preferred-xml".equals(cmd)) {
21319                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21320                if (opti < args.length && "--full".equals(args[opti])) {
21321                    fullPreferred = true;
21322                    opti++;
21323                }
21324            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21325                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21326            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21327                dumpState.setDump(DumpState.DUMP_PACKAGES);
21328            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21329                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21330            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21331                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21332            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21333                dumpState.setDump(DumpState.DUMP_MESSAGES);
21334            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21335                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21336            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21337                    || "intent-filter-verifiers".equals(cmd)) {
21338                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21339            } else if ("version".equals(cmd)) {
21340                dumpState.setDump(DumpState.DUMP_VERSION);
21341            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21342                dumpState.setDump(DumpState.DUMP_KEYSETS);
21343            } else if ("installs".equals(cmd)) {
21344                dumpState.setDump(DumpState.DUMP_INSTALLS);
21345            } else if ("frozen".equals(cmd)) {
21346                dumpState.setDump(DumpState.DUMP_FROZEN);
21347            } else if ("volumes".equals(cmd)) {
21348                dumpState.setDump(DumpState.DUMP_VOLUMES);
21349            } else if ("dexopt".equals(cmd)) {
21350                dumpState.setDump(DumpState.DUMP_DEXOPT);
21351            } else if ("compiler-stats".equals(cmd)) {
21352                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21353            } else if ("changes".equals(cmd)) {
21354                dumpState.setDump(DumpState.DUMP_CHANGES);
21355            } else if ("service-permissions".equals(cmd)) {
21356                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21357            } else if ("write".equals(cmd)) {
21358                synchronized (mPackages) {
21359                    mSettings.writeLPr();
21360                    pw.println("Settings written.");
21361                    return;
21362                }
21363            }
21364        }
21365
21366        if (checkin) {
21367            pw.println("vers,1");
21368        }
21369
21370        // reader
21371        synchronized (mPackages) {
21372            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21373                if (!checkin) {
21374                    if (dumpState.onTitlePrinted())
21375                        pw.println();
21376                    pw.println("Database versions:");
21377                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21378                }
21379            }
21380
21381            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21382                if (!checkin) {
21383                    if (dumpState.onTitlePrinted())
21384                        pw.println();
21385                    pw.println("Verifiers:");
21386                    pw.print("  Required: ");
21387                    pw.print(mRequiredVerifierPackage);
21388                    pw.print(" (uid=");
21389                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21390                            UserHandle.USER_SYSTEM));
21391                    pw.println(")");
21392                } else if (mRequiredVerifierPackage != null) {
21393                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21394                    pw.print(",");
21395                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21396                            UserHandle.USER_SYSTEM));
21397                }
21398            }
21399
21400            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21401                    packageName == null) {
21402                if (mIntentFilterVerifierComponent != null) {
21403                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21404                    if (!checkin) {
21405                        if (dumpState.onTitlePrinted())
21406                            pw.println();
21407                        pw.println("Intent Filter Verifier:");
21408                        pw.print("  Using: ");
21409                        pw.print(verifierPackageName);
21410                        pw.print(" (uid=");
21411                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21412                                UserHandle.USER_SYSTEM));
21413                        pw.println(")");
21414                    } else if (verifierPackageName != null) {
21415                        pw.print("ifv,"); pw.print(verifierPackageName);
21416                        pw.print(",");
21417                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21418                                UserHandle.USER_SYSTEM));
21419                    }
21420                } else {
21421                    pw.println();
21422                    pw.println("No Intent Filter Verifier available!");
21423                }
21424            }
21425
21426            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21427                boolean printedHeader = false;
21428                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21429                while (it.hasNext()) {
21430                    String libName = it.next();
21431                    LongSparseArray<SharedLibraryEntry> versionedLib
21432                            = mSharedLibraries.get(libName);
21433                    if (versionedLib == null) {
21434                        continue;
21435                    }
21436                    final int versionCount = versionedLib.size();
21437                    for (int i = 0; i < versionCount; i++) {
21438                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21439                        if (!checkin) {
21440                            if (!printedHeader) {
21441                                if (dumpState.onTitlePrinted())
21442                                    pw.println();
21443                                pw.println("Libraries:");
21444                                printedHeader = true;
21445                            }
21446                            pw.print("  ");
21447                        } else {
21448                            pw.print("lib,");
21449                        }
21450                        pw.print(libEntry.info.getName());
21451                        if (libEntry.info.isStatic()) {
21452                            pw.print(" version=" + libEntry.info.getLongVersion());
21453                        }
21454                        if (!checkin) {
21455                            pw.print(" -> ");
21456                        }
21457                        if (libEntry.path != null) {
21458                            pw.print(" (jar) ");
21459                            pw.print(libEntry.path);
21460                        } else {
21461                            pw.print(" (apk) ");
21462                            pw.print(libEntry.apk);
21463                        }
21464                        pw.println();
21465                    }
21466                }
21467            }
21468
21469            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21470                if (dumpState.onTitlePrinted())
21471                    pw.println();
21472                if (!checkin) {
21473                    pw.println("Features:");
21474                }
21475
21476                synchronized (mAvailableFeatures) {
21477                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21478                        if (checkin) {
21479                            pw.print("feat,");
21480                            pw.print(feat.name);
21481                            pw.print(",");
21482                            pw.println(feat.version);
21483                        } else {
21484                            pw.print("  ");
21485                            pw.print(feat.name);
21486                            if (feat.version > 0) {
21487                                pw.print(" version=");
21488                                pw.print(feat.version);
21489                            }
21490                            pw.println();
21491                        }
21492                    }
21493                }
21494            }
21495
21496            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21497                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21498                        : "Activity Resolver Table:", "  ", packageName,
21499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21500                    dumpState.setTitlePrinted(true);
21501                }
21502            }
21503            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21504                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21505                        : "Receiver Resolver Table:", "  ", packageName,
21506                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21507                    dumpState.setTitlePrinted(true);
21508                }
21509            }
21510            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21511                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21512                        : "Service Resolver Table:", "  ", packageName,
21513                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21514                    dumpState.setTitlePrinted(true);
21515                }
21516            }
21517            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21518                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21519                        : "Provider Resolver Table:", "  ", packageName,
21520                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21521                    dumpState.setTitlePrinted(true);
21522                }
21523            }
21524
21525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21526                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21527                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21528                    int user = mSettings.mPreferredActivities.keyAt(i);
21529                    if (pir.dump(pw,
21530                            dumpState.getTitlePrinted()
21531                                ? "\nPreferred Activities User " + user + ":"
21532                                : "Preferred Activities User " + user + ":", "  ",
21533                            packageName, true, false)) {
21534                        dumpState.setTitlePrinted(true);
21535                    }
21536                }
21537            }
21538
21539            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21540                pw.flush();
21541                FileOutputStream fout = new FileOutputStream(fd);
21542                BufferedOutputStream str = new BufferedOutputStream(fout);
21543                XmlSerializer serializer = new FastXmlSerializer();
21544                try {
21545                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21546                    serializer.startDocument(null, true);
21547                    serializer.setFeature(
21548                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21549                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21550                    serializer.endDocument();
21551                    serializer.flush();
21552                } catch (IllegalArgumentException e) {
21553                    pw.println("Failed writing: " + e);
21554                } catch (IllegalStateException e) {
21555                    pw.println("Failed writing: " + e);
21556                } catch (IOException e) {
21557                    pw.println("Failed writing: " + e);
21558                }
21559            }
21560
21561            if (!checkin
21562                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21563                    && packageName == null) {
21564                pw.println();
21565                int count = mSettings.mPackages.size();
21566                if (count == 0) {
21567                    pw.println("No applications!");
21568                    pw.println();
21569                } else {
21570                    final String prefix = "  ";
21571                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21572                    if (allPackageSettings.size() == 0) {
21573                        pw.println("No domain preferred apps!");
21574                        pw.println();
21575                    } else {
21576                        pw.println("App verification status:");
21577                        pw.println();
21578                        count = 0;
21579                        for (PackageSetting ps : allPackageSettings) {
21580                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21581                            if (ivi == null || ivi.getPackageName() == null) continue;
21582                            pw.println(prefix + "Package: " + ivi.getPackageName());
21583                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21584                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21585                            pw.println();
21586                            count++;
21587                        }
21588                        if (count == 0) {
21589                            pw.println(prefix + "No app verification established.");
21590                            pw.println();
21591                        }
21592                        for (int userId : sUserManager.getUserIds()) {
21593                            pw.println("App linkages for user " + userId + ":");
21594                            pw.println();
21595                            count = 0;
21596                            for (PackageSetting ps : allPackageSettings) {
21597                                final long status = ps.getDomainVerificationStatusForUser(userId);
21598                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21599                                        && !DEBUG_DOMAIN_VERIFICATION) {
21600                                    continue;
21601                                }
21602                                pw.println(prefix + "Package: " + ps.name);
21603                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21604                                String statusStr = IntentFilterVerificationInfo.
21605                                        getStatusStringFromValue(status);
21606                                pw.println(prefix + "Status:  " + statusStr);
21607                                pw.println();
21608                                count++;
21609                            }
21610                            if (count == 0) {
21611                                pw.println(prefix + "No configured app linkages.");
21612                                pw.println();
21613                            }
21614                        }
21615                    }
21616                }
21617            }
21618
21619            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21620                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21621            }
21622
21623            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21624                boolean printedSomething = false;
21625                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21626                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21627                        continue;
21628                    }
21629                    if (!printedSomething) {
21630                        if (dumpState.onTitlePrinted())
21631                            pw.println();
21632                        pw.println("Registered ContentProviders:");
21633                        printedSomething = true;
21634                    }
21635                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21636                    pw.print("    "); pw.println(p.toString());
21637                }
21638                printedSomething = false;
21639                for (Map.Entry<String, PackageParser.Provider> entry :
21640                        mProvidersByAuthority.entrySet()) {
21641                    PackageParser.Provider p = entry.getValue();
21642                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21643                        continue;
21644                    }
21645                    if (!printedSomething) {
21646                        if (dumpState.onTitlePrinted())
21647                            pw.println();
21648                        pw.println("ContentProvider Authorities:");
21649                        printedSomething = true;
21650                    }
21651                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21652                    pw.print("    "); pw.println(p.toString());
21653                    if (p.info != null && p.info.applicationInfo != null) {
21654                        final String appInfo = p.info.applicationInfo.toString();
21655                        pw.print("      applicationInfo="); pw.println(appInfo);
21656                    }
21657                }
21658            }
21659
21660            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21661                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21662            }
21663
21664            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21665                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21666            }
21667
21668            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21669                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21670            }
21671
21672            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21673                if (dumpState.onTitlePrinted()) pw.println();
21674                pw.println("Package Changes:");
21675                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21676                final int K = mChangedPackages.size();
21677                for (int i = 0; i < K; i++) {
21678                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21679                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21680                    final int N = changes.size();
21681                    if (N == 0) {
21682                        pw.print("    "); pw.println("No packages changed");
21683                    } else {
21684                        for (int j = 0; j < N; j++) {
21685                            final String pkgName = changes.valueAt(j);
21686                            final int sequenceNumber = changes.keyAt(j);
21687                            pw.print("    ");
21688                            pw.print("seq=");
21689                            pw.print(sequenceNumber);
21690                            pw.print(", package=");
21691                            pw.println(pkgName);
21692                        }
21693                    }
21694                }
21695            }
21696
21697            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21698                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21699            }
21700
21701            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21702                // XXX should handle packageName != null by dumping only install data that
21703                // the given package is involved with.
21704                if (dumpState.onTitlePrinted()) pw.println();
21705
21706                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21707                ipw.println();
21708                ipw.println("Frozen packages:");
21709                ipw.increaseIndent();
21710                if (mFrozenPackages.size() == 0) {
21711                    ipw.println("(none)");
21712                } else {
21713                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21714                        ipw.println(mFrozenPackages.valueAt(i));
21715                    }
21716                }
21717                ipw.decreaseIndent();
21718            }
21719
21720            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21721                if (dumpState.onTitlePrinted()) pw.println();
21722
21723                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21724                ipw.println();
21725                ipw.println("Loaded volumes:");
21726                ipw.increaseIndent();
21727                if (mLoadedVolumes.size() == 0) {
21728                    ipw.println("(none)");
21729                } else {
21730                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21731                        ipw.println(mLoadedVolumes.valueAt(i));
21732                    }
21733                }
21734                ipw.decreaseIndent();
21735            }
21736
21737            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21738                    && packageName == null) {
21739                if (dumpState.onTitlePrinted()) pw.println();
21740                pw.println("Service permissions:");
21741
21742                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21743                while (filterIterator.hasNext()) {
21744                    final ServiceIntentInfo info = filterIterator.next();
21745                    final ServiceInfo serviceInfo = info.service.info;
21746                    final String permission = serviceInfo.permission;
21747                    if (permission != null) {
21748                        pw.print("    ");
21749                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21750                        pw.print(": ");
21751                        pw.println(permission);
21752                    }
21753                }
21754            }
21755
21756            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21757                if (dumpState.onTitlePrinted()) pw.println();
21758                dumpDexoptStateLPr(pw, packageName);
21759            }
21760
21761            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21762                if (dumpState.onTitlePrinted()) pw.println();
21763                dumpCompilerStatsLPr(pw, packageName);
21764            }
21765
21766            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21767                if (dumpState.onTitlePrinted()) pw.println();
21768                mSettings.dumpReadMessagesLPr(pw, dumpState);
21769
21770                pw.println();
21771                pw.println("Package warning messages:");
21772                dumpCriticalInfo(pw, null);
21773            }
21774
21775            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21776                dumpCriticalInfo(pw, "msg,");
21777            }
21778        }
21779
21780        // PackageInstaller should be called outside of mPackages lock
21781        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21782            // XXX should handle packageName != null by dumping only install data that
21783            // the given package is involved with.
21784            if (dumpState.onTitlePrinted()) pw.println();
21785            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21786        }
21787    }
21788
21789    private void dumpProto(FileDescriptor fd) {
21790        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21791
21792        synchronized (mPackages) {
21793            final long requiredVerifierPackageToken =
21794                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21795            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21796            proto.write(
21797                    PackageServiceDumpProto.PackageShortProto.UID,
21798                    getPackageUid(
21799                            mRequiredVerifierPackage,
21800                            MATCH_DEBUG_TRIAGED_MISSING,
21801                            UserHandle.USER_SYSTEM));
21802            proto.end(requiredVerifierPackageToken);
21803
21804            if (mIntentFilterVerifierComponent != null) {
21805                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21806                final long verifierPackageToken =
21807                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21808                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21809                proto.write(
21810                        PackageServiceDumpProto.PackageShortProto.UID,
21811                        getPackageUid(
21812                                verifierPackageName,
21813                                MATCH_DEBUG_TRIAGED_MISSING,
21814                                UserHandle.USER_SYSTEM));
21815                proto.end(verifierPackageToken);
21816            }
21817
21818            dumpSharedLibrariesProto(proto);
21819            dumpFeaturesProto(proto);
21820            mSettings.dumpPackagesProto(proto);
21821            mSettings.dumpSharedUsersProto(proto);
21822            dumpCriticalInfo(proto);
21823        }
21824        proto.flush();
21825    }
21826
21827    private void dumpFeaturesProto(ProtoOutputStream proto) {
21828        synchronized (mAvailableFeatures) {
21829            final int count = mAvailableFeatures.size();
21830            for (int i = 0; i < count; i++) {
21831                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21832            }
21833        }
21834    }
21835
21836    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21837        final int count = mSharedLibraries.size();
21838        for (int i = 0; i < count; i++) {
21839            final String libName = mSharedLibraries.keyAt(i);
21840            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21841            if (versionedLib == null) {
21842                continue;
21843            }
21844            final int versionCount = versionedLib.size();
21845            for (int j = 0; j < versionCount; j++) {
21846                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21847                final long sharedLibraryToken =
21848                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21849                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21850                final boolean isJar = (libEntry.path != null);
21851                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21852                if (isJar) {
21853                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21854                } else {
21855                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21856                }
21857                proto.end(sharedLibraryToken);
21858            }
21859        }
21860    }
21861
21862    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21863        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21864        ipw.println();
21865        ipw.println("Dexopt state:");
21866        ipw.increaseIndent();
21867        Collection<PackageParser.Package> packages = null;
21868        if (packageName != null) {
21869            PackageParser.Package targetPackage = mPackages.get(packageName);
21870            if (targetPackage != null) {
21871                packages = Collections.singletonList(targetPackage);
21872            } else {
21873                ipw.println("Unable to find package: " + packageName);
21874                return;
21875            }
21876        } else {
21877            packages = mPackages.values();
21878        }
21879
21880        for (PackageParser.Package pkg : packages) {
21881            ipw.println("[" + pkg.packageName + "]");
21882            ipw.increaseIndent();
21883            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21884                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21885            ipw.decreaseIndent();
21886        }
21887    }
21888
21889    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21890        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21891        ipw.println();
21892        ipw.println("Compiler stats:");
21893        ipw.increaseIndent();
21894        Collection<PackageParser.Package> packages = null;
21895        if (packageName != null) {
21896            PackageParser.Package targetPackage = mPackages.get(packageName);
21897            if (targetPackage != null) {
21898                packages = Collections.singletonList(targetPackage);
21899            } else {
21900                ipw.println("Unable to find package: " + packageName);
21901                return;
21902            }
21903        } else {
21904            packages = mPackages.values();
21905        }
21906
21907        for (PackageParser.Package pkg : packages) {
21908            ipw.println("[" + pkg.packageName + "]");
21909            ipw.increaseIndent();
21910
21911            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21912            if (stats == null) {
21913                ipw.println("(No recorded stats)");
21914            } else {
21915                stats.dump(ipw);
21916            }
21917            ipw.decreaseIndent();
21918        }
21919    }
21920
21921    private String dumpDomainString(String packageName) {
21922        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21923                .getList();
21924        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21925
21926        ArraySet<String> result = new ArraySet<>();
21927        if (iviList.size() > 0) {
21928            for (IntentFilterVerificationInfo ivi : iviList) {
21929                for (String host : ivi.getDomains()) {
21930                    result.add(host);
21931                }
21932            }
21933        }
21934        if (filters != null && filters.size() > 0) {
21935            for (IntentFilter filter : filters) {
21936                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21937                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21938                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21939                    result.addAll(filter.getHostsList());
21940                }
21941            }
21942        }
21943
21944        StringBuilder sb = new StringBuilder(result.size() * 16);
21945        for (String domain : result) {
21946            if (sb.length() > 0) sb.append(" ");
21947            sb.append(domain);
21948        }
21949        return sb.toString();
21950    }
21951
21952    // ------- apps on sdcard specific code -------
21953    static final boolean DEBUG_SD_INSTALL = false;
21954
21955    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21956
21957    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21958
21959    private boolean mMediaMounted = false;
21960
21961    static String getEncryptKey() {
21962        try {
21963            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21964                    SD_ENCRYPTION_KEYSTORE_NAME);
21965            if (sdEncKey == null) {
21966                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21967                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21968                if (sdEncKey == null) {
21969                    Slog.e(TAG, "Failed to create encryption keys");
21970                    return null;
21971                }
21972            }
21973            return sdEncKey;
21974        } catch (NoSuchAlgorithmException nsae) {
21975            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21976            return null;
21977        } catch (IOException ioe) {
21978            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21979            return null;
21980        }
21981    }
21982
21983    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21984            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21985        final int size = infos.size();
21986        final String[] packageNames = new String[size];
21987        final int[] packageUids = new int[size];
21988        for (int i = 0; i < size; i++) {
21989            final ApplicationInfo info = infos.get(i);
21990            packageNames[i] = info.packageName;
21991            packageUids[i] = info.uid;
21992        }
21993        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21994                finishedReceiver);
21995    }
21996
21997    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21998            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21999        sendResourcesChangedBroadcast(mediaStatus, replacing,
22000                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22001    }
22002
22003    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22004            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22005        int size = pkgList.length;
22006        if (size > 0) {
22007            // Send broadcasts here
22008            Bundle extras = new Bundle();
22009            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22010            if (uidArr != null) {
22011                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22012            }
22013            if (replacing) {
22014                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22015            }
22016            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22017                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22018            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22019        }
22020    }
22021
22022    private void loadPrivatePackages(final VolumeInfo vol) {
22023        mHandler.post(new Runnable() {
22024            @Override
22025            public void run() {
22026                loadPrivatePackagesInner(vol);
22027            }
22028        });
22029    }
22030
22031    private void loadPrivatePackagesInner(VolumeInfo vol) {
22032        final String volumeUuid = vol.fsUuid;
22033        if (TextUtils.isEmpty(volumeUuid)) {
22034            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22035            return;
22036        }
22037
22038        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22039        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22040        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22041
22042        final VersionInfo ver;
22043        final List<PackageSetting> packages;
22044        synchronized (mPackages) {
22045            ver = mSettings.findOrCreateVersion(volumeUuid);
22046            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22047        }
22048
22049        for (PackageSetting ps : packages) {
22050            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22051            synchronized (mInstallLock) {
22052                final PackageParser.Package pkg;
22053                try {
22054                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22055                    loaded.add(pkg.applicationInfo);
22056
22057                } catch (PackageManagerException e) {
22058                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22059                }
22060
22061                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22062                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22063                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22064                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22065                }
22066            }
22067        }
22068
22069        // Reconcile app data for all started/unlocked users
22070        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22071        final UserManager um = mContext.getSystemService(UserManager.class);
22072        UserManagerInternal umInternal = getUserManagerInternal();
22073        for (UserInfo user : um.getUsers()) {
22074            final int flags;
22075            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22076                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22077            } else if (umInternal.isUserRunning(user.id)) {
22078                flags = StorageManager.FLAG_STORAGE_DE;
22079            } else {
22080                continue;
22081            }
22082
22083            try {
22084                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22085                synchronized (mInstallLock) {
22086                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22087                }
22088            } catch (IllegalStateException e) {
22089                // Device was probably ejected, and we'll process that event momentarily
22090                Slog.w(TAG, "Failed to prepare storage: " + e);
22091            }
22092        }
22093
22094        synchronized (mPackages) {
22095            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22096            if (sdkUpdated) {
22097                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22098                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22099            }
22100            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22101                    mPermissionCallback);
22102
22103            // Yay, everything is now upgraded
22104            ver.forceCurrent();
22105
22106            mSettings.writeLPr();
22107        }
22108
22109        for (PackageFreezer freezer : freezers) {
22110            freezer.close();
22111        }
22112
22113        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22114        sendResourcesChangedBroadcast(true, false, loaded, null);
22115        mLoadedVolumes.add(vol.getId());
22116    }
22117
22118    private void unloadPrivatePackages(final VolumeInfo vol) {
22119        mHandler.post(new Runnable() {
22120            @Override
22121            public void run() {
22122                unloadPrivatePackagesInner(vol);
22123            }
22124        });
22125    }
22126
22127    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22128        final String volumeUuid = vol.fsUuid;
22129        if (TextUtils.isEmpty(volumeUuid)) {
22130            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22131            return;
22132        }
22133
22134        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22135        synchronized (mInstallLock) {
22136        synchronized (mPackages) {
22137            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22138            for (PackageSetting ps : packages) {
22139                if (ps.pkg == null) continue;
22140
22141                final ApplicationInfo info = ps.pkg.applicationInfo;
22142                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22143                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22144
22145                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22146                        "unloadPrivatePackagesInner")) {
22147                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22148                            false, null)) {
22149                        unloaded.add(info);
22150                    } else {
22151                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22152                    }
22153                }
22154
22155                // Try very hard to release any references to this package
22156                // so we don't risk the system server being killed due to
22157                // open FDs
22158                AttributeCache.instance().removePackage(ps.name);
22159            }
22160
22161            mSettings.writeLPr();
22162        }
22163        }
22164
22165        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22166        sendResourcesChangedBroadcast(false, false, unloaded, null);
22167        mLoadedVolumes.remove(vol.getId());
22168
22169        // Try very hard to release any references to this path so we don't risk
22170        // the system server being killed due to open FDs
22171        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22172
22173        for (int i = 0; i < 3; i++) {
22174            System.gc();
22175            System.runFinalization();
22176        }
22177    }
22178
22179    private void assertPackageKnown(String volumeUuid, String packageName)
22180            throws PackageManagerException {
22181        synchronized (mPackages) {
22182            // Normalize package name to handle renamed packages
22183            packageName = normalizePackageNameLPr(packageName);
22184
22185            final PackageSetting ps = mSettings.mPackages.get(packageName);
22186            if (ps == null) {
22187                throw new PackageManagerException("Package " + packageName + " is unknown");
22188            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22189                throw new PackageManagerException(
22190                        "Package " + packageName + " found on unknown volume " + volumeUuid
22191                                + "; expected volume " + ps.volumeUuid);
22192            }
22193        }
22194    }
22195
22196    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22197            throws PackageManagerException {
22198        synchronized (mPackages) {
22199            // Normalize package name to handle renamed packages
22200            packageName = normalizePackageNameLPr(packageName);
22201
22202            final PackageSetting ps = mSettings.mPackages.get(packageName);
22203            if (ps == null) {
22204                throw new PackageManagerException("Package " + packageName + " is unknown");
22205            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22206                throw new PackageManagerException(
22207                        "Package " + packageName + " found on unknown volume " + volumeUuid
22208                                + "; expected volume " + ps.volumeUuid);
22209            } else if (!ps.getInstalled(userId)) {
22210                throw new PackageManagerException(
22211                        "Package " + packageName + " not installed for user " + userId);
22212            }
22213        }
22214    }
22215
22216    private List<String> collectAbsoluteCodePaths() {
22217        synchronized (mPackages) {
22218            List<String> codePaths = new ArrayList<>();
22219            final int packageCount = mSettings.mPackages.size();
22220            for (int i = 0; i < packageCount; i++) {
22221                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22222                codePaths.add(ps.codePath.getAbsolutePath());
22223            }
22224            return codePaths;
22225        }
22226    }
22227
22228    /**
22229     * Examine all apps present on given mounted volume, and destroy apps that
22230     * aren't expected, either due to uninstallation or reinstallation on
22231     * another volume.
22232     */
22233    private void reconcileApps(String volumeUuid) {
22234        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22235        List<File> filesToDelete = null;
22236
22237        final File[] files = FileUtils.listFilesOrEmpty(
22238                Environment.getDataAppDirectory(volumeUuid));
22239        for (File file : files) {
22240            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22241                    && !PackageInstallerService.isStageName(file.getName());
22242            if (!isPackage) {
22243                // Ignore entries which are not packages
22244                continue;
22245            }
22246
22247            String absolutePath = file.getAbsolutePath();
22248
22249            boolean pathValid = false;
22250            final int absoluteCodePathCount = absoluteCodePaths.size();
22251            for (int i = 0; i < absoluteCodePathCount; i++) {
22252                String absoluteCodePath = absoluteCodePaths.get(i);
22253                if (absolutePath.startsWith(absoluteCodePath)) {
22254                    pathValid = true;
22255                    break;
22256                }
22257            }
22258
22259            if (!pathValid) {
22260                if (filesToDelete == null) {
22261                    filesToDelete = new ArrayList<>();
22262                }
22263                filesToDelete.add(file);
22264            }
22265        }
22266
22267        if (filesToDelete != null) {
22268            final int fileToDeleteCount = filesToDelete.size();
22269            for (int i = 0; i < fileToDeleteCount; i++) {
22270                File fileToDelete = filesToDelete.get(i);
22271                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22272                synchronized (mInstallLock) {
22273                    removeCodePathLI(fileToDelete);
22274                }
22275            }
22276        }
22277    }
22278
22279    /**
22280     * Reconcile all app data for the given user.
22281     * <p>
22282     * Verifies that directories exist and that ownership and labeling is
22283     * correct for all installed apps on all mounted volumes.
22284     */
22285    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22286        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22287        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22288            final String volumeUuid = vol.getFsUuid();
22289            synchronized (mInstallLock) {
22290                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22291            }
22292        }
22293    }
22294
22295    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22296            boolean migrateAppData) {
22297        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22298    }
22299
22300    /**
22301     * Reconcile all app data on given mounted volume.
22302     * <p>
22303     * Destroys app data that isn't expected, either due to uninstallation or
22304     * reinstallation on another volume.
22305     * <p>
22306     * Verifies that directories exist and that ownership and labeling is
22307     * correct for all installed apps.
22308     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22309     */
22310    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22311            boolean migrateAppData, boolean onlyCoreApps) {
22312        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22313                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22314        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22315
22316        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22317        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22318
22319        // First look for stale data that doesn't belong, and check if things
22320        // have changed since we did our last restorecon
22321        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22322            if (StorageManager.isFileEncryptedNativeOrEmulated()
22323                    && !StorageManager.isUserKeyUnlocked(userId)) {
22324                throw new RuntimeException(
22325                        "Yikes, someone asked us to reconcile CE storage while " + userId
22326                                + " was still locked; this would have caused massive data loss!");
22327            }
22328
22329            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22330            for (File file : files) {
22331                final String packageName = file.getName();
22332                try {
22333                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22334                } catch (PackageManagerException e) {
22335                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22336                    try {
22337                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22338                                StorageManager.FLAG_STORAGE_CE, 0);
22339                    } catch (InstallerException e2) {
22340                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22341                    }
22342                }
22343            }
22344        }
22345        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22346            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22347            for (File file : files) {
22348                final String packageName = file.getName();
22349                try {
22350                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22351                } catch (PackageManagerException e) {
22352                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22353                    try {
22354                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22355                                StorageManager.FLAG_STORAGE_DE, 0);
22356                    } catch (InstallerException e2) {
22357                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22358                    }
22359                }
22360            }
22361        }
22362
22363        // Ensure that data directories are ready to roll for all packages
22364        // installed for this volume and user
22365        final List<PackageSetting> packages;
22366        synchronized (mPackages) {
22367            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22368        }
22369        int preparedCount = 0;
22370        for (PackageSetting ps : packages) {
22371            final String packageName = ps.name;
22372            if (ps.pkg == null) {
22373                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22374                // TODO: might be due to legacy ASEC apps; we should circle back
22375                // and reconcile again once they're scanned
22376                continue;
22377            }
22378            // Skip non-core apps if requested
22379            if (onlyCoreApps && !ps.pkg.coreApp) {
22380                result.add(packageName);
22381                continue;
22382            }
22383
22384            if (ps.getInstalled(userId)) {
22385                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22386                preparedCount++;
22387            }
22388        }
22389
22390        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22391        return result;
22392    }
22393
22394    /**
22395     * Prepare app data for the given app just after it was installed or
22396     * upgraded. This method carefully only touches users that it's installed
22397     * for, and it forces a restorecon to handle any seinfo changes.
22398     * <p>
22399     * Verifies that directories exist and that ownership and labeling is
22400     * correct for all installed apps. If there is an ownership mismatch, it
22401     * will try recovering system apps by wiping data; third-party app data is
22402     * left intact.
22403     * <p>
22404     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22405     */
22406    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22407        final PackageSetting ps;
22408        synchronized (mPackages) {
22409            ps = mSettings.mPackages.get(pkg.packageName);
22410            mSettings.writeKernelMappingLPr(ps);
22411        }
22412
22413        final UserManager um = mContext.getSystemService(UserManager.class);
22414        UserManagerInternal umInternal = getUserManagerInternal();
22415        for (UserInfo user : um.getUsers()) {
22416            final int flags;
22417            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22418                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22419            } else if (umInternal.isUserRunning(user.id)) {
22420                flags = StorageManager.FLAG_STORAGE_DE;
22421            } else {
22422                continue;
22423            }
22424
22425            if (ps.getInstalled(user.id)) {
22426                // TODO: when user data is locked, mark that we're still dirty
22427                prepareAppDataLIF(pkg, user.id, flags);
22428            }
22429        }
22430    }
22431
22432    /**
22433     * Prepare app data for the given app.
22434     * <p>
22435     * Verifies that directories exist and that ownership and labeling is
22436     * correct for all installed apps. If there is an ownership mismatch, this
22437     * will try recovering system apps by wiping data; third-party app data is
22438     * left intact.
22439     */
22440    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22441        if (pkg == null) {
22442            Slog.wtf(TAG, "Package was null!", new Throwable());
22443            return;
22444        }
22445        prepareAppDataLeafLIF(pkg, userId, flags);
22446        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22447        for (int i = 0; i < childCount; i++) {
22448            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22449        }
22450    }
22451
22452    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22453            boolean maybeMigrateAppData) {
22454        prepareAppDataLIF(pkg, userId, flags);
22455
22456        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22457            // We may have just shuffled around app data directories, so
22458            // prepare them one more time
22459            prepareAppDataLIF(pkg, userId, flags);
22460        }
22461    }
22462
22463    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22464        if (DEBUG_APP_DATA) {
22465            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22466                    + Integer.toHexString(flags));
22467        }
22468
22469        final PackageSetting ps;
22470        synchronized (mPackages) {
22471            ps = mSettings.mPackages.get(pkg.packageName);
22472        }
22473        final String volumeUuid = pkg.volumeUuid;
22474        final String packageName = pkg.packageName;
22475        final ApplicationInfo app = (ps == null)
22476                ? pkg.applicationInfo
22477                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22478
22479        final int appId = UserHandle.getAppId(app.uid);
22480
22481        Preconditions.checkNotNull(app.seInfo);
22482
22483        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22484        long ceDataInode = -1;
22485        try {
22486            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22487                    appId, seInfo, app.targetSdkVersion);
22488        } catch (InstallerException e) {
22489            if (app.isSystemApp()) {
22490                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22491                        + ", but trying to recover: " + e);
22492                destroyAppDataLeafLIF(pkg, userId, flags);
22493                try {
22494                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22495                            appId, seInfo, app.targetSdkVersion);
22496                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22497                } catch (InstallerException e2) {
22498                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22499                }
22500            } else {
22501                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22502            }
22503        }
22504        // Prepare the application profiles only for upgrades and first boot (so that we don't
22505        // repeat the same operation at each boot).
22506        // We only have to cover the upgrade and first boot here because for app installs we
22507        // prepare the profiles before invoking dexopt (in installPackageLI).
22508        //
22509        // We also have to cover non system users because we do not call the usual install package
22510        // methods for them.
22511        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22512            mArtManagerService.prepareAppProfiles(pkg, userId);
22513        }
22514
22515        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22516            // TODO: mark this structure as dirty so we persist it!
22517            synchronized (mPackages) {
22518                if (ps != null) {
22519                    ps.setCeDataInode(ceDataInode, userId);
22520                }
22521            }
22522        }
22523
22524        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22525    }
22526
22527    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22528        if (pkg == null) {
22529            Slog.wtf(TAG, "Package was null!", new Throwable());
22530            return;
22531        }
22532        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22534        for (int i = 0; i < childCount; i++) {
22535            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22536        }
22537    }
22538
22539    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22540        final String volumeUuid = pkg.volumeUuid;
22541        final String packageName = pkg.packageName;
22542        final ApplicationInfo app = pkg.applicationInfo;
22543
22544        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22545            // Create a native library symlink only if we have native libraries
22546            // and if the native libraries are 32 bit libraries. We do not provide
22547            // this symlink for 64 bit libraries.
22548            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22549                final String nativeLibPath = app.nativeLibraryDir;
22550                try {
22551                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22552                            nativeLibPath, userId);
22553                } catch (InstallerException e) {
22554                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22555                }
22556            }
22557        }
22558    }
22559
22560    /**
22561     * For system apps on non-FBE devices, this method migrates any existing
22562     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22563     * requested by the app.
22564     */
22565    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22566        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22567                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22568            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22569                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22570            try {
22571                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22572                        storageTarget);
22573            } catch (InstallerException e) {
22574                logCriticalInfo(Log.WARN,
22575                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22576            }
22577            return true;
22578        } else {
22579            return false;
22580        }
22581    }
22582
22583    public PackageFreezer freezePackage(String packageName, String killReason) {
22584        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22585    }
22586
22587    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22588        return new PackageFreezer(packageName, userId, killReason);
22589    }
22590
22591    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22592            String killReason) {
22593        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22594    }
22595
22596    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22597            String killReason) {
22598        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22599            return new PackageFreezer();
22600        } else {
22601            return freezePackage(packageName, userId, killReason);
22602        }
22603    }
22604
22605    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22606            String killReason) {
22607        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22608    }
22609
22610    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22611            String killReason) {
22612        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22613            return new PackageFreezer();
22614        } else {
22615            return freezePackage(packageName, userId, killReason);
22616        }
22617    }
22618
22619    /**
22620     * Class that freezes and kills the given package upon creation, and
22621     * unfreezes it upon closing. This is typically used when doing surgery on
22622     * app code/data to prevent the app from running while you're working.
22623     */
22624    private class PackageFreezer implements AutoCloseable {
22625        private final String mPackageName;
22626        private final PackageFreezer[] mChildren;
22627
22628        private final boolean mWeFroze;
22629
22630        private final AtomicBoolean mClosed = new AtomicBoolean();
22631        private final CloseGuard mCloseGuard = CloseGuard.get();
22632
22633        /**
22634         * Create and return a stub freezer that doesn't actually do anything,
22635         * typically used when someone requested
22636         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22637         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22638         */
22639        public PackageFreezer() {
22640            mPackageName = null;
22641            mChildren = null;
22642            mWeFroze = false;
22643            mCloseGuard.open("close");
22644        }
22645
22646        public PackageFreezer(String packageName, int userId, String killReason) {
22647            synchronized (mPackages) {
22648                mPackageName = packageName;
22649                mWeFroze = mFrozenPackages.add(mPackageName);
22650
22651                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22652                if (ps != null) {
22653                    killApplication(ps.name, ps.appId, userId, killReason);
22654                }
22655
22656                final PackageParser.Package p = mPackages.get(packageName);
22657                if (p != null && p.childPackages != null) {
22658                    final int N = p.childPackages.size();
22659                    mChildren = new PackageFreezer[N];
22660                    for (int i = 0; i < N; i++) {
22661                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22662                                userId, killReason);
22663                    }
22664                } else {
22665                    mChildren = null;
22666                }
22667            }
22668            mCloseGuard.open("close");
22669        }
22670
22671        @Override
22672        protected void finalize() throws Throwable {
22673            try {
22674                if (mCloseGuard != null) {
22675                    mCloseGuard.warnIfOpen();
22676                }
22677
22678                close();
22679            } finally {
22680                super.finalize();
22681            }
22682        }
22683
22684        @Override
22685        public void close() {
22686            mCloseGuard.close();
22687            if (mClosed.compareAndSet(false, true)) {
22688                synchronized (mPackages) {
22689                    if (mWeFroze) {
22690                        mFrozenPackages.remove(mPackageName);
22691                    }
22692
22693                    if (mChildren != null) {
22694                        for (PackageFreezer freezer : mChildren) {
22695                            freezer.close();
22696                        }
22697                    }
22698                }
22699            }
22700        }
22701    }
22702
22703    /**
22704     * Verify that given package is currently frozen.
22705     */
22706    private void checkPackageFrozen(String packageName) {
22707        synchronized (mPackages) {
22708            if (!mFrozenPackages.contains(packageName)) {
22709                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22710            }
22711        }
22712    }
22713
22714    @Override
22715    public int movePackage(final String packageName, final String volumeUuid) {
22716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22717
22718        final int callingUid = Binder.getCallingUid();
22719        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22720        final int moveId = mNextMoveId.getAndIncrement();
22721        mHandler.post(new Runnable() {
22722            @Override
22723            public void run() {
22724                try {
22725                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22726                } catch (PackageManagerException e) {
22727                    Slog.w(TAG, "Failed to move " + packageName, e);
22728                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22729                }
22730            }
22731        });
22732        return moveId;
22733    }
22734
22735    private void movePackageInternal(final String packageName, final String volumeUuid,
22736            final int moveId, final int callingUid, UserHandle user)
22737                    throws PackageManagerException {
22738        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22739        final PackageManager pm = mContext.getPackageManager();
22740
22741        final boolean currentAsec;
22742        final String currentVolumeUuid;
22743        final File codeFile;
22744        final String installerPackageName;
22745        final String packageAbiOverride;
22746        final int appId;
22747        final String seinfo;
22748        final String label;
22749        final int targetSdkVersion;
22750        final PackageFreezer freezer;
22751        final int[] installedUserIds;
22752
22753        // reader
22754        synchronized (mPackages) {
22755            final PackageParser.Package pkg = mPackages.get(packageName);
22756            final PackageSetting ps = mSettings.mPackages.get(packageName);
22757            if (pkg == null
22758                    || ps == null
22759                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22760                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22761            }
22762            if (pkg.applicationInfo.isSystemApp()) {
22763                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22764                        "Cannot move system application");
22765            }
22766
22767            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22768            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22769                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22770            if (isInternalStorage && !allow3rdPartyOnInternal) {
22771                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22772                        "3rd party apps are not allowed on internal storage");
22773            }
22774
22775            if (pkg.applicationInfo.isExternalAsec()) {
22776                currentAsec = true;
22777                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22778            } else if (pkg.applicationInfo.isForwardLocked()) {
22779                currentAsec = true;
22780                currentVolumeUuid = "forward_locked";
22781            } else {
22782                currentAsec = false;
22783                currentVolumeUuid = ps.volumeUuid;
22784
22785                final File probe = new File(pkg.codePath);
22786                final File probeOat = new File(probe, "oat");
22787                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22788                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22789                            "Move only supported for modern cluster style installs");
22790                }
22791            }
22792
22793            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22794                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22795                        "Package already moved to " + volumeUuid);
22796            }
22797            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22798                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22799                        "Device admin cannot be moved");
22800            }
22801
22802            if (mFrozenPackages.contains(packageName)) {
22803                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22804                        "Failed to move already frozen package");
22805            }
22806
22807            codeFile = new File(pkg.codePath);
22808            installerPackageName = ps.installerPackageName;
22809            packageAbiOverride = ps.cpuAbiOverrideString;
22810            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22811            seinfo = pkg.applicationInfo.seInfo;
22812            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22813            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22814            freezer = freezePackage(packageName, "movePackageInternal");
22815            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22816        }
22817
22818        final Bundle extras = new Bundle();
22819        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22820        extras.putString(Intent.EXTRA_TITLE, label);
22821        mMoveCallbacks.notifyCreated(moveId, extras);
22822
22823        int installFlags;
22824        final boolean moveCompleteApp;
22825        final File measurePath;
22826
22827        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22828            installFlags = INSTALL_INTERNAL;
22829            moveCompleteApp = !currentAsec;
22830            measurePath = Environment.getDataAppDirectory(volumeUuid);
22831        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22832            installFlags = INSTALL_EXTERNAL;
22833            moveCompleteApp = false;
22834            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22835        } else {
22836            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22837            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22838                    || !volume.isMountedWritable()) {
22839                freezer.close();
22840                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22841                        "Move location not mounted private volume");
22842            }
22843
22844            Preconditions.checkState(!currentAsec);
22845
22846            installFlags = INSTALL_INTERNAL;
22847            moveCompleteApp = true;
22848            measurePath = Environment.getDataAppDirectory(volumeUuid);
22849        }
22850
22851        // If we're moving app data around, we need all the users unlocked
22852        if (moveCompleteApp) {
22853            for (int userId : installedUserIds) {
22854                if (StorageManager.isFileEncryptedNativeOrEmulated()
22855                        && !StorageManager.isUserKeyUnlocked(userId)) {
22856                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22857                            "User " + userId + " must be unlocked");
22858                }
22859            }
22860        }
22861
22862        final PackageStats stats = new PackageStats(null, -1);
22863        synchronized (mInstaller) {
22864            for (int userId : installedUserIds) {
22865                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22866                    freezer.close();
22867                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22868                            "Failed to measure package size");
22869                }
22870            }
22871        }
22872
22873        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22874                + stats.dataSize);
22875
22876        final long startFreeBytes = measurePath.getUsableSpace();
22877        final long sizeBytes;
22878        if (moveCompleteApp) {
22879            sizeBytes = stats.codeSize + stats.dataSize;
22880        } else {
22881            sizeBytes = stats.codeSize;
22882        }
22883
22884        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22885            freezer.close();
22886            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22887                    "Not enough free space to move");
22888        }
22889
22890        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22891
22892        final CountDownLatch installedLatch = new CountDownLatch(1);
22893        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22894            @Override
22895            public void onUserActionRequired(Intent intent) throws RemoteException {
22896                throw new IllegalStateException();
22897            }
22898
22899            @Override
22900            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22901                    Bundle extras) throws RemoteException {
22902                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22903                        + PackageManager.installStatusToString(returnCode, msg));
22904
22905                installedLatch.countDown();
22906                freezer.close();
22907
22908                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22909                switch (status) {
22910                    case PackageInstaller.STATUS_SUCCESS:
22911                        mMoveCallbacks.notifyStatusChanged(moveId,
22912                                PackageManager.MOVE_SUCCEEDED);
22913                        break;
22914                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22915                        mMoveCallbacks.notifyStatusChanged(moveId,
22916                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22917                        break;
22918                    default:
22919                        mMoveCallbacks.notifyStatusChanged(moveId,
22920                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22921                        break;
22922                }
22923            }
22924        };
22925
22926        final MoveInfo move;
22927        if (moveCompleteApp) {
22928            // Kick off a thread to report progress estimates
22929            new Thread() {
22930                @Override
22931                public void run() {
22932                    while (true) {
22933                        try {
22934                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22935                                break;
22936                            }
22937                        } catch (InterruptedException ignored) {
22938                        }
22939
22940                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22941                        final int progress = 10 + (int) MathUtils.constrain(
22942                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22943                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22944                    }
22945                }
22946            }.start();
22947
22948            final String dataAppName = codeFile.getName();
22949            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22950                    dataAppName, appId, seinfo, targetSdkVersion);
22951        } else {
22952            move = null;
22953        }
22954
22955        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22956
22957        final Message msg = mHandler.obtainMessage(INIT_COPY);
22958        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22959        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22960                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22961                packageAbiOverride, null /*grantedPermissions*/,
22962                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22963        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22964        msg.obj = params;
22965
22966        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22967                System.identityHashCode(msg.obj));
22968        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22969                System.identityHashCode(msg.obj));
22970
22971        mHandler.sendMessage(msg);
22972    }
22973
22974    @Override
22975    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22976        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22977
22978        final int realMoveId = mNextMoveId.getAndIncrement();
22979        final Bundle extras = new Bundle();
22980        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22981        mMoveCallbacks.notifyCreated(realMoveId, extras);
22982
22983        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22984            @Override
22985            public void onCreated(int moveId, Bundle extras) {
22986                // Ignored
22987            }
22988
22989            @Override
22990            public void onStatusChanged(int moveId, int status, long estMillis) {
22991                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22992            }
22993        };
22994
22995        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22996        storage.setPrimaryStorageUuid(volumeUuid, callback);
22997        return realMoveId;
22998    }
22999
23000    @Override
23001    public int getMoveStatus(int moveId) {
23002        mContext.enforceCallingOrSelfPermission(
23003                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23004        return mMoveCallbacks.mLastStatus.get(moveId);
23005    }
23006
23007    @Override
23008    public void registerMoveCallback(IPackageMoveObserver callback) {
23009        mContext.enforceCallingOrSelfPermission(
23010                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23011        mMoveCallbacks.register(callback);
23012    }
23013
23014    @Override
23015    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23016        mContext.enforceCallingOrSelfPermission(
23017                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23018        mMoveCallbacks.unregister(callback);
23019    }
23020
23021    @Override
23022    public boolean setInstallLocation(int loc) {
23023        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23024                null);
23025        if (getInstallLocation() == loc) {
23026            return true;
23027        }
23028        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23029                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23030            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23031                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23032            return true;
23033        }
23034        return false;
23035   }
23036
23037    @Override
23038    public int getInstallLocation() {
23039        // allow instant app access
23040        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23041                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23042                PackageHelper.APP_INSTALL_AUTO);
23043    }
23044
23045    /** Called by UserManagerService */
23046    void cleanUpUser(UserManagerService userManager, int userHandle) {
23047        synchronized (mPackages) {
23048            mDirtyUsers.remove(userHandle);
23049            mUserNeedsBadging.delete(userHandle);
23050            mSettings.removeUserLPw(userHandle);
23051            mPendingBroadcasts.remove(userHandle);
23052            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23053            removeUnusedPackagesLPw(userManager, userHandle);
23054        }
23055    }
23056
23057    /**
23058     * We're removing userHandle and would like to remove any downloaded packages
23059     * that are no longer in use by any other user.
23060     * @param userHandle the user being removed
23061     */
23062    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23063        final boolean DEBUG_CLEAN_APKS = false;
23064        int [] users = userManager.getUserIds();
23065        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23066        while (psit.hasNext()) {
23067            PackageSetting ps = psit.next();
23068            if (ps.pkg == null) {
23069                continue;
23070            }
23071            final String packageName = ps.pkg.packageName;
23072            // Skip over if system app
23073            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23074                continue;
23075            }
23076            if (DEBUG_CLEAN_APKS) {
23077                Slog.i(TAG, "Checking package " + packageName);
23078            }
23079            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23080            if (keep) {
23081                if (DEBUG_CLEAN_APKS) {
23082                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23083                }
23084            } else {
23085                for (int i = 0; i < users.length; i++) {
23086                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23087                        keep = true;
23088                        if (DEBUG_CLEAN_APKS) {
23089                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23090                                    + users[i]);
23091                        }
23092                        break;
23093                    }
23094                }
23095            }
23096            if (!keep) {
23097                if (DEBUG_CLEAN_APKS) {
23098                    Slog.i(TAG, "  Removing package " + packageName);
23099                }
23100                mHandler.post(new Runnable() {
23101                    public void run() {
23102                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23103                                userHandle, 0);
23104                    } //end run
23105                });
23106            }
23107        }
23108    }
23109
23110    /** Called by UserManagerService */
23111    void createNewUser(int userId, String[] disallowedPackages) {
23112        synchronized (mInstallLock) {
23113            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23114        }
23115        synchronized (mPackages) {
23116            scheduleWritePackageRestrictionsLocked(userId);
23117            scheduleWritePackageListLocked(userId);
23118            applyFactoryDefaultBrowserLPw(userId);
23119            primeDomainVerificationsLPw(userId);
23120        }
23121    }
23122
23123    void onNewUserCreated(final int userId) {
23124        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23125        synchronized(mPackages) {
23126            // If permission review for legacy apps is required, we represent
23127            // dagerous permissions for such apps as always granted runtime
23128            // permissions to keep per user flag state whether review is needed.
23129            // Hence, if a new user is added we have to propagate dangerous
23130            // permission grants for these legacy apps.
23131            if (mSettings.mPermissions.mPermissionReviewRequired) {
23132// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23133                mPermissionManager.updateAllPermissions(
23134                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23135                        mPermissionCallback);
23136            }
23137        }
23138    }
23139
23140    @Override
23141    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23142        mContext.enforceCallingOrSelfPermission(
23143                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23144                "Only package verification agents can read the verifier device identity");
23145
23146        synchronized (mPackages) {
23147            return mSettings.getVerifierDeviceIdentityLPw();
23148        }
23149    }
23150
23151    @Override
23152    public void setPermissionEnforced(String permission, boolean enforced) {
23153        // TODO: Now that we no longer change GID for storage, this should to away.
23154        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23155                "setPermissionEnforced");
23156        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23157            synchronized (mPackages) {
23158                if (mSettings.mReadExternalStorageEnforced == null
23159                        || mSettings.mReadExternalStorageEnforced != enforced) {
23160                    mSettings.mReadExternalStorageEnforced =
23161                            enforced ? Boolean.TRUE : Boolean.FALSE;
23162                    mSettings.writeLPr();
23163                }
23164            }
23165            // kill any non-foreground processes so we restart them and
23166            // grant/revoke the GID.
23167            final IActivityManager am = ActivityManager.getService();
23168            if (am != null) {
23169                final long token = Binder.clearCallingIdentity();
23170                try {
23171                    am.killProcessesBelowForeground("setPermissionEnforcement");
23172                } catch (RemoteException e) {
23173                } finally {
23174                    Binder.restoreCallingIdentity(token);
23175                }
23176            }
23177        } else {
23178            throw new IllegalArgumentException("No selective enforcement for " + permission);
23179        }
23180    }
23181
23182    @Override
23183    @Deprecated
23184    public boolean isPermissionEnforced(String permission) {
23185        // allow instant applications
23186        return true;
23187    }
23188
23189    @Override
23190    public boolean isStorageLow() {
23191        // allow instant applications
23192        final long token = Binder.clearCallingIdentity();
23193        try {
23194            final DeviceStorageMonitorInternal
23195                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23196            if (dsm != null) {
23197                return dsm.isMemoryLow();
23198            } else {
23199                return false;
23200            }
23201        } finally {
23202            Binder.restoreCallingIdentity(token);
23203        }
23204    }
23205
23206    @Override
23207    public IPackageInstaller getPackageInstaller() {
23208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23209            return null;
23210        }
23211        return mInstallerService;
23212    }
23213
23214    @Override
23215    public IArtManager getArtManager() {
23216        return mArtManagerService;
23217    }
23218
23219    private boolean userNeedsBadging(int userId) {
23220        int index = mUserNeedsBadging.indexOfKey(userId);
23221        if (index < 0) {
23222            final UserInfo userInfo;
23223            final long token = Binder.clearCallingIdentity();
23224            try {
23225                userInfo = sUserManager.getUserInfo(userId);
23226            } finally {
23227                Binder.restoreCallingIdentity(token);
23228            }
23229            final boolean b;
23230            if (userInfo != null && userInfo.isManagedProfile()) {
23231                b = true;
23232            } else {
23233                b = false;
23234            }
23235            mUserNeedsBadging.put(userId, b);
23236            return b;
23237        }
23238        return mUserNeedsBadging.valueAt(index);
23239    }
23240
23241    @Override
23242    public KeySet getKeySetByAlias(String packageName, String alias) {
23243        if (packageName == null || alias == null) {
23244            return null;
23245        }
23246        synchronized(mPackages) {
23247            final PackageParser.Package pkg = mPackages.get(packageName);
23248            if (pkg == null) {
23249                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23250                throw new IllegalArgumentException("Unknown package: " + packageName);
23251            }
23252            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23253            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23254                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23255                throw new IllegalArgumentException("Unknown package: " + packageName);
23256            }
23257            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23258            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23259        }
23260    }
23261
23262    @Override
23263    public KeySet getSigningKeySet(String packageName) {
23264        if (packageName == null) {
23265            return null;
23266        }
23267        synchronized(mPackages) {
23268            final int callingUid = Binder.getCallingUid();
23269            final int callingUserId = UserHandle.getUserId(callingUid);
23270            final PackageParser.Package pkg = mPackages.get(packageName);
23271            if (pkg == null) {
23272                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23273                throw new IllegalArgumentException("Unknown package: " + packageName);
23274            }
23275            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23276            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23277                // filter and pretend the package doesn't exist
23278                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23279                        + ", uid:" + callingUid);
23280                throw new IllegalArgumentException("Unknown package: " + packageName);
23281            }
23282            if (pkg.applicationInfo.uid != callingUid
23283                    && Process.SYSTEM_UID != callingUid) {
23284                throw new SecurityException("May not access signing KeySet of other apps.");
23285            }
23286            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23287            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23288        }
23289    }
23290
23291    @Override
23292    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23293        final int callingUid = Binder.getCallingUid();
23294        if (getInstantAppPackageName(callingUid) != null) {
23295            return false;
23296        }
23297        if (packageName == null || ks == null) {
23298            return false;
23299        }
23300        synchronized(mPackages) {
23301            final PackageParser.Package pkg = mPackages.get(packageName);
23302            if (pkg == null
23303                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23304                            UserHandle.getUserId(callingUid))) {
23305                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23306                throw new IllegalArgumentException("Unknown package: " + packageName);
23307            }
23308            IBinder ksh = ks.getToken();
23309            if (ksh instanceof KeySetHandle) {
23310                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23311                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23312            }
23313            return false;
23314        }
23315    }
23316
23317    @Override
23318    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23319        final int callingUid = Binder.getCallingUid();
23320        if (getInstantAppPackageName(callingUid) != null) {
23321            return false;
23322        }
23323        if (packageName == null || ks == null) {
23324            return false;
23325        }
23326        synchronized(mPackages) {
23327            final PackageParser.Package pkg = mPackages.get(packageName);
23328            if (pkg == null
23329                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23330                            UserHandle.getUserId(callingUid))) {
23331                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23332                throw new IllegalArgumentException("Unknown package: " + packageName);
23333            }
23334            IBinder ksh = ks.getToken();
23335            if (ksh instanceof KeySetHandle) {
23336                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23337                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23338            }
23339            return false;
23340        }
23341    }
23342
23343    private void deletePackageIfUnusedLPr(final String packageName) {
23344        PackageSetting ps = mSettings.mPackages.get(packageName);
23345        if (ps == null) {
23346            return;
23347        }
23348        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23349            // TODO Implement atomic delete if package is unused
23350            // It is currently possible that the package will be deleted even if it is installed
23351            // after this method returns.
23352            mHandler.post(new Runnable() {
23353                public void run() {
23354                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23355                            0, PackageManager.DELETE_ALL_USERS);
23356                }
23357            });
23358        }
23359    }
23360
23361    /**
23362     * Check and throw if the given before/after packages would be considered a
23363     * downgrade.
23364     */
23365    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23366            throws PackageManagerException {
23367        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23368            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23369                    "Update version code " + after.versionCode + " is older than current "
23370                    + before.getLongVersionCode());
23371        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23372            if (after.baseRevisionCode < before.baseRevisionCode) {
23373                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23374                        "Update base revision code " + after.baseRevisionCode
23375                        + " is older than current " + before.baseRevisionCode);
23376            }
23377
23378            if (!ArrayUtils.isEmpty(after.splitNames)) {
23379                for (int i = 0; i < after.splitNames.length; i++) {
23380                    final String splitName = after.splitNames[i];
23381                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23382                    if (j != -1) {
23383                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23384                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23385                                    "Update split " + splitName + " revision code "
23386                                    + after.splitRevisionCodes[i] + " is older than current "
23387                                    + before.splitRevisionCodes[j]);
23388                        }
23389                    }
23390                }
23391            }
23392        }
23393    }
23394
23395    private static class MoveCallbacks extends Handler {
23396        private static final int MSG_CREATED = 1;
23397        private static final int MSG_STATUS_CHANGED = 2;
23398
23399        private final RemoteCallbackList<IPackageMoveObserver>
23400                mCallbacks = new RemoteCallbackList<>();
23401
23402        private final SparseIntArray mLastStatus = new SparseIntArray();
23403
23404        public MoveCallbacks(Looper looper) {
23405            super(looper);
23406        }
23407
23408        public void register(IPackageMoveObserver callback) {
23409            mCallbacks.register(callback);
23410        }
23411
23412        public void unregister(IPackageMoveObserver callback) {
23413            mCallbacks.unregister(callback);
23414        }
23415
23416        @Override
23417        public void handleMessage(Message msg) {
23418            final SomeArgs args = (SomeArgs) msg.obj;
23419            final int n = mCallbacks.beginBroadcast();
23420            for (int i = 0; i < n; i++) {
23421                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23422                try {
23423                    invokeCallback(callback, msg.what, args);
23424                } catch (RemoteException ignored) {
23425                }
23426            }
23427            mCallbacks.finishBroadcast();
23428            args.recycle();
23429        }
23430
23431        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23432                throws RemoteException {
23433            switch (what) {
23434                case MSG_CREATED: {
23435                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23436                    break;
23437                }
23438                case MSG_STATUS_CHANGED: {
23439                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23440                    break;
23441                }
23442            }
23443        }
23444
23445        private void notifyCreated(int moveId, Bundle extras) {
23446            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23447
23448            final SomeArgs args = SomeArgs.obtain();
23449            args.argi1 = moveId;
23450            args.arg2 = extras;
23451            obtainMessage(MSG_CREATED, args).sendToTarget();
23452        }
23453
23454        private void notifyStatusChanged(int moveId, int status) {
23455            notifyStatusChanged(moveId, status, -1);
23456        }
23457
23458        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23459            Slog.v(TAG, "Move " + moveId + " status " + status);
23460
23461            final SomeArgs args = SomeArgs.obtain();
23462            args.argi1 = moveId;
23463            args.argi2 = status;
23464            args.arg3 = estMillis;
23465            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23466
23467            synchronized (mLastStatus) {
23468                mLastStatus.put(moveId, status);
23469            }
23470        }
23471    }
23472
23473    private final static class OnPermissionChangeListeners extends Handler {
23474        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23475
23476        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23477                new RemoteCallbackList<>();
23478
23479        public OnPermissionChangeListeners(Looper looper) {
23480            super(looper);
23481        }
23482
23483        @Override
23484        public void handleMessage(Message msg) {
23485            switch (msg.what) {
23486                case MSG_ON_PERMISSIONS_CHANGED: {
23487                    final int uid = msg.arg1;
23488                    handleOnPermissionsChanged(uid);
23489                } break;
23490            }
23491        }
23492
23493        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23494            mPermissionListeners.register(listener);
23495
23496        }
23497
23498        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23499            mPermissionListeners.unregister(listener);
23500        }
23501
23502        public void onPermissionsChanged(int uid) {
23503            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23504                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23505            }
23506        }
23507
23508        private void handleOnPermissionsChanged(int uid) {
23509            final int count = mPermissionListeners.beginBroadcast();
23510            try {
23511                for (int i = 0; i < count; i++) {
23512                    IOnPermissionsChangeListener callback = mPermissionListeners
23513                            .getBroadcastItem(i);
23514                    try {
23515                        callback.onPermissionsChanged(uid);
23516                    } catch (RemoteException e) {
23517                        Log.e(TAG, "Permission listener is dead", e);
23518                    }
23519                }
23520            } finally {
23521                mPermissionListeners.finishBroadcast();
23522            }
23523        }
23524    }
23525
23526    private class PackageManagerNative extends IPackageManagerNative.Stub {
23527        @Override
23528        public String[] getNamesForUids(int[] uids) throws RemoteException {
23529            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23530            // massage results so they can be parsed by the native binder
23531            for (int i = results.length - 1; i >= 0; --i) {
23532                if (results[i] == null) {
23533                    results[i] = "";
23534                }
23535            }
23536            return results;
23537        }
23538
23539        // NB: this differentiates between preloads and sideloads
23540        @Override
23541        public String getInstallerForPackage(String packageName) throws RemoteException {
23542            final String installerName = getInstallerPackageName(packageName);
23543            if (!TextUtils.isEmpty(installerName)) {
23544                return installerName;
23545            }
23546            // differentiate between preload and sideload
23547            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23548            ApplicationInfo appInfo = getApplicationInfo(packageName,
23549                                    /*flags*/ 0,
23550                                    /*userId*/ callingUser);
23551            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23552                return "preload";
23553            }
23554            return "";
23555        }
23556
23557        @Override
23558        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23559            try {
23560                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23561                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23562                if (pInfo != null) {
23563                    return pInfo.getLongVersionCode();
23564                }
23565            } catch (Exception e) {
23566            }
23567            return 0;
23568        }
23569    }
23570
23571    private class PackageManagerInternalImpl extends PackageManagerInternal {
23572        @Override
23573        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23574                int flagValues, int userId) {
23575            PackageManagerService.this.updatePermissionFlags(
23576                    permName, packageName, flagMask, flagValues, userId);
23577        }
23578
23579        @Override
23580        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23581            SigningDetails sd = getSigningDetails(packageName);
23582            if (sd == null) {
23583                return false;
23584            }
23585            return sd.hasSha256Certificate(restoringFromSigHash,
23586                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23587        }
23588
23589        @Override
23590        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23591            SigningDetails sd = getSigningDetails(packageName);
23592            if (sd == null) {
23593                return false;
23594            }
23595            return sd.hasCertificate(restoringFromSig,
23596                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23597        }
23598
23599        @Override
23600        public boolean hasSignatureCapability(int serverUid, int clientUid,
23601                @SigningDetails.CertCapabilities int capability) {
23602            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23603            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23604            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23605                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23606
23607        }
23608
23609        private SigningDetails getSigningDetails(@NonNull String packageName) {
23610            synchronized (mPackages) {
23611                PackageParser.Package p = mPackages.get(packageName);
23612                if (p == null) {
23613                    return null;
23614                }
23615                return p.mSigningDetails;
23616            }
23617        }
23618
23619        private SigningDetails getSigningDetails(int uid) {
23620            synchronized (mPackages) {
23621                final int appId = UserHandle.getAppId(uid);
23622                final Object obj = mSettings.getUserIdLPr(appId);
23623                if (obj != null) {
23624                    if (obj instanceof SharedUserSetting) {
23625                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23626                    } else if (obj instanceof PackageSetting) {
23627                        final PackageSetting ps = (PackageSetting) obj;
23628                        return ps.signatures.mSigningDetails;
23629                    }
23630                }
23631                return SigningDetails.UNKNOWN;
23632            }
23633        }
23634
23635        @Override
23636        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23637            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23638        }
23639
23640        @Override
23641        public boolean isInstantApp(String packageName, int userId) {
23642            return PackageManagerService.this.isInstantApp(packageName, userId);
23643        }
23644
23645        @Override
23646        public String getInstantAppPackageName(int uid) {
23647            return PackageManagerService.this.getInstantAppPackageName(uid);
23648        }
23649
23650        @Override
23651        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23652            synchronized (mPackages) {
23653                return PackageManagerService.this.filterAppAccessLPr(
23654                        (PackageSetting) pkg.mExtras, callingUid, userId);
23655            }
23656        }
23657
23658        @Override
23659        public PackageParser.Package getPackage(String packageName) {
23660            synchronized (mPackages) {
23661                packageName = resolveInternalPackageNameLPr(
23662                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23663                return mPackages.get(packageName);
23664            }
23665        }
23666
23667        @Override
23668        public PackageList getPackageList(PackageListObserver observer) {
23669            synchronized (mPackages) {
23670                final int N = mPackages.size();
23671                final ArrayList<String> list = new ArrayList<>(N);
23672                for (int i = 0; i < N; i++) {
23673                    list.add(mPackages.keyAt(i));
23674                }
23675                final PackageList packageList = new PackageList(list, observer);
23676                if (observer != null) {
23677                    mPackageListObservers.add(packageList);
23678                }
23679                return packageList;
23680            }
23681        }
23682
23683        @Override
23684        public void removePackageListObserver(PackageListObserver observer) {
23685            synchronized (mPackages) {
23686                mPackageListObservers.remove(observer);
23687            }
23688        }
23689
23690        @Override
23691        public PackageParser.Package getDisabledPackage(String packageName) {
23692            synchronized (mPackages) {
23693                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23694                return (ps != null) ? ps.pkg : null;
23695            }
23696        }
23697
23698        @Override
23699        public String getKnownPackageName(int knownPackage, int userId) {
23700            switch(knownPackage) {
23701                case PackageManagerInternal.PACKAGE_BROWSER:
23702                    return getDefaultBrowserPackageName(userId);
23703                case PackageManagerInternal.PACKAGE_INSTALLER:
23704                    return mRequiredInstallerPackage;
23705                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23706                    return mSetupWizardPackage;
23707                case PackageManagerInternal.PACKAGE_SYSTEM:
23708                    return "android";
23709                case PackageManagerInternal.PACKAGE_VERIFIER:
23710                    return mRequiredVerifierPackage;
23711                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23712                    return mSystemTextClassifierPackage;
23713            }
23714            return null;
23715        }
23716
23717        @Override
23718        public boolean isResolveActivityComponent(ComponentInfo component) {
23719            return mResolveActivity.packageName.equals(component.packageName)
23720                    && mResolveActivity.name.equals(component.name);
23721        }
23722
23723        @Override
23724        public void setLocationPackagesProvider(PackagesProvider provider) {
23725            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23726        }
23727
23728        @Override
23729        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23730            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23731        }
23732
23733        @Override
23734        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23735            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23736        }
23737
23738        @Override
23739        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23740            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23741        }
23742
23743        @Override
23744        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23745            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23746        }
23747
23748        @Override
23749        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23750            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23751        }
23752
23753        @Override
23754        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23755            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23756        }
23757
23758        @Override
23759        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23760            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23761        }
23762
23763        @Override
23764        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23765            synchronized (mPackages) {
23766                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23767            }
23768            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23769        }
23770
23771        @Override
23772        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23773            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23774                    packageName, userId);
23775        }
23776
23777        @Override
23778        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23779            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23780                    packageName, userId);
23781        }
23782
23783        @Override
23784        public void setKeepUninstalledPackages(final List<String> packageList) {
23785            Preconditions.checkNotNull(packageList);
23786            List<String> removedFromList = null;
23787            synchronized (mPackages) {
23788                if (mKeepUninstalledPackages != null) {
23789                    final int packagesCount = mKeepUninstalledPackages.size();
23790                    for (int i = 0; i < packagesCount; i++) {
23791                        String oldPackage = mKeepUninstalledPackages.get(i);
23792                        if (packageList != null && packageList.contains(oldPackage)) {
23793                            continue;
23794                        }
23795                        if (removedFromList == null) {
23796                            removedFromList = new ArrayList<>();
23797                        }
23798                        removedFromList.add(oldPackage);
23799                    }
23800                }
23801                mKeepUninstalledPackages = new ArrayList<>(packageList);
23802                if (removedFromList != null) {
23803                    final int removedCount = removedFromList.size();
23804                    for (int i = 0; i < removedCount; i++) {
23805                        deletePackageIfUnusedLPr(removedFromList.get(i));
23806                    }
23807                }
23808            }
23809        }
23810
23811        @Override
23812        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23813            synchronized (mPackages) {
23814                return mPermissionManager.isPermissionsReviewRequired(
23815                        mPackages.get(packageName), userId);
23816            }
23817        }
23818
23819        @Override
23820        public PackageInfo getPackageInfo(
23821                String packageName, int flags, int filterCallingUid, int userId) {
23822            return PackageManagerService.this
23823                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23824                            flags, filterCallingUid, userId);
23825        }
23826
23827        @Override
23828        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23829            synchronized (mPackages) {
23830                final PackageSetting ps = mSettings.mPackages.get(packageName);
23831                PersistableBundle launcherExtras = null;
23832                if (ps != null) {
23833                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23834                }
23835                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23836            }
23837        }
23838
23839        @Override
23840        public boolean isPackageSuspended(String packageName, int userId) {
23841            synchronized (mPackages) {
23842                final PackageSetting ps = mSettings.mPackages.get(packageName);
23843                return (ps != null) ? ps.getSuspended(userId) : false;
23844            }
23845        }
23846
23847        @Override
23848        public String getSuspendingPackage(String suspendedPackage, int userId) {
23849            synchronized (mPackages) {
23850                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23851                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23852            }
23853        }
23854
23855        @Override
23856        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23857            synchronized (mPackages) {
23858                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23859                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23860            }
23861        }
23862
23863        @Override
23864        public int getPackageUid(String packageName, int flags, int userId) {
23865            return PackageManagerService.this
23866                    .getPackageUid(packageName, flags, userId);
23867        }
23868
23869        @Override
23870        public ApplicationInfo getApplicationInfo(
23871                String packageName, int flags, int filterCallingUid, int userId) {
23872            return PackageManagerService.this
23873                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23874        }
23875
23876        @Override
23877        public ActivityInfo getActivityInfo(
23878                ComponentName component, int flags, int filterCallingUid, int userId) {
23879            return PackageManagerService.this
23880                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23881        }
23882
23883        @Override
23884        public List<ResolveInfo> queryIntentActivities(
23885                Intent intent, int flags, int filterCallingUid, int userId) {
23886            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23887            return PackageManagerService.this
23888                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23889                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23890        }
23891
23892        @Override
23893        public List<ResolveInfo> queryIntentServices(
23894                Intent intent, int flags, int callingUid, int userId) {
23895            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23896            return PackageManagerService.this
23897                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23898                            false);
23899        }
23900
23901        @Override
23902        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23903                int userId) {
23904            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23905        }
23906
23907        @Override
23908        public ComponentName getDefaultHomeActivity(int userId) {
23909            return PackageManagerService.this.getDefaultHomeActivity(userId);
23910        }
23911
23912        @Override
23913        public void setDeviceAndProfileOwnerPackages(
23914                int deviceOwnerUserId, String deviceOwnerPackage,
23915                SparseArray<String> profileOwnerPackages) {
23916            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23917                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23918        }
23919
23920        @Override
23921        public boolean isPackageDataProtected(int userId, String packageName) {
23922            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23923        }
23924
23925        @Override
23926        public boolean isPackageStateProtected(String packageName, int userId) {
23927            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23928        }
23929
23930        @Override
23931        public boolean isPackageEphemeral(int userId, String packageName) {
23932            synchronized (mPackages) {
23933                final PackageSetting ps = mSettings.mPackages.get(packageName);
23934                return ps != null ? ps.getInstantApp(userId) : false;
23935            }
23936        }
23937
23938        @Override
23939        public boolean wasPackageEverLaunched(String packageName, int userId) {
23940            synchronized (mPackages) {
23941                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23942            }
23943        }
23944
23945        @Override
23946        public void grantRuntimePermission(String packageName, String permName, int userId,
23947                boolean overridePolicy) {
23948            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23949                    permName, packageName, overridePolicy, getCallingUid(), userId,
23950                    mPermissionCallback);
23951        }
23952
23953        @Override
23954        public void revokeRuntimePermission(String packageName, String permName, int userId,
23955                boolean overridePolicy) {
23956            mPermissionManager.revokeRuntimePermission(
23957                    permName, packageName, overridePolicy, getCallingUid(), userId,
23958                    mPermissionCallback);
23959        }
23960
23961        @Override
23962        public String getNameForUid(int uid) {
23963            return PackageManagerService.this.getNameForUid(uid);
23964        }
23965
23966        @Override
23967        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23968                Intent origIntent, String resolvedType, String callingPackage,
23969                Bundle verificationBundle, int userId) {
23970            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23971                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23972                    userId);
23973        }
23974
23975        @Override
23976        public void grantEphemeralAccess(int userId, Intent intent,
23977                int targetAppId, int ephemeralAppId) {
23978            synchronized (mPackages) {
23979                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23980                        targetAppId, ephemeralAppId);
23981            }
23982        }
23983
23984        @Override
23985        public boolean isInstantAppInstallerComponent(ComponentName component) {
23986            synchronized (mPackages) {
23987                return mInstantAppInstallerActivity != null
23988                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23989            }
23990        }
23991
23992        @Override
23993        public void pruneInstantApps() {
23994            mInstantAppRegistry.pruneInstantApps();
23995        }
23996
23997        @Override
23998        public String getSetupWizardPackageName() {
23999            return mSetupWizardPackage;
24000        }
24001
24002        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24003            if (policy != null) {
24004                mExternalSourcesPolicy = policy;
24005            }
24006        }
24007
24008        @Override
24009        public boolean isPackagePersistent(String packageName) {
24010            synchronized (mPackages) {
24011                PackageParser.Package pkg = mPackages.get(packageName);
24012                return pkg != null
24013                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24014                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24015                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24016                        : false;
24017            }
24018        }
24019
24020        @Override
24021        public boolean isLegacySystemApp(Package pkg) {
24022            synchronized (mPackages) {
24023                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24024                return mPromoteSystemApps
24025                        && ps.isSystem()
24026                        && mExistingSystemPackages.contains(ps.name);
24027            }
24028        }
24029
24030        @Override
24031        public List<PackageInfo> getOverlayPackages(int userId) {
24032            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24033            synchronized (mPackages) {
24034                for (PackageParser.Package p : mPackages.values()) {
24035                    if (p.mOverlayTarget != null) {
24036                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24037                        if (pkg != null) {
24038                            overlayPackages.add(pkg);
24039                        }
24040                    }
24041                }
24042            }
24043            return overlayPackages;
24044        }
24045
24046        @Override
24047        public List<String> getTargetPackageNames(int userId) {
24048            List<String> targetPackages = new ArrayList<>();
24049            synchronized (mPackages) {
24050                for (PackageParser.Package p : mPackages.values()) {
24051                    if (p.mOverlayTarget == null) {
24052                        targetPackages.add(p.packageName);
24053                    }
24054                }
24055            }
24056            return targetPackages;
24057        }
24058
24059        @Override
24060        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24061                @Nullable List<String> overlayPackageNames) {
24062            synchronized (mPackages) {
24063                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24064                    Slog.e(TAG, "failed to find package " + targetPackageName);
24065                    return false;
24066                }
24067                ArrayList<String> overlayPaths = null;
24068                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24069                    final int N = overlayPackageNames.size();
24070                    overlayPaths = new ArrayList<>(N);
24071                    for (int i = 0; i < N; i++) {
24072                        final String packageName = overlayPackageNames.get(i);
24073                        final PackageParser.Package pkg = mPackages.get(packageName);
24074                        if (pkg == null) {
24075                            Slog.e(TAG, "failed to find package " + packageName);
24076                            return false;
24077                        }
24078                        overlayPaths.add(pkg.baseCodePath);
24079                    }
24080                }
24081
24082                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24083                ps.setOverlayPaths(overlayPaths, userId);
24084                return true;
24085            }
24086        }
24087
24088        @Override
24089        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24090                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24091            return resolveIntentInternal(
24092                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24093        }
24094
24095        @Override
24096        public ResolveInfo resolveService(Intent intent, String resolvedType,
24097                int flags, int userId, int callingUid) {
24098            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24099        }
24100
24101        @Override
24102        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24103            return PackageManagerService.this.resolveContentProviderInternal(
24104                    name, flags, userId);
24105        }
24106
24107        @Override
24108        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24109            synchronized (mPackages) {
24110                mIsolatedOwners.put(isolatedUid, ownerUid);
24111            }
24112        }
24113
24114        @Override
24115        public void removeIsolatedUid(int isolatedUid) {
24116            synchronized (mPackages) {
24117                mIsolatedOwners.delete(isolatedUid);
24118            }
24119        }
24120
24121        @Override
24122        public int getUidTargetSdkVersion(int uid) {
24123            synchronized (mPackages) {
24124                return getUidTargetSdkVersionLockedLPr(uid);
24125            }
24126        }
24127
24128        @Override
24129        public int getPackageTargetSdkVersion(String packageName) {
24130            synchronized (mPackages) {
24131                return getPackageTargetSdkVersionLockedLPr(packageName);
24132            }
24133        }
24134
24135        @Override
24136        public boolean canAccessInstantApps(int callingUid, int userId) {
24137            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24138        }
24139
24140        @Override
24141        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24142            synchronized (mPackages) {
24143                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24144                return !PackageManagerService.this.filterAppAccessLPr(
24145                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24146            }
24147        }
24148
24149        @Override
24150        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24151            synchronized (mPackages) {
24152                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24153            }
24154        }
24155
24156        @Override
24157        public void notifyPackageUse(String packageName, int reason) {
24158            synchronized (mPackages) {
24159                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24160            }
24161        }
24162    }
24163
24164    @Override
24165    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24166        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24167        synchronized (mPackages) {
24168            final long identity = Binder.clearCallingIdentity();
24169            try {
24170                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24171                        packageNames, userId);
24172            } finally {
24173                Binder.restoreCallingIdentity(identity);
24174            }
24175        }
24176    }
24177
24178    @Override
24179    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24180        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24181        synchronized (mPackages) {
24182            final long identity = Binder.clearCallingIdentity();
24183            try {
24184                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24185                        packageNames, userId);
24186            } finally {
24187                Binder.restoreCallingIdentity(identity);
24188            }
24189        }
24190    }
24191
24192    @Override
24193    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24194            String[] packageNames, int userId) {
24195        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24196        synchronized (mPackages) {
24197            Binder.withCleanCallingIdentity( () -> {
24198                mDefaultPermissionPolicy.
24199                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24200                                packageNames, userId);
24201            });
24202        }
24203    }
24204
24205    @Override
24206    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24207            String[] packageNames, int userId) {
24208        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24209        synchronized (mPackages) {
24210            Binder.withCleanCallingIdentity( () -> {
24211                mDefaultPermissionPolicy.
24212                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24213                                packageNames, userId);
24214            });
24215        }
24216    }
24217
24218    @Override
24219    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24220        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24221        synchronized (mPackages) {
24222            final long identity = Binder.clearCallingIdentity();
24223            try {
24224                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24225                        packageName, userId);
24226            } finally {
24227                Binder.restoreCallingIdentity(identity);
24228            }
24229        }
24230    }
24231
24232    @Override
24233    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24234        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24235        synchronized (mPackages) {
24236            final long identity = Binder.clearCallingIdentity();
24237            try {
24238                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24239            } finally {
24240                Binder.restoreCallingIdentity(identity);
24241            }
24242        }
24243    }
24244
24245    private static void enforceSystemOrPhoneCaller(String tag) {
24246        int callingUid = Binder.getCallingUid();
24247        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24248            throw new SecurityException(
24249                    "Cannot call " + tag + " from UID " + callingUid);
24250        }
24251    }
24252
24253    boolean isHistoricalPackageUsageAvailable() {
24254        return mPackageUsage.isHistoricalPackageUsageAvailable();
24255    }
24256
24257    /**
24258     * Return a <b>copy</b> of the collection of packages known to the package manager.
24259     * @return A copy of the values of mPackages.
24260     */
24261    Collection<PackageParser.Package> getPackages() {
24262        synchronized (mPackages) {
24263            return new ArrayList<>(mPackages.values());
24264        }
24265    }
24266
24267    /**
24268     * Logs process start information (including base APK hash) to the security log.
24269     * @hide
24270     */
24271    @Override
24272    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24273            String apkFile, int pid) {
24274        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24275            return;
24276        }
24277        if (!SecurityLog.isLoggingEnabled()) {
24278            return;
24279        }
24280        Bundle data = new Bundle();
24281        data.putLong("startTimestamp", System.currentTimeMillis());
24282        data.putString("processName", processName);
24283        data.putInt("uid", uid);
24284        data.putString("seinfo", seinfo);
24285        data.putString("apkFile", apkFile);
24286        data.putInt("pid", pid);
24287        Message msg = mProcessLoggingHandler.obtainMessage(
24288                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24289        msg.setData(data);
24290        mProcessLoggingHandler.sendMessage(msg);
24291    }
24292
24293    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24294        return mCompilerStats.getPackageStats(pkgName);
24295    }
24296
24297    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24298        return getOrCreateCompilerPackageStats(pkg.packageName);
24299    }
24300
24301    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24302        return mCompilerStats.getOrCreatePackageStats(pkgName);
24303    }
24304
24305    public void deleteCompilerPackageStats(String pkgName) {
24306        mCompilerStats.deletePackageStats(pkgName);
24307    }
24308
24309    @Override
24310    public int getInstallReason(String packageName, int userId) {
24311        final int callingUid = Binder.getCallingUid();
24312        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24313                true /* requireFullPermission */, false /* checkShell */,
24314                "get install reason");
24315        synchronized (mPackages) {
24316            final PackageSetting ps = mSettings.mPackages.get(packageName);
24317            if (filterAppAccessLPr(ps, callingUid, userId)) {
24318                return PackageManager.INSTALL_REASON_UNKNOWN;
24319            }
24320            if (ps != null) {
24321                return ps.getInstallReason(userId);
24322            }
24323        }
24324        return PackageManager.INSTALL_REASON_UNKNOWN;
24325    }
24326
24327    @Override
24328    public boolean canRequestPackageInstalls(String packageName, int userId) {
24329        return canRequestPackageInstallsInternal(packageName, 0, userId,
24330                true /* throwIfPermNotDeclared*/);
24331    }
24332
24333    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24334            boolean throwIfPermNotDeclared) {
24335        int callingUid = Binder.getCallingUid();
24336        int uid = getPackageUid(packageName, 0, userId);
24337        if (callingUid != uid && callingUid != Process.ROOT_UID
24338                && callingUid != Process.SYSTEM_UID) {
24339            throw new SecurityException(
24340                    "Caller uid " + callingUid + " does not own package " + packageName);
24341        }
24342        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24343        if (info == null) {
24344            return false;
24345        }
24346        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24347            return false;
24348        }
24349        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24350        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24351        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24352            if (throwIfPermNotDeclared) {
24353                throw new SecurityException("Need to declare " + appOpPermission
24354                        + " to call this api");
24355            } else {
24356                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24357                return false;
24358            }
24359        }
24360        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24361            return false;
24362        }
24363        if (mExternalSourcesPolicy != null) {
24364            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24365            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24366                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24367            }
24368        }
24369        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24370    }
24371
24372    @Override
24373    public ComponentName getInstantAppResolverSettingsComponent() {
24374        return mInstantAppResolverSettingsComponent;
24375    }
24376
24377    @Override
24378    public ComponentName getInstantAppInstallerComponent() {
24379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24380            return null;
24381        }
24382        return mInstantAppInstallerActivity == null
24383                ? null : mInstantAppInstallerActivity.getComponentName();
24384    }
24385
24386    @Override
24387    public String getInstantAppAndroidId(String packageName, int userId) {
24388        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24389                "getInstantAppAndroidId");
24390        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24391                true /* requireFullPermission */, false /* checkShell */,
24392                "getInstantAppAndroidId");
24393        // Make sure the target is an Instant App.
24394        if (!isInstantApp(packageName, userId)) {
24395            return null;
24396        }
24397        synchronized (mPackages) {
24398            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24399        }
24400    }
24401
24402    boolean canHaveOatDir(String packageName) {
24403        synchronized (mPackages) {
24404            PackageParser.Package p = mPackages.get(packageName);
24405            if (p == null) {
24406                return false;
24407            }
24408            return p.canHaveOatDir();
24409        }
24410    }
24411
24412    private String getOatDir(PackageParser.Package pkg) {
24413        if (!pkg.canHaveOatDir()) {
24414            return null;
24415        }
24416        File codePath = new File(pkg.codePath);
24417        if (codePath.isDirectory()) {
24418            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24419        }
24420        return null;
24421    }
24422
24423    void deleteOatArtifactsOfPackage(String packageName) {
24424        final String[] instructionSets;
24425        final List<String> codePaths;
24426        final String oatDir;
24427        final PackageParser.Package pkg;
24428        synchronized (mPackages) {
24429            pkg = mPackages.get(packageName);
24430        }
24431        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24432        codePaths = pkg.getAllCodePaths();
24433        oatDir = getOatDir(pkg);
24434
24435        for (String codePath : codePaths) {
24436            for (String isa : instructionSets) {
24437                try {
24438                    mInstaller.deleteOdex(codePath, isa, oatDir);
24439                } catch (InstallerException e) {
24440                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24441                }
24442            }
24443        }
24444    }
24445
24446    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24447        Set<String> unusedPackages = new HashSet<>();
24448        long currentTimeInMillis = System.currentTimeMillis();
24449        synchronized (mPackages) {
24450            for (PackageParser.Package pkg : mPackages.values()) {
24451                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24452                if (ps == null) {
24453                    continue;
24454                }
24455                PackageDexUsage.PackageUseInfo packageUseInfo =
24456                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24457                if (PackageManagerServiceUtils
24458                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24459                                downgradeTimeThresholdMillis, packageUseInfo,
24460                                pkg.getLatestPackageUseTimeInMills(),
24461                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24462                    unusedPackages.add(pkg.packageName);
24463                }
24464            }
24465        }
24466        return unusedPackages;
24467    }
24468
24469    @Override
24470    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24471            int userId) {
24472        final int callingUid = Binder.getCallingUid();
24473        final int callingAppId = UserHandle.getAppId(callingUid);
24474
24475        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24476                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24477
24478        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24479                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24480            throw new SecurityException("Caller must have the "
24481                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24482        }
24483
24484        synchronized(mPackages) {
24485            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24486            scheduleWritePackageRestrictionsLocked(userId);
24487        }
24488    }
24489
24490    @Nullable
24491    @Override
24492    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24493        final int callingUid = Binder.getCallingUid();
24494        final int callingAppId = UserHandle.getAppId(callingUid);
24495
24496        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24497                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24498
24499        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24500                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24501            throw new SecurityException("Caller must have the "
24502                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24503        }
24504
24505        synchronized(mPackages) {
24506            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24507        }
24508    }
24509
24510    @Override
24511    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24512        final int callingUid = Binder.getCallingUid();
24513        final int callingAppId = UserHandle.getAppId(callingUid);
24514
24515        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24516                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24517
24518        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24519                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24520            throw new SecurityException("Caller must have the "
24521                    + MANAGE_DEVICE_ADMINS + " permission.");
24522        }
24523
24524        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24525    }
24526}
24527
24528interface PackageSender {
24529    /**
24530     * @param userIds User IDs where the action occurred on a full application
24531     * @param instantUserIds User IDs where the action occurred on an instant application
24532     */
24533    void sendPackageBroadcast(final String action, final String pkg,
24534        final Bundle extras, final int flags, final String targetPkg,
24535        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24536    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24537        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24538    void notifyPackageAdded(String packageName);
24539    void notifyPackageRemoved(String packageName);
24540}
24541