PackageManagerService.java revision 5da867597eb31c9e2296928c4a21200610747508
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_SUCCEEDED) {
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 " + pkgSetting.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                // If the system app is part of a shared user we allow that shared user to change
10202                // signatures as well in part as part of an OTA.
10203                if (signatureCheckPs.sharedUser != null) {
10204                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10205                }
10206                // File a report about this.
10207                String msg = "System package " + pkg.packageName
10208                        + " signature changed; retaining data.";
10209                reportSettingsProblem(Log.WARN, msg);
10210            } catch (IllegalArgumentException e) {
10211
10212                // should never happen: certs matched when checking, but not when comparing
10213                // old to new for sharedUser
10214                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10215                        "Signing certificates comparison made on incomparable signing details"
10216                        + " but somehow passed verifySignatures!");
10217            }
10218        }
10219
10220        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10221            // This package wants to adopt ownership of permissions from
10222            // another package.
10223            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10224                final String origName = pkg.mAdoptPermissions.get(i);
10225                final PackageSetting orig = mSettings.getPackageLPr(origName);
10226                if (orig != null) {
10227                    if (verifyPackageUpdateLPr(orig, pkg)) {
10228                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10229                                + pkg.packageName);
10230                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10231                    }
10232                }
10233            }
10234        }
10235
10236        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10237            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10238                final String codePathString = changedAbiCodePath.get(i);
10239                try {
10240                    mInstaller.rmdex(codePathString,
10241                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10242                } catch (InstallerException ignored) {
10243                }
10244            }
10245        }
10246
10247        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10248            if (oldPkgSetting != null) {
10249                synchronized (mPackages) {
10250                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10251                }
10252            }
10253        } else {
10254            final int userId = user == null ? 0 : user.getIdentifier();
10255            // Modify state for the given package setting
10256            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10257                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10258            if (pkgSetting.getInstantApp(userId)) {
10259                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10260            }
10261        }
10262    }
10263
10264    /**
10265     * Returns the "real" name of the package.
10266     * <p>This may differ from the package's actual name if the application has already
10267     * been installed under one of this package's original names.
10268     */
10269    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10270            @Nullable String renamedPkgName) {
10271        if (isPackageRenamed(pkg, renamedPkgName)) {
10272            return pkg.mRealPackage;
10273        }
10274        return null;
10275    }
10276
10277    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10278    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10279            @Nullable String renamedPkgName) {
10280        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10281    }
10282
10283    /**
10284     * Returns the original package setting.
10285     * <p>A package can migrate its name during an update. In this scenario, a package
10286     * designates a set of names that it considers as one of its original names.
10287     * <p>An original package must be signed identically and it must have the same
10288     * shared user [if any].
10289     */
10290    @GuardedBy("mPackages")
10291    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10292            @Nullable String renamedPkgName) {
10293        if (!isPackageRenamed(pkg, renamedPkgName)) {
10294            return null;
10295        }
10296        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10297            final PackageSetting originalPs =
10298                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10299            if (originalPs != null) {
10300                // the package is already installed under its original name...
10301                // but, should we use it?
10302                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10303                    // the new package is incompatible with the original
10304                    continue;
10305                } else if (originalPs.sharedUser != null) {
10306                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10307                        // the shared user id is incompatible with the original
10308                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10309                                + " to " + pkg.packageName + ": old uid "
10310                                + originalPs.sharedUser.name
10311                                + " differs from " + pkg.mSharedUserId);
10312                        continue;
10313                    }
10314                    // TODO: Add case when shared user id is added [b/28144775]
10315                } else {
10316                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10317                            + pkg.packageName + " to old name " + originalPs.name);
10318                }
10319                return originalPs;
10320            }
10321        }
10322        return null;
10323    }
10324
10325    /**
10326     * Renames the package if it was installed under a different name.
10327     * <p>When we've already installed the package under an original name, update
10328     * the new package so we can continue to have the old name.
10329     */
10330    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10331            @NonNull String renamedPackageName) {
10332        if (pkg.mOriginalPackages == null
10333                || !pkg.mOriginalPackages.contains(renamedPackageName)
10334                || pkg.packageName.equals(renamedPackageName)) {
10335            return;
10336        }
10337        pkg.setPackageName(renamedPackageName);
10338    }
10339
10340    /**
10341     * Just scans the package without any side effects.
10342     * <p>Not entirely true at the moment. There is still one side effect -- this
10343     * method potentially modifies a live {@link PackageSetting} object representing
10344     * the package being scanned. This will be resolved in the future.
10345     *
10346     * @param request Information about the package to be scanned
10347     * @param isUnderFactoryTest Whether or not the device is under factory test
10348     * @param currentTime The current time, in millis
10349     * @return The results of the scan
10350     */
10351    @GuardedBy("mInstallLock")
10352    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10353            boolean isUnderFactoryTest, long currentTime)
10354                    throws PackageManagerException {
10355        final PackageParser.Package pkg = request.pkg;
10356        PackageSetting pkgSetting = request.pkgSetting;
10357        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10358        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10359        final @ParseFlags int parseFlags = request.parseFlags;
10360        final @ScanFlags int scanFlags = request.scanFlags;
10361        final String realPkgName = request.realPkgName;
10362        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10363        final UserHandle user = request.user;
10364        final boolean isPlatformPackage = request.isPlatformPackage;
10365
10366        List<String> changedAbiCodePath = null;
10367
10368        if (DEBUG_PACKAGE_SCANNING) {
10369            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10370                Log.d(TAG, "Scanning package " + pkg.packageName);
10371        }
10372
10373        if (Build.IS_DEBUGGABLE &&
10374                pkg.isPrivileged() &&
10375                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10376            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10377        }
10378
10379        // Initialize package source and resource directories
10380        final File scanFile = new File(pkg.codePath);
10381        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10382        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10383
10384        // We keep references to the derived CPU Abis from settings in oder to reuse
10385        // them in the case where we're not upgrading or booting for the first time.
10386        String primaryCpuAbiFromSettings = null;
10387        String secondaryCpuAbiFromSettings = null;
10388        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10389
10390        if (!needToDeriveAbi) {
10391            if (pkgSetting != null) {
10392                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10393                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10394            } else {
10395                // Re-scanning a system package after uninstalling updates; need to derive ABI
10396                needToDeriveAbi = true;
10397            }
10398        }
10399
10400        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10401            PackageManagerService.reportSettingsProblem(Log.WARN,
10402                    "Package " + pkg.packageName + " shared user changed from "
10403                            + (pkgSetting.sharedUser != null
10404                            ? pkgSetting.sharedUser.name : "<nothing>")
10405                            + " to "
10406                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10407                            + "; replacing with new");
10408            pkgSetting = null;
10409        }
10410
10411        String[] usesStaticLibraries = null;
10412        if (pkg.usesStaticLibraries != null) {
10413            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10414            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10415        }
10416        final boolean createNewPackage = (pkgSetting == null);
10417        if (createNewPackage) {
10418            final String parentPackageName = (pkg.parentPackage != null)
10419                    ? pkg.parentPackage.packageName : null;
10420            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10421            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10422            // REMOVE SharedUserSetting from method; update in a separate call
10423            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10424                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10425                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10426                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10427                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10428                    user, true /*allowInstall*/, instantApp, virtualPreload,
10429                    parentPackageName, pkg.getChildPackageNames(),
10430                    UserManagerService.getInstance(), usesStaticLibraries,
10431                    pkg.usesStaticLibrariesVersions);
10432        } else {
10433            // REMOVE SharedUserSetting from method; update in a separate call.
10434            //
10435            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10436            // secondaryCpuAbi are not known at this point so we always update them
10437            // to null here, only to reset them at a later point.
10438            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10439                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10440                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10441                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10442                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10443                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10444        }
10445        if (createNewPackage && originalPkgSetting != null) {
10446            // This is the initial transition from the original package, so,
10447            // fix up the new package's name now. We must do this after looking
10448            // up the package under its new name, so getPackageLP takes care of
10449            // fiddling things correctly.
10450            pkg.setPackageName(originalPkgSetting.name);
10451
10452            // File a report about this.
10453            String msg = "New package " + pkgSetting.realName
10454                    + " renamed to replace old package " + pkgSetting.name;
10455            reportSettingsProblem(Log.WARN, msg);
10456        }
10457
10458        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10459        // for existing packages, change the install state; but, only if it's explicitly specified
10460        if (!createNewPackage) {
10461            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10462            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10463            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10464        }
10465
10466        if (disabledPkgSetting != null) {
10467            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10468        }
10469
10470        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10471        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10472        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10473        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10474        // least restrictive selinux domain.
10475        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10476        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10477        // ensures that all packages continue to run in the same selinux domain.
10478        final int targetSdkVersion =
10479            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10480            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10481        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10482        // They currently can be if the sharedUser apps are signed with the platform key.
10483        final boolean isPrivileged = (sharedUserSetting != null) ?
10484            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10485
10486        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10487                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10488        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10489                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10490
10491        pkg.mExtras = pkgSetting;
10492        pkg.applicationInfo.processName = fixProcessName(
10493                pkg.applicationInfo.packageName,
10494                pkg.applicationInfo.processName);
10495
10496        if (!isPlatformPackage) {
10497            // Get all of our default paths setup
10498            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10499        }
10500
10501        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10502
10503        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10504            if (needToDeriveAbi) {
10505                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10506                final boolean extractNativeLibs = !pkg.isLibrary();
10507                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10508                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10509
10510                // Some system apps still use directory structure for native libraries
10511                // in which case we might end up not detecting abi solely based on apk
10512                // structure. Try to detect abi based on directory structure.
10513                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10514                        pkg.applicationInfo.primaryCpuAbi == null) {
10515                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10516                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10517                }
10518            } else {
10519                // This is not a first boot or an upgrade, don't bother deriving the
10520                // ABI during the scan. Instead, trust the value that was stored in the
10521                // package setting.
10522                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10523                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10524
10525                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10526
10527                if (DEBUG_ABI_SELECTION) {
10528                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10529                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10530                            pkg.applicationInfo.secondaryCpuAbi);
10531                }
10532            }
10533        } else {
10534            if ((scanFlags & SCAN_MOVE) != 0) {
10535                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10536                // but we already have this packages package info in the PackageSetting. We just
10537                // use that and derive the native library path based on the new codepath.
10538                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10539                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10540            }
10541
10542            // Set native library paths again. For moves, the path will be updated based on the
10543            // ABIs we've determined above. For non-moves, the path will be updated based on the
10544            // ABIs we determined during compilation, but the path will depend on the final
10545            // package path (after the rename away from the stage path).
10546            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10547        }
10548
10549        // This is a special case for the "system" package, where the ABI is
10550        // dictated by the zygote configuration (and init.rc). We should keep track
10551        // of this ABI so that we can deal with "normal" applications that run under
10552        // the same UID correctly.
10553        if (isPlatformPackage) {
10554            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10555                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10556        }
10557
10558        // If there's a mismatch between the abi-override in the package setting
10559        // and the abiOverride specified for the install. Warn about this because we
10560        // would've already compiled the app without taking the package setting into
10561        // account.
10562        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10563            if (cpuAbiOverride == null && pkg.packageName != null) {
10564                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10565                        " for package " + pkg.packageName);
10566            }
10567        }
10568
10569        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10570        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10571        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10572
10573        // Copy the derived override back to the parsed package, so that we can
10574        // update the package settings accordingly.
10575        pkg.cpuAbiOverride = cpuAbiOverride;
10576
10577        if (DEBUG_ABI_SELECTION) {
10578            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10579                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10580                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10581        }
10582
10583        // Push the derived path down into PackageSettings so we know what to
10584        // clean up at uninstall time.
10585        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10586
10587        if (DEBUG_ABI_SELECTION) {
10588            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10589                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10590                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10591        }
10592
10593        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10594            // We don't do this here during boot because we can do it all
10595            // at once after scanning all existing packages.
10596            //
10597            // We also do this *before* we perform dexopt on this package, so that
10598            // we can avoid redundant dexopts, and also to make sure we've got the
10599            // code and package path correct.
10600            changedAbiCodePath =
10601                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10602        }
10603
10604        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10605                android.Manifest.permission.FACTORY_TEST)) {
10606            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10607        }
10608
10609        if (isSystemApp(pkg)) {
10610            pkgSetting.isOrphaned = true;
10611        }
10612
10613        // Take care of first install / last update times.
10614        final long scanFileTime = getLastModifiedTime(pkg);
10615        if (currentTime != 0) {
10616            if (pkgSetting.firstInstallTime == 0) {
10617                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10618            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10619                pkgSetting.lastUpdateTime = currentTime;
10620            }
10621        } else if (pkgSetting.firstInstallTime == 0) {
10622            // We need *something*.  Take time time stamp of the file.
10623            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10624        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10625            if (scanFileTime != pkgSetting.timeStamp) {
10626                // A package on the system image has changed; consider this
10627                // to be an update.
10628                pkgSetting.lastUpdateTime = scanFileTime;
10629            }
10630        }
10631        pkgSetting.setTimeStamp(scanFileTime);
10632
10633        pkgSetting.pkg = pkg;
10634        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10635        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10636            pkgSetting.versionCode = pkg.getLongVersionCode();
10637        }
10638        // Update volume if needed
10639        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10640        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10641            Slog.i(PackageManagerService.TAG,
10642                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10643                    + " package " + pkg.packageName
10644                    + " volume from " + pkgSetting.volumeUuid
10645                    + " to " + volumeUuid);
10646            pkgSetting.volumeUuid = volumeUuid;
10647        }
10648
10649        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10650    }
10651
10652    /**
10653     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10654     */
10655    private static boolean apkHasCode(String fileName) {
10656        StrictJarFile jarFile = null;
10657        try {
10658            jarFile = new StrictJarFile(fileName,
10659                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10660            return jarFile.findEntry("classes.dex") != null;
10661        } catch (IOException ignore) {
10662        } finally {
10663            try {
10664                if (jarFile != null) {
10665                    jarFile.close();
10666                }
10667            } catch (IOException ignore) {}
10668        }
10669        return false;
10670    }
10671
10672    /**
10673     * Enforces code policy for the package. This ensures that if an APK has
10674     * declared hasCode="true" in its manifest that the APK actually contains
10675     * code.
10676     *
10677     * @throws PackageManagerException If bytecode could not be found when it should exist
10678     */
10679    private static void assertCodePolicy(PackageParser.Package pkg)
10680            throws PackageManagerException {
10681        final boolean shouldHaveCode =
10682                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10683        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10684            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10685                    "Package " + pkg.baseCodePath + " code is missing");
10686        }
10687
10688        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10689            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10690                final boolean splitShouldHaveCode =
10691                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10692                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10693                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10694                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10695                }
10696            }
10697        }
10698    }
10699
10700    /**
10701     * Applies policy to the parsed package based upon the given policy flags.
10702     * Ensures the package is in a good state.
10703     * <p>
10704     * Implementation detail: This method must NOT have any side effect. It would
10705     * ideally be static, but, it requires locks to read system state.
10706     */
10707    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10708            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10709        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10710            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10711            if (pkg.applicationInfo.isDirectBootAware()) {
10712                // we're direct boot aware; set for all components
10713                for (PackageParser.Service s : pkg.services) {
10714                    s.info.encryptionAware = s.info.directBootAware = true;
10715                }
10716                for (PackageParser.Provider p : pkg.providers) {
10717                    p.info.encryptionAware = p.info.directBootAware = true;
10718                }
10719                for (PackageParser.Activity a : pkg.activities) {
10720                    a.info.encryptionAware = a.info.directBootAware = true;
10721                }
10722                for (PackageParser.Activity r : pkg.receivers) {
10723                    r.info.encryptionAware = r.info.directBootAware = true;
10724                }
10725            }
10726            if (compressedFileExists(pkg.codePath)) {
10727                pkg.isStub = true;
10728            }
10729        } else {
10730            // non system apps can't be flagged as core
10731            pkg.coreApp = false;
10732            // clear flags not applicable to regular apps
10733            pkg.applicationInfo.flags &=
10734                    ~ApplicationInfo.FLAG_PERSISTENT;
10735            pkg.applicationInfo.privateFlags &=
10736                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10737            pkg.applicationInfo.privateFlags &=
10738                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10739            // cap permission priorities
10740            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10741                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10742                    pkg.permissionGroups.get(i).info.priority = 0;
10743                }
10744            }
10745        }
10746        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10747            // clear protected broadcasts
10748            pkg.protectedBroadcasts = null;
10749            // ignore export request for single user receivers
10750            if (pkg.receivers != null) {
10751                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10752                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10753                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10754                        receiver.info.exported = false;
10755                    }
10756                }
10757            }
10758            // ignore export request for single user services
10759            if (pkg.services != null) {
10760                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10761                    final PackageParser.Service service = pkg.services.get(i);
10762                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10763                        service.info.exported = false;
10764                    }
10765                }
10766            }
10767            // ignore export request for single user providers
10768            if (pkg.providers != null) {
10769                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10770                    final PackageParser.Provider provider = pkg.providers.get(i);
10771                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10772                        provider.info.exported = false;
10773                    }
10774                }
10775            }
10776        }
10777
10778        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10779            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10780        }
10781
10782        if ((scanFlags & SCAN_AS_OEM) != 0) {
10783            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10784        }
10785
10786        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10787            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10788        }
10789
10790        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10791            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10792        }
10793
10794        // Check if the package is signed with the same key as the platform package.
10795        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10796                (platformPkg != null && compareSignatures(
10797                        platformPkg.mSigningDetails.signatures,
10798                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10799            pkg.applicationInfo.privateFlags |=
10800                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10801        }
10802
10803        if (!isSystemApp(pkg)) {
10804            // Only system apps can use these features.
10805            pkg.mOriginalPackages = null;
10806            pkg.mRealPackage = null;
10807            pkg.mAdoptPermissions = null;
10808        }
10809    }
10810
10811    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10812            throws PackageManagerException {
10813        if (object == null) {
10814            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10815        }
10816        return object;
10817    }
10818
10819    /**
10820     * Asserts the parsed package is valid according to the given policy. If the
10821     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10822     * <p>
10823     * Implementation detail: This method must NOT have any side effects. It would
10824     * ideally be static, but, it requires locks to read system state.
10825     *
10826     * @throws PackageManagerException If the package fails any of the validation checks
10827     */
10828    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10829            final @ScanFlags int scanFlags)
10830                    throws PackageManagerException {
10831        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10832            assertCodePolicy(pkg);
10833        }
10834
10835        if (pkg.applicationInfo.getCodePath() == null ||
10836                pkg.applicationInfo.getResourcePath() == null) {
10837            // Bail out. The resource and code paths haven't been set.
10838            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10839                    "Code and resource paths haven't been set correctly");
10840        }
10841
10842        // Make sure we're not adding any bogus keyset info
10843        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10844        ksms.assertScannedPackageValid(pkg);
10845
10846        synchronized (mPackages) {
10847            // The special "android" package can only be defined once
10848            if (pkg.packageName.equals("android")) {
10849                if (mAndroidApplication != null) {
10850                    Slog.w(TAG, "*************************************************");
10851                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10852                    Slog.w(TAG, " codePath=" + pkg.codePath);
10853                    Slog.w(TAG, "*************************************************");
10854                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10855                            "Core android package being redefined.  Skipping.");
10856                }
10857            }
10858
10859            // A package name must be unique; don't allow duplicates
10860            if (mPackages.containsKey(pkg.packageName)) {
10861                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10862                        "Application package " + pkg.packageName
10863                        + " already installed.  Skipping duplicate.");
10864            }
10865
10866            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10867                // Static libs have a synthetic package name containing the version
10868                // but we still want the base name to be unique.
10869                if (mPackages.containsKey(pkg.manifestPackageName)) {
10870                    throw new PackageManagerException(
10871                            "Duplicate static shared lib provider package");
10872                }
10873
10874                // Static shared libraries should have at least O target SDK
10875                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10876                    throw new PackageManagerException(
10877                            "Packages declaring static-shared libs must target O SDK or higher");
10878                }
10879
10880                // Package declaring static a shared lib cannot be instant apps
10881                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10882                    throw new PackageManagerException(
10883                            "Packages declaring static-shared libs cannot be instant apps");
10884                }
10885
10886                // Package declaring static a shared lib cannot be renamed since the package
10887                // name is synthetic and apps can't code around package manager internals.
10888                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10889                    throw new PackageManagerException(
10890                            "Packages declaring static-shared libs cannot be renamed");
10891                }
10892
10893                // Package declaring static a shared lib cannot declare child packages
10894                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10895                    throw new PackageManagerException(
10896                            "Packages declaring static-shared libs cannot have child packages");
10897                }
10898
10899                // Package declaring static a shared lib cannot declare dynamic libs
10900                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10901                    throw new PackageManagerException(
10902                            "Packages declaring static-shared libs cannot declare dynamic libs");
10903                }
10904
10905                // Package declaring static a shared lib cannot declare shared users
10906                if (pkg.mSharedUserId != null) {
10907                    throw new PackageManagerException(
10908                            "Packages declaring static-shared libs cannot declare shared users");
10909                }
10910
10911                // Static shared libs cannot declare activities
10912                if (!pkg.activities.isEmpty()) {
10913                    throw new PackageManagerException(
10914                            "Static shared libs cannot declare activities");
10915                }
10916
10917                // Static shared libs cannot declare services
10918                if (!pkg.services.isEmpty()) {
10919                    throw new PackageManagerException(
10920                            "Static shared libs cannot declare services");
10921                }
10922
10923                // Static shared libs cannot declare providers
10924                if (!pkg.providers.isEmpty()) {
10925                    throw new PackageManagerException(
10926                            "Static shared libs cannot declare content providers");
10927                }
10928
10929                // Static shared libs cannot declare receivers
10930                if (!pkg.receivers.isEmpty()) {
10931                    throw new PackageManagerException(
10932                            "Static shared libs cannot declare broadcast receivers");
10933                }
10934
10935                // Static shared libs cannot declare permission groups
10936                if (!pkg.permissionGroups.isEmpty()) {
10937                    throw new PackageManagerException(
10938                            "Static shared libs cannot declare permission groups");
10939                }
10940
10941                // Static shared libs cannot declare permissions
10942                if (!pkg.permissions.isEmpty()) {
10943                    throw new PackageManagerException(
10944                            "Static shared libs cannot declare permissions");
10945                }
10946
10947                // Static shared libs cannot declare protected broadcasts
10948                if (pkg.protectedBroadcasts != null) {
10949                    throw new PackageManagerException(
10950                            "Static shared libs cannot declare protected broadcasts");
10951                }
10952
10953                // Static shared libs cannot be overlay targets
10954                if (pkg.mOverlayTarget != null) {
10955                    throw new PackageManagerException(
10956                            "Static shared libs cannot be overlay targets");
10957                }
10958
10959                // The version codes must be ordered as lib versions
10960                long minVersionCode = Long.MIN_VALUE;
10961                long maxVersionCode = Long.MAX_VALUE;
10962
10963                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10964                        pkg.staticSharedLibName);
10965                if (versionedLib != null) {
10966                    final int versionCount = versionedLib.size();
10967                    for (int i = 0; i < versionCount; i++) {
10968                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10969                        final long libVersionCode = libInfo.getDeclaringPackage()
10970                                .getLongVersionCode();
10971                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10972                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10973                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10974                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10975                        } else {
10976                            minVersionCode = maxVersionCode = libVersionCode;
10977                            break;
10978                        }
10979                    }
10980                }
10981                if (pkg.getLongVersionCode() < minVersionCode
10982                        || pkg.getLongVersionCode() > maxVersionCode) {
10983                    throw new PackageManagerException("Static shared"
10984                            + " lib version codes must be ordered as lib versions");
10985                }
10986            }
10987
10988            // Only privileged apps and updated privileged apps can add child packages.
10989            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10990                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10991                    throw new PackageManagerException("Only privileged apps can add child "
10992                            + "packages. Ignoring package " + pkg.packageName);
10993                }
10994                final int childCount = pkg.childPackages.size();
10995                for (int i = 0; i < childCount; i++) {
10996                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10997                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10998                            childPkg.packageName)) {
10999                        throw new PackageManagerException("Can't override child of "
11000                                + "another disabled app. Ignoring package " + pkg.packageName);
11001                    }
11002                }
11003            }
11004
11005            // If we're only installing presumed-existing packages, require that the
11006            // scanned APK is both already known and at the path previously established
11007            // for it.  Previously unknown packages we pick up normally, but if we have an
11008            // a priori expectation about this package's install presence, enforce it.
11009            // With a singular exception for new system packages. When an OTA contains
11010            // a new system package, we allow the codepath to change from a system location
11011            // to the user-installed location. If we don't allow this change, any newer,
11012            // user-installed version of the application will be ignored.
11013            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11014                if (mExpectingBetter.containsKey(pkg.packageName)) {
11015                    logCriticalInfo(Log.WARN,
11016                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11017                } else {
11018                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11019                    if (known != null) {
11020                        if (DEBUG_PACKAGE_SCANNING) {
11021                            Log.d(TAG, "Examining " + pkg.codePath
11022                                    + " and requiring known paths " + known.codePathString
11023                                    + " & " + known.resourcePathString);
11024                        }
11025                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11026                                || !pkg.applicationInfo.getResourcePath().equals(
11027                                        known.resourcePathString)) {
11028                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11029                                    "Application package " + pkg.packageName
11030                                    + " found at " + pkg.applicationInfo.getCodePath()
11031                                    + " but expected at " + known.codePathString
11032                                    + "; ignoring.");
11033                        }
11034                    } else {
11035                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11036                                "Application package " + pkg.packageName
11037                                + " not found; ignoring.");
11038                    }
11039                }
11040            }
11041
11042            // Verify that this new package doesn't have any content providers
11043            // that conflict with existing packages.  Only do this if the
11044            // package isn't already installed, since we don't want to break
11045            // things that are installed.
11046            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11047                final int N = pkg.providers.size();
11048                int i;
11049                for (i=0; i<N; i++) {
11050                    PackageParser.Provider p = pkg.providers.get(i);
11051                    if (p.info.authority != null) {
11052                        String names[] = p.info.authority.split(";");
11053                        for (int j = 0; j < names.length; j++) {
11054                            if (mProvidersByAuthority.containsKey(names[j])) {
11055                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11056                                final String otherPackageName =
11057                                        ((other != null && other.getComponentName() != null) ?
11058                                                other.getComponentName().getPackageName() : "?");
11059                                throw new PackageManagerException(
11060                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11061                                        "Can't install because provider name " + names[j]
11062                                                + " (in package " + pkg.applicationInfo.packageName
11063                                                + ") is already used by " + otherPackageName);
11064                            }
11065                        }
11066                    }
11067                }
11068            }
11069
11070            // Verify that packages sharing a user with a privileged app are marked as privileged.
11071            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11072                SharedUserSetting sharedUserSetting = null;
11073                try {
11074                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11075                } catch (PackageManagerException ignore) {}
11076                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11077                    // Exempt SharedUsers signed with the platform key.
11078                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11079                    if ((platformPkgSetting.signatures.mSigningDetails
11080                            != PackageParser.SigningDetails.UNKNOWN)
11081                            && (compareSignatures(
11082                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11083                                    pkg.mSigningDetails.signatures)
11084                                            != PackageManager.SIGNATURE_MATCH)) {
11085                        throw new PackageManagerException("Apps that share a user with a " +
11086                                "privileged app must themselves be marked as privileged. " +
11087                                pkg.packageName + " shares privileged user " +
11088                                pkg.mSharedUserId + ".");
11089                    }
11090                }
11091            }
11092
11093            // Apply policies specific for runtime resource overlays (RROs).
11094            if (pkg.mOverlayTarget != null) {
11095                // System overlays have some restrictions on their use of the 'static' state.
11096                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11097                    // We are scanning a system overlay. This can be the first scan of the
11098                    // system/vendor/oem partition, or an update to the system overlay.
11099                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11100                        // This must be an update to a system overlay.
11101                        final PackageSetting previousPkg = assertNotNull(
11102                                mSettings.getPackageLPr(pkg.packageName),
11103                                "previous package state not present");
11104
11105                        // previousPkg.pkg may be null: the package will be not be scanned if the
11106                        // package manager knows there is a newer version on /data.
11107                        // TODO[b/79435695]: Find a better way to keep track of the "static"
11108                        // property for RROs instead of having to parse packages on /system
11109                        PackageParser.Package ppkg = previousPkg.pkg;
11110                        if (ppkg == null) {
11111                            try {
11112                                final PackageParser pp = new PackageParser();
11113                                ppkg = pp.parsePackage(previousPkg.codePath,
11114                                        parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR);
11115                            } catch (PackageParserException e) {
11116                                Slog.w(TAG, "failed to parse " + previousPkg.codePath, e);
11117                            }
11118                        }
11119
11120                        // Static overlays cannot be updated.
11121                        if (ppkg != null && ppkg.mOverlayIsStatic) {
11122                            throw new PackageManagerException("Overlay " + pkg.packageName +
11123                                    " is static and cannot be upgraded.");
11124                        // Non-static overlays cannot be converted to static overlays.
11125                        } else if (pkg.mOverlayIsStatic) {
11126                            throw new PackageManagerException("Overlay " + pkg.packageName +
11127                                    " cannot be upgraded into a static overlay.");
11128                        }
11129                    }
11130                } else {
11131                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11132                    if (pkg.mOverlayIsStatic) {
11133                        throw new PackageManagerException("Overlay " + pkg.packageName +
11134                                " is static but not pre-installed.");
11135                    }
11136
11137                    // The only case where we allow installation of a non-system overlay is when
11138                    // its signature is signed with the platform certificate.
11139                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11140                    if ((platformPkgSetting.signatures.mSigningDetails
11141                            != PackageParser.SigningDetails.UNKNOWN)
11142                            && (compareSignatures(
11143                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11144                                    pkg.mSigningDetails.signatures)
11145                                            != PackageManager.SIGNATURE_MATCH)) {
11146                        throw new PackageManagerException("Overlay " + pkg.packageName +
11147                                " must be signed with the platform certificate.");
11148                    }
11149                }
11150            }
11151        }
11152    }
11153
11154    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11155            int type, String declaringPackageName, long declaringVersionCode) {
11156        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11157        if (versionedLib == null) {
11158            versionedLib = new LongSparseArray<>();
11159            mSharedLibraries.put(name, versionedLib);
11160            if (type == SharedLibraryInfo.TYPE_STATIC) {
11161                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11162            }
11163        } else if (versionedLib.indexOfKey(version) >= 0) {
11164            return false;
11165        }
11166        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11167                version, type, declaringPackageName, declaringVersionCode);
11168        versionedLib.put(version, libEntry);
11169        return true;
11170    }
11171
11172    private boolean removeSharedLibraryLPw(String name, long version) {
11173        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11174        if (versionedLib == null) {
11175            return false;
11176        }
11177        final int libIdx = versionedLib.indexOfKey(version);
11178        if (libIdx < 0) {
11179            return false;
11180        }
11181        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11182        versionedLib.remove(version);
11183        if (versionedLib.size() <= 0) {
11184            mSharedLibraries.remove(name);
11185            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11186                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11187                        .getPackageName());
11188            }
11189        }
11190        return true;
11191    }
11192
11193    /**
11194     * Adds a scanned package to the system. When this method is finished, the package will
11195     * be available for query, resolution, etc...
11196     */
11197    private void commitPackageSettings(PackageParser.Package pkg,
11198            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11199            final @ScanFlags int scanFlags, boolean chatty) {
11200        final String pkgName = pkg.packageName;
11201        if (mCustomResolverComponentName != null &&
11202                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11203            setUpCustomResolverActivity(pkg);
11204        }
11205
11206        if (pkg.packageName.equals("android")) {
11207            synchronized (mPackages) {
11208                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11209                    // Set up information for our fall-back user intent resolution activity.
11210                    mPlatformPackage = pkg;
11211                    pkg.mVersionCode = mSdkVersion;
11212                    pkg.mVersionCodeMajor = 0;
11213                    mAndroidApplication = pkg.applicationInfo;
11214                    if (!mResolverReplaced) {
11215                        mResolveActivity.applicationInfo = mAndroidApplication;
11216                        mResolveActivity.name = ResolverActivity.class.getName();
11217                        mResolveActivity.packageName = mAndroidApplication.packageName;
11218                        mResolveActivity.processName = "system:ui";
11219                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11220                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11221                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11222                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11223                        mResolveActivity.exported = true;
11224                        mResolveActivity.enabled = true;
11225                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11226                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11227                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11228                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11229                                | ActivityInfo.CONFIG_ORIENTATION
11230                                | ActivityInfo.CONFIG_KEYBOARD
11231                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11232                        mResolveInfo.activityInfo = mResolveActivity;
11233                        mResolveInfo.priority = 0;
11234                        mResolveInfo.preferredOrder = 0;
11235                        mResolveInfo.match = 0;
11236                        mResolveComponentName = new ComponentName(
11237                                mAndroidApplication.packageName, mResolveActivity.name);
11238                    }
11239                }
11240            }
11241        }
11242
11243        ArrayList<PackageParser.Package> clientLibPkgs = null;
11244        // writer
11245        synchronized (mPackages) {
11246            boolean hasStaticSharedLibs = false;
11247
11248            // Any app can add new static shared libraries
11249            if (pkg.staticSharedLibName != null) {
11250                // Static shared libs don't allow renaming as they have synthetic package
11251                // names to allow install of multiple versions, so use name from manifest.
11252                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11253                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11254                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11255                    hasStaticSharedLibs = true;
11256                } else {
11257                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11258                                + pkg.staticSharedLibName + " already exists; skipping");
11259                }
11260                // Static shared libs cannot be updated once installed since they
11261                // use synthetic package name which includes the version code, so
11262                // not need to update other packages's shared lib dependencies.
11263            }
11264
11265            if (!hasStaticSharedLibs
11266                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11267                // Only system apps can add new dynamic shared libraries.
11268                if (pkg.libraryNames != null) {
11269                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11270                        String name = pkg.libraryNames.get(i);
11271                        boolean allowed = false;
11272                        if (pkg.isUpdatedSystemApp()) {
11273                            // New library entries can only be added through the
11274                            // system image.  This is important to get rid of a lot
11275                            // of nasty edge cases: for example if we allowed a non-
11276                            // system update of the app to add a library, then uninstalling
11277                            // the update would make the library go away, and assumptions
11278                            // we made such as through app install filtering would now
11279                            // have allowed apps on the device which aren't compatible
11280                            // with it.  Better to just have the restriction here, be
11281                            // conservative, and create many fewer cases that can negatively
11282                            // impact the user experience.
11283                            final PackageSetting sysPs = mSettings
11284                                    .getDisabledSystemPkgLPr(pkg.packageName);
11285                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11286                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11287                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11288                                        allowed = true;
11289                                        break;
11290                                    }
11291                                }
11292                            }
11293                        } else {
11294                            allowed = true;
11295                        }
11296                        if (allowed) {
11297                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11298                                    SharedLibraryInfo.VERSION_UNDEFINED,
11299                                    SharedLibraryInfo.TYPE_DYNAMIC,
11300                                    pkg.packageName, pkg.getLongVersionCode())) {
11301                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11302                                        + name + " already exists; skipping");
11303                            }
11304                        } else {
11305                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11306                                    + name + " that is not declared on system image; skipping");
11307                        }
11308                    }
11309
11310                    if ((scanFlags & SCAN_BOOTING) == 0) {
11311                        // If we are not booting, we need to update any applications
11312                        // that are clients of our shared library.  If we are booting,
11313                        // this will all be done once the scan is complete.
11314                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11315                    }
11316                }
11317            }
11318        }
11319
11320        if ((scanFlags & SCAN_BOOTING) != 0) {
11321            // No apps can run during boot scan, so they don't need to be frozen
11322        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11323            // Caller asked to not kill app, so it's probably not frozen
11324        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11325            // Caller asked us to ignore frozen check for some reason; they
11326            // probably didn't know the package name
11327        } else {
11328            // We're doing major surgery on this package, so it better be frozen
11329            // right now to keep it from launching
11330            checkPackageFrozen(pkgName);
11331        }
11332
11333        // Also need to kill any apps that are dependent on the library.
11334        if (clientLibPkgs != null) {
11335            for (int i=0; i<clientLibPkgs.size(); i++) {
11336                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11337                killApplication(clientPkg.applicationInfo.packageName,
11338                        clientPkg.applicationInfo.uid, "update lib");
11339            }
11340        }
11341
11342        // writer
11343        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11344
11345        synchronized (mPackages) {
11346            // We don't expect installation to fail beyond this point
11347
11348            // Add the new setting to mSettings
11349            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11350            // Add the new setting to mPackages
11351            mPackages.put(pkg.applicationInfo.packageName, pkg);
11352            // Make sure we don't accidentally delete its data.
11353            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11354            while (iter.hasNext()) {
11355                PackageCleanItem item = iter.next();
11356                if (pkgName.equals(item.packageName)) {
11357                    iter.remove();
11358                }
11359            }
11360
11361            // Add the package's KeySets to the global KeySetManagerService
11362            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11363            ksms.addScannedPackageLPw(pkg);
11364
11365            int N = pkg.providers.size();
11366            StringBuilder r = null;
11367            int i;
11368            for (i=0; i<N; i++) {
11369                PackageParser.Provider p = pkg.providers.get(i);
11370                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11371                        p.info.processName);
11372                mProviders.addProvider(p);
11373                p.syncable = p.info.isSyncable;
11374                if (p.info.authority != null) {
11375                    String names[] = p.info.authority.split(";");
11376                    p.info.authority = null;
11377                    for (int j = 0; j < names.length; j++) {
11378                        if (j == 1 && p.syncable) {
11379                            // We only want the first authority for a provider to possibly be
11380                            // syncable, so if we already added this provider using a different
11381                            // authority clear the syncable flag. We copy the provider before
11382                            // changing it because the mProviders object contains a reference
11383                            // to a provider that we don't want to change.
11384                            // Only do this for the second authority since the resulting provider
11385                            // object can be the same for all future authorities for this provider.
11386                            p = new PackageParser.Provider(p);
11387                            p.syncable = false;
11388                        }
11389                        if (!mProvidersByAuthority.containsKey(names[j])) {
11390                            mProvidersByAuthority.put(names[j], p);
11391                            if (p.info.authority == null) {
11392                                p.info.authority = names[j];
11393                            } else {
11394                                p.info.authority = p.info.authority + ";" + names[j];
11395                            }
11396                            if (DEBUG_PACKAGE_SCANNING) {
11397                                if (chatty)
11398                                    Log.d(TAG, "Registered content provider: " + names[j]
11399                                            + ", className = " + p.info.name + ", isSyncable = "
11400                                            + p.info.isSyncable);
11401                            }
11402                        } else {
11403                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11404                            Slog.w(TAG, "Skipping provider name " + names[j] +
11405                                    " (in package " + pkg.applicationInfo.packageName +
11406                                    "): name already used by "
11407                                    + ((other != null && other.getComponentName() != null)
11408                                            ? other.getComponentName().getPackageName() : "?"));
11409                        }
11410                    }
11411                }
11412                if (chatty) {
11413                    if (r == null) {
11414                        r = new StringBuilder(256);
11415                    } else {
11416                        r.append(' ');
11417                    }
11418                    r.append(p.info.name);
11419                }
11420            }
11421            if (r != null) {
11422                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11423            }
11424
11425            N = pkg.services.size();
11426            r = null;
11427            for (i=0; i<N; i++) {
11428                PackageParser.Service s = pkg.services.get(i);
11429                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11430                        s.info.processName);
11431                mServices.addService(s);
11432                if (chatty) {
11433                    if (r == null) {
11434                        r = new StringBuilder(256);
11435                    } else {
11436                        r.append(' ');
11437                    }
11438                    r.append(s.info.name);
11439                }
11440            }
11441            if (r != null) {
11442                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11443            }
11444
11445            N = pkg.receivers.size();
11446            r = null;
11447            for (i=0; i<N; i++) {
11448                PackageParser.Activity a = pkg.receivers.get(i);
11449                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11450                        a.info.processName);
11451                mReceivers.addActivity(a, "receiver");
11452                if (chatty) {
11453                    if (r == null) {
11454                        r = new StringBuilder(256);
11455                    } else {
11456                        r.append(' ');
11457                    }
11458                    r.append(a.info.name);
11459                }
11460            }
11461            if (r != null) {
11462                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11463            }
11464
11465            N = pkg.activities.size();
11466            r = null;
11467            for (i=0; i<N; i++) {
11468                PackageParser.Activity a = pkg.activities.get(i);
11469                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11470                        a.info.processName);
11471                mActivities.addActivity(a, "activity");
11472                if (chatty) {
11473                    if (r == null) {
11474                        r = new StringBuilder(256);
11475                    } else {
11476                        r.append(' ');
11477                    }
11478                    r.append(a.info.name);
11479                }
11480            }
11481            if (r != null) {
11482                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11483            }
11484
11485            // Don't allow ephemeral applications to define new permissions groups.
11486            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11487                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11488                        + " ignored: instant apps cannot define new permission groups.");
11489            } else {
11490                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11491            }
11492
11493            // Don't allow ephemeral applications to define new permissions.
11494            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11495                Slog.w(TAG, "Permissions from package " + pkg.packageName
11496                        + " ignored: instant apps cannot define new permissions.");
11497            } else {
11498                mPermissionManager.addAllPermissions(pkg, chatty);
11499            }
11500
11501            N = pkg.instrumentation.size();
11502            r = null;
11503            for (i=0; i<N; i++) {
11504                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11505                a.info.packageName = pkg.applicationInfo.packageName;
11506                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11507                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11508                a.info.splitNames = pkg.splitNames;
11509                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11510                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11511                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11512                a.info.dataDir = pkg.applicationInfo.dataDir;
11513                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11514                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11515                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11516                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11517                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11518                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11519                mInstrumentation.put(a.getComponentName(), a);
11520                if (chatty) {
11521                    if (r == null) {
11522                        r = new StringBuilder(256);
11523                    } else {
11524                        r.append(' ');
11525                    }
11526                    r.append(a.info.name);
11527                }
11528            }
11529            if (r != null) {
11530                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11531            }
11532
11533            if (pkg.protectedBroadcasts != null) {
11534                N = pkg.protectedBroadcasts.size();
11535                synchronized (mProtectedBroadcasts) {
11536                    for (i = 0; i < N; i++) {
11537                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11538                    }
11539                }
11540            }
11541
11542            if (oldPkg != null) {
11543                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11544                // revoke callbacks from this method might need to kill apps which need the
11545                // mPackages lock on a different thread. This would dead lock.
11546                //
11547                // Hence create a copy of all package names and pass it into
11548                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11549                // revoked. If a new package is added before the async code runs the permission
11550                // won't be granted yet, hence new packages are no problem.
11551                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11552
11553                AsyncTask.execute(() ->
11554                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11555                                allPackageNames, mPermissionCallback));
11556            }
11557        }
11558
11559        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11560    }
11561
11562    /**
11563     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11564     * is derived purely on the basis of the contents of {@code scanFile} and
11565     * {@code cpuAbiOverride}.
11566     *
11567     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11568     */
11569    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11570            boolean extractLibs)
11571                    throws PackageManagerException {
11572        // Give ourselves some initial paths; we'll come back for another
11573        // pass once we've determined ABI below.
11574        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11575
11576        // We would never need to extract libs for forward-locked and external packages,
11577        // since the container service will do it for us. We shouldn't attempt to
11578        // extract libs from system app when it was not updated.
11579        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11580                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11581            extractLibs = false;
11582        }
11583
11584        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11585        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11586
11587        NativeLibraryHelper.Handle handle = null;
11588        try {
11589            handle = NativeLibraryHelper.Handle.create(pkg);
11590            // TODO(multiArch): This can be null for apps that didn't go through the
11591            // usual installation process. We can calculate it again, like we
11592            // do during install time.
11593            //
11594            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11595            // unnecessary.
11596            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11597
11598            // Null out the abis so that they can be recalculated.
11599            pkg.applicationInfo.primaryCpuAbi = null;
11600            pkg.applicationInfo.secondaryCpuAbi = null;
11601            if (isMultiArch(pkg.applicationInfo)) {
11602                // Warn if we've set an abiOverride for multi-lib packages..
11603                // By definition, we need to copy both 32 and 64 bit libraries for
11604                // such packages.
11605                if (pkg.cpuAbiOverride != null
11606                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11607                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11608                }
11609
11610                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11611                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11612                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11613                    if (extractLibs) {
11614                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11615                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11616                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11617                                useIsaSpecificSubdirs);
11618                    } else {
11619                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11620                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11621                    }
11622                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11623                }
11624
11625                // Shared library native code should be in the APK zip aligned
11626                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11627                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11628                            "Shared library native lib extraction not supported");
11629                }
11630
11631                maybeThrowExceptionForMultiArchCopy(
11632                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11633
11634                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11635                    if (extractLibs) {
11636                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11637                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11638                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11639                                useIsaSpecificSubdirs);
11640                    } else {
11641                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11642                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11643                    }
11644                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11645                }
11646
11647                maybeThrowExceptionForMultiArchCopy(
11648                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11649
11650                if (abi64 >= 0) {
11651                    // Shared library native libs should be in the APK zip aligned
11652                    if (extractLibs && pkg.isLibrary()) {
11653                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11654                                "Shared library native lib extraction not supported");
11655                    }
11656                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11657                }
11658
11659                if (abi32 >= 0) {
11660                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11661                    if (abi64 >= 0) {
11662                        if (pkg.use32bitAbi) {
11663                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11664                            pkg.applicationInfo.primaryCpuAbi = abi;
11665                        } else {
11666                            pkg.applicationInfo.secondaryCpuAbi = abi;
11667                        }
11668                    } else {
11669                        pkg.applicationInfo.primaryCpuAbi = abi;
11670                    }
11671                }
11672            } else {
11673                String[] abiList = (cpuAbiOverride != null) ?
11674                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11675
11676                // Enable gross and lame hacks for apps that are built with old
11677                // SDK tools. We must scan their APKs for renderscript bitcode and
11678                // not launch them if it's present. Don't bother checking on devices
11679                // that don't have 64 bit support.
11680                boolean needsRenderScriptOverride = false;
11681                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11682                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11683                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11684                    needsRenderScriptOverride = true;
11685                }
11686
11687                final int copyRet;
11688                if (extractLibs) {
11689                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11690                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11691                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11692                } else {
11693                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11694                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11695                }
11696                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11697
11698                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11699                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11700                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11701                }
11702
11703                if (copyRet >= 0) {
11704                    // Shared libraries that have native libs must be multi-architecture
11705                    if (pkg.isLibrary()) {
11706                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11707                                "Shared library with native libs must be multiarch");
11708                    }
11709                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11710                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11711                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11712                } else if (needsRenderScriptOverride) {
11713                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11714                }
11715            }
11716        } catch (IOException ioe) {
11717            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11718        } finally {
11719            IoUtils.closeQuietly(handle);
11720        }
11721
11722        // Now that we've calculated the ABIs and determined if it's an internal app,
11723        // we will go ahead and populate the nativeLibraryPath.
11724        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11725    }
11726
11727    /**
11728     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11729     * i.e, so that all packages can be run inside a single process if required.
11730     *
11731     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11732     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11733     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11734     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11735     * updating a package that belongs to a shared user.
11736     *
11737     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11738     * adds unnecessary complexity.
11739     */
11740    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11741            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11742        List<String> changedAbiCodePath = null;
11743        String requiredInstructionSet = null;
11744        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11745            requiredInstructionSet = VMRuntime.getInstructionSet(
11746                     scannedPackage.applicationInfo.primaryCpuAbi);
11747        }
11748
11749        PackageSetting requirer = null;
11750        for (PackageSetting ps : packagesForUser) {
11751            // If packagesForUser contains scannedPackage, we skip it. This will happen
11752            // when scannedPackage is an update of an existing package. Without this check,
11753            // we will never be able to change the ABI of any package belonging to a shared
11754            // user, even if it's compatible with other packages.
11755            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11756                if (ps.primaryCpuAbiString == null) {
11757                    continue;
11758                }
11759
11760                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11761                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11762                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11763                    // this but there's not much we can do.
11764                    String errorMessage = "Instruction set mismatch, "
11765                            + ((requirer == null) ? "[caller]" : requirer)
11766                            + " requires " + requiredInstructionSet + " whereas " + ps
11767                            + " requires " + instructionSet;
11768                    Slog.w(TAG, errorMessage);
11769                }
11770
11771                if (requiredInstructionSet == null) {
11772                    requiredInstructionSet = instructionSet;
11773                    requirer = ps;
11774                }
11775            }
11776        }
11777
11778        if (requiredInstructionSet != null) {
11779            String adjustedAbi;
11780            if (requirer != null) {
11781                // requirer != null implies that either scannedPackage was null or that scannedPackage
11782                // did not require an ABI, in which case we have to adjust scannedPackage to match
11783                // the ABI of the set (which is the same as requirer's ABI)
11784                adjustedAbi = requirer.primaryCpuAbiString;
11785                if (scannedPackage != null) {
11786                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11787                }
11788            } else {
11789                // requirer == null implies that we're updating all ABIs in the set to
11790                // match scannedPackage.
11791                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11792            }
11793
11794            for (PackageSetting ps : packagesForUser) {
11795                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11796                    if (ps.primaryCpuAbiString != null) {
11797                        continue;
11798                    }
11799
11800                    ps.primaryCpuAbiString = adjustedAbi;
11801                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11802                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11803                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11804                        if (DEBUG_ABI_SELECTION) {
11805                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11806                                    + " (requirer="
11807                                    + (requirer != null ? requirer.pkg : "null")
11808                                    + ", scannedPackage="
11809                                    + (scannedPackage != null ? scannedPackage : "null")
11810                                    + ")");
11811                        }
11812                        if (changedAbiCodePath == null) {
11813                            changedAbiCodePath = new ArrayList<>();
11814                        }
11815                        changedAbiCodePath.add(ps.codePathString);
11816                    }
11817                }
11818            }
11819        }
11820        return changedAbiCodePath;
11821    }
11822
11823    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11824        synchronized (mPackages) {
11825            mResolverReplaced = true;
11826            // Set up information for custom user intent resolution activity.
11827            mResolveActivity.applicationInfo = pkg.applicationInfo;
11828            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11829            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11830            mResolveActivity.processName = pkg.applicationInfo.packageName;
11831            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11832            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11833                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11834            mResolveActivity.theme = 0;
11835            mResolveActivity.exported = true;
11836            mResolveActivity.enabled = true;
11837            mResolveInfo.activityInfo = mResolveActivity;
11838            mResolveInfo.priority = 0;
11839            mResolveInfo.preferredOrder = 0;
11840            mResolveInfo.match = 0;
11841            mResolveComponentName = mCustomResolverComponentName;
11842            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11843                    mResolveComponentName);
11844        }
11845    }
11846
11847    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11848        if (installerActivity == null) {
11849            if (DEBUG_INSTANT) {
11850                Slog.d(TAG, "Clear ephemeral installer activity");
11851            }
11852            mInstantAppInstallerActivity = null;
11853            return;
11854        }
11855
11856        if (DEBUG_INSTANT) {
11857            Slog.d(TAG, "Set ephemeral installer activity: "
11858                    + installerActivity.getComponentName());
11859        }
11860        // Set up information for ephemeral installer activity
11861        mInstantAppInstallerActivity = installerActivity;
11862        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11863                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11864        mInstantAppInstallerActivity.exported = true;
11865        mInstantAppInstallerActivity.enabled = true;
11866        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11867        mInstantAppInstallerInfo.priority = 1;
11868        mInstantAppInstallerInfo.preferredOrder = 1;
11869        mInstantAppInstallerInfo.isDefault = true;
11870        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11871                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11872    }
11873
11874    private static String calculateBundledApkRoot(final String codePathString) {
11875        final File codePath = new File(codePathString);
11876        final File codeRoot;
11877        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11878            codeRoot = Environment.getRootDirectory();
11879        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11880            codeRoot = Environment.getOemDirectory();
11881        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11882            codeRoot = Environment.getVendorDirectory();
11883        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11884            codeRoot = Environment.getOdmDirectory();
11885        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11886            codeRoot = Environment.getProductDirectory();
11887        } else {
11888            // Unrecognized code path; take its top real segment as the apk root:
11889            // e.g. /something/app/blah.apk => /something
11890            try {
11891                File f = codePath.getCanonicalFile();
11892                File parent = f.getParentFile();    // non-null because codePath is a file
11893                File tmp;
11894                while ((tmp = parent.getParentFile()) != null) {
11895                    f = parent;
11896                    parent = tmp;
11897                }
11898                codeRoot = f;
11899                Slog.w(TAG, "Unrecognized code path "
11900                        + codePath + " - using " + codeRoot);
11901            } catch (IOException e) {
11902                // Can't canonicalize the code path -- shenanigans?
11903                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11904                return Environment.getRootDirectory().getPath();
11905            }
11906        }
11907        return codeRoot.getPath();
11908    }
11909
11910    /**
11911     * Derive and set the location of native libraries for the given package,
11912     * which varies depending on where and how the package was installed.
11913     */
11914    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11915        final ApplicationInfo info = pkg.applicationInfo;
11916        final String codePath = pkg.codePath;
11917        final File codeFile = new File(codePath);
11918        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11919        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11920
11921        info.nativeLibraryRootDir = null;
11922        info.nativeLibraryRootRequiresIsa = false;
11923        info.nativeLibraryDir = null;
11924        info.secondaryNativeLibraryDir = null;
11925
11926        if (isApkFile(codeFile)) {
11927            // Monolithic install
11928            if (bundledApp) {
11929                // If "/system/lib64/apkname" exists, assume that is the per-package
11930                // native library directory to use; otherwise use "/system/lib/apkname".
11931                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11932                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11933                        getPrimaryInstructionSet(info));
11934
11935                // This is a bundled system app so choose the path based on the ABI.
11936                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11937                // is just the default path.
11938                final String apkName = deriveCodePathName(codePath);
11939                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11940                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11941                        apkName).getAbsolutePath();
11942
11943                if (info.secondaryCpuAbi != null) {
11944                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11945                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11946                            secondaryLibDir, apkName).getAbsolutePath();
11947                }
11948            } else if (asecApp) {
11949                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11950                        .getAbsolutePath();
11951            } else {
11952                final String apkName = deriveCodePathName(codePath);
11953                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11954                        .getAbsolutePath();
11955            }
11956
11957            info.nativeLibraryRootRequiresIsa = false;
11958            info.nativeLibraryDir = info.nativeLibraryRootDir;
11959        } else {
11960            // Cluster install
11961            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11962            info.nativeLibraryRootRequiresIsa = true;
11963
11964            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11965                    getPrimaryInstructionSet(info)).getAbsolutePath();
11966
11967            if (info.secondaryCpuAbi != null) {
11968                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11969                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11970            }
11971        }
11972    }
11973
11974    /**
11975     * Calculate the abis and roots for a bundled app. These can uniquely
11976     * be determined from the contents of the system partition, i.e whether
11977     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11978     * of this information, and instead assume that the system was built
11979     * sensibly.
11980     */
11981    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11982                                           PackageSetting pkgSetting) {
11983        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11984
11985        // If "/system/lib64/apkname" exists, assume that is the per-package
11986        // native library directory to use; otherwise use "/system/lib/apkname".
11987        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11988        setBundledAppAbi(pkg, apkRoot, apkName);
11989        // pkgSetting might be null during rescan following uninstall of updates
11990        // to a bundled app, so accommodate that possibility.  The settings in
11991        // that case will be established later from the parsed package.
11992        //
11993        // If the settings aren't null, sync them up with what we've just derived.
11994        // note that apkRoot isn't stored in the package settings.
11995        if (pkgSetting != null) {
11996            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11997            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11998        }
11999    }
12000
12001    /**
12002     * Deduces the ABI of a bundled app and sets the relevant fields on the
12003     * parsed pkg object.
12004     *
12005     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12006     *        under which system libraries are installed.
12007     * @param apkName the name of the installed package.
12008     */
12009    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12010        final File codeFile = new File(pkg.codePath);
12011
12012        final boolean has64BitLibs;
12013        final boolean has32BitLibs;
12014        if (isApkFile(codeFile)) {
12015            // Monolithic install
12016            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12017            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12018        } else {
12019            // Cluster install
12020            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12021            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12022                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12023                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12024                has64BitLibs = (new File(rootDir, isa)).exists();
12025            } else {
12026                has64BitLibs = false;
12027            }
12028            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12029                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12030                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12031                has32BitLibs = (new File(rootDir, isa)).exists();
12032            } else {
12033                has32BitLibs = false;
12034            }
12035        }
12036
12037        if (has64BitLibs && !has32BitLibs) {
12038            // The package has 64 bit libs, but not 32 bit libs. Its primary
12039            // ABI should be 64 bit. We can safely assume here that the bundled
12040            // native libraries correspond to the most preferred ABI in the list.
12041
12042            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12043            pkg.applicationInfo.secondaryCpuAbi = null;
12044        } else if (has32BitLibs && !has64BitLibs) {
12045            // The package has 32 bit libs but not 64 bit libs. Its primary
12046            // ABI should be 32 bit.
12047
12048            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12049            pkg.applicationInfo.secondaryCpuAbi = null;
12050        } else if (has32BitLibs && has64BitLibs) {
12051            // The application has both 64 and 32 bit bundled libraries. We check
12052            // here that the app declares multiArch support, and warn if it doesn't.
12053            //
12054            // We will be lenient here and record both ABIs. The primary will be the
12055            // ABI that's higher on the list, i.e, a device that's configured to prefer
12056            // 64 bit apps will see a 64 bit primary ABI,
12057
12058            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12059                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12060            }
12061
12062            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12063                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12064                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12065            } else {
12066                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12067                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12068            }
12069        } else {
12070            pkg.applicationInfo.primaryCpuAbi = null;
12071            pkg.applicationInfo.secondaryCpuAbi = null;
12072        }
12073    }
12074
12075    private void killApplication(String pkgName, int appId, String reason) {
12076        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12077    }
12078
12079    private void killApplication(String pkgName, int appId, int userId, String reason) {
12080        // Request the ActivityManager to kill the process(only for existing packages)
12081        // so that we do not end up in a confused state while the user is still using the older
12082        // version of the application while the new one gets installed.
12083        final long token = Binder.clearCallingIdentity();
12084        try {
12085            IActivityManager am = ActivityManager.getService();
12086            if (am != null) {
12087                try {
12088                    am.killApplication(pkgName, appId, userId, reason);
12089                } catch (RemoteException e) {
12090                }
12091            }
12092        } finally {
12093            Binder.restoreCallingIdentity(token);
12094        }
12095    }
12096
12097    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12098        // Remove the parent package setting
12099        PackageSetting ps = (PackageSetting) pkg.mExtras;
12100        if (ps != null) {
12101            removePackageLI(ps, chatty);
12102        }
12103        // Remove the child package setting
12104        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12105        for (int i = 0; i < childCount; i++) {
12106            PackageParser.Package childPkg = pkg.childPackages.get(i);
12107            ps = (PackageSetting) childPkg.mExtras;
12108            if (ps != null) {
12109                removePackageLI(ps, chatty);
12110            }
12111        }
12112    }
12113
12114    void removePackageLI(PackageSetting ps, boolean chatty) {
12115        if (DEBUG_INSTALL) {
12116            if (chatty)
12117                Log.d(TAG, "Removing package " + ps.name);
12118        }
12119
12120        // writer
12121        synchronized (mPackages) {
12122            mPackages.remove(ps.name);
12123            final PackageParser.Package pkg = ps.pkg;
12124            if (pkg != null) {
12125                cleanPackageDataStructuresLILPw(pkg, chatty);
12126            }
12127        }
12128    }
12129
12130    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12131        if (DEBUG_INSTALL) {
12132            if (chatty)
12133                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12134        }
12135
12136        // writer
12137        synchronized (mPackages) {
12138            // Remove the parent package
12139            mPackages.remove(pkg.applicationInfo.packageName);
12140            cleanPackageDataStructuresLILPw(pkg, chatty);
12141
12142            // Remove the child packages
12143            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12144            for (int i = 0; i < childCount; i++) {
12145                PackageParser.Package childPkg = pkg.childPackages.get(i);
12146                mPackages.remove(childPkg.applicationInfo.packageName);
12147                cleanPackageDataStructuresLILPw(childPkg, chatty);
12148            }
12149        }
12150    }
12151
12152    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12153        int N = pkg.providers.size();
12154        StringBuilder r = null;
12155        int i;
12156        for (i=0; i<N; i++) {
12157            PackageParser.Provider p = pkg.providers.get(i);
12158            mProviders.removeProvider(p);
12159            if (p.info.authority == null) {
12160
12161                /* There was another ContentProvider with this authority when
12162                 * this app was installed so this authority is null,
12163                 * Ignore it as we don't have to unregister the provider.
12164                 */
12165                continue;
12166            }
12167            String names[] = p.info.authority.split(";");
12168            for (int j = 0; j < names.length; j++) {
12169                if (mProvidersByAuthority.get(names[j]) == p) {
12170                    mProvidersByAuthority.remove(names[j]);
12171                    if (DEBUG_REMOVE) {
12172                        if (chatty)
12173                            Log.d(TAG, "Unregistered content provider: " + names[j]
12174                                    + ", className = " + p.info.name + ", isSyncable = "
12175                                    + p.info.isSyncable);
12176                    }
12177                }
12178            }
12179            if (DEBUG_REMOVE && chatty) {
12180                if (r == null) {
12181                    r = new StringBuilder(256);
12182                } else {
12183                    r.append(' ');
12184                }
12185                r.append(p.info.name);
12186            }
12187        }
12188        if (r != null) {
12189            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12190        }
12191
12192        N = pkg.services.size();
12193        r = null;
12194        for (i=0; i<N; i++) {
12195            PackageParser.Service s = pkg.services.get(i);
12196            mServices.removeService(s);
12197            if (chatty) {
12198                if (r == null) {
12199                    r = new StringBuilder(256);
12200                } else {
12201                    r.append(' ');
12202                }
12203                r.append(s.info.name);
12204            }
12205        }
12206        if (r != null) {
12207            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12208        }
12209
12210        N = pkg.receivers.size();
12211        r = null;
12212        for (i=0; i<N; i++) {
12213            PackageParser.Activity a = pkg.receivers.get(i);
12214            mReceivers.removeActivity(a, "receiver");
12215            if (DEBUG_REMOVE && chatty) {
12216                if (r == null) {
12217                    r = new StringBuilder(256);
12218                } else {
12219                    r.append(' ');
12220                }
12221                r.append(a.info.name);
12222            }
12223        }
12224        if (r != null) {
12225            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12226        }
12227
12228        N = pkg.activities.size();
12229        r = null;
12230        for (i=0; i<N; i++) {
12231            PackageParser.Activity a = pkg.activities.get(i);
12232            mActivities.removeActivity(a, "activity");
12233            if (DEBUG_REMOVE && chatty) {
12234                if (r == null) {
12235                    r = new StringBuilder(256);
12236                } else {
12237                    r.append(' ');
12238                }
12239                r.append(a.info.name);
12240            }
12241        }
12242        if (r != null) {
12243            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12244        }
12245
12246        mPermissionManager.removeAllPermissions(pkg, chatty);
12247
12248        N = pkg.instrumentation.size();
12249        r = null;
12250        for (i=0; i<N; i++) {
12251            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12252            mInstrumentation.remove(a.getComponentName());
12253            if (DEBUG_REMOVE && chatty) {
12254                if (r == null) {
12255                    r = new StringBuilder(256);
12256                } else {
12257                    r.append(' ');
12258                }
12259                r.append(a.info.name);
12260            }
12261        }
12262        if (r != null) {
12263            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12264        }
12265
12266        r = null;
12267        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12268            // Only system apps can hold shared libraries.
12269            if (pkg.libraryNames != null) {
12270                for (i = 0; i < pkg.libraryNames.size(); i++) {
12271                    String name = pkg.libraryNames.get(i);
12272                    if (removeSharedLibraryLPw(name, 0)) {
12273                        if (DEBUG_REMOVE && chatty) {
12274                            if (r == null) {
12275                                r = new StringBuilder(256);
12276                            } else {
12277                                r.append(' ');
12278                            }
12279                            r.append(name);
12280                        }
12281                    }
12282                }
12283            }
12284        }
12285
12286        r = null;
12287
12288        // Any package can hold static shared libraries.
12289        if (pkg.staticSharedLibName != null) {
12290            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12291                if (DEBUG_REMOVE && chatty) {
12292                    if (r == null) {
12293                        r = new StringBuilder(256);
12294                    } else {
12295                        r.append(' ');
12296                    }
12297                    r.append(pkg.staticSharedLibName);
12298                }
12299            }
12300        }
12301
12302        if (r != null) {
12303            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12304        }
12305    }
12306
12307
12308    final class ActivityIntentResolver
12309            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12310        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12311                boolean defaultOnly, int userId) {
12312            if (!sUserManager.exists(userId)) return null;
12313            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12314            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12315        }
12316
12317        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12318                int userId) {
12319            if (!sUserManager.exists(userId)) return null;
12320            mFlags = flags;
12321            return super.queryIntent(intent, resolvedType,
12322                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12323                    userId);
12324        }
12325
12326        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12327                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12328            if (!sUserManager.exists(userId)) return null;
12329            if (packageActivities == null) {
12330                return null;
12331            }
12332            mFlags = flags;
12333            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12334            final int N = packageActivities.size();
12335            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12336                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12337
12338            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12339            for (int i = 0; i < N; ++i) {
12340                intentFilters = packageActivities.get(i).intents;
12341                if (intentFilters != null && intentFilters.size() > 0) {
12342                    PackageParser.ActivityIntentInfo[] array =
12343                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12344                    intentFilters.toArray(array);
12345                    listCut.add(array);
12346                }
12347            }
12348            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12349        }
12350
12351        /**
12352         * Finds a privileged activity that matches the specified activity names.
12353         */
12354        private PackageParser.Activity findMatchingActivity(
12355                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12356            for (PackageParser.Activity sysActivity : activityList) {
12357                if (sysActivity.info.name.equals(activityInfo.name)) {
12358                    return sysActivity;
12359                }
12360                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12361                    return sysActivity;
12362                }
12363                if (sysActivity.info.targetActivity != null) {
12364                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12365                        return sysActivity;
12366                    }
12367                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12368                        return sysActivity;
12369                    }
12370                }
12371            }
12372            return null;
12373        }
12374
12375        public class IterGenerator<E> {
12376            public Iterator<E> generate(ActivityIntentInfo info) {
12377                return null;
12378            }
12379        }
12380
12381        public class ActionIterGenerator extends IterGenerator<String> {
12382            @Override
12383            public Iterator<String> generate(ActivityIntentInfo info) {
12384                return info.actionsIterator();
12385            }
12386        }
12387
12388        public class CategoriesIterGenerator extends IterGenerator<String> {
12389            @Override
12390            public Iterator<String> generate(ActivityIntentInfo info) {
12391                return info.categoriesIterator();
12392            }
12393        }
12394
12395        public class SchemesIterGenerator extends IterGenerator<String> {
12396            @Override
12397            public Iterator<String> generate(ActivityIntentInfo info) {
12398                return info.schemesIterator();
12399            }
12400        }
12401
12402        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12403            @Override
12404            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12405                return info.authoritiesIterator();
12406            }
12407        }
12408
12409        /**
12410         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12411         * MODIFIED. Do not pass in a list that should not be changed.
12412         */
12413        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12414                IterGenerator<T> generator, Iterator<T> searchIterator) {
12415            // loop through the set of actions; every one must be found in the intent filter
12416            while (searchIterator.hasNext()) {
12417                // we must have at least one filter in the list to consider a match
12418                if (intentList.size() == 0) {
12419                    break;
12420                }
12421
12422                final T searchAction = searchIterator.next();
12423
12424                // loop through the set of intent filters
12425                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12426                while (intentIter.hasNext()) {
12427                    final ActivityIntentInfo intentInfo = intentIter.next();
12428                    boolean selectionFound = false;
12429
12430                    // loop through the intent filter's selection criteria; at least one
12431                    // of them must match the searched criteria
12432                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12433                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12434                        final T intentSelection = intentSelectionIter.next();
12435                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12436                            selectionFound = true;
12437                            break;
12438                        }
12439                    }
12440
12441                    // the selection criteria wasn't found in this filter's set; this filter
12442                    // is not a potential match
12443                    if (!selectionFound) {
12444                        intentIter.remove();
12445                    }
12446                }
12447            }
12448        }
12449
12450        private boolean isProtectedAction(ActivityIntentInfo filter) {
12451            final Iterator<String> actionsIter = filter.actionsIterator();
12452            while (actionsIter != null && actionsIter.hasNext()) {
12453                final String filterAction = actionsIter.next();
12454                if (PROTECTED_ACTIONS.contains(filterAction)) {
12455                    return true;
12456                }
12457            }
12458            return false;
12459        }
12460
12461        /**
12462         * Adjusts the priority of the given intent filter according to policy.
12463         * <p>
12464         * <ul>
12465         * <li>The priority for non privileged applications is capped to '0'</li>
12466         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12467         * <li>The priority for unbundled updates to privileged applications is capped to the
12468         *      priority defined on the system partition</li>
12469         * </ul>
12470         * <p>
12471         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12472         * allowed to obtain any priority on any action.
12473         */
12474        private void adjustPriority(
12475                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12476            // nothing to do; priority is fine as-is
12477            if (intent.getPriority() <= 0) {
12478                return;
12479            }
12480
12481            final ActivityInfo activityInfo = intent.activity.info;
12482            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12483
12484            final boolean privilegedApp =
12485                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12486            if (!privilegedApp) {
12487                // non-privileged applications can never define a priority >0
12488                if (DEBUG_FILTERS) {
12489                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12490                            + " package: " + applicationInfo.packageName
12491                            + " activity: " + intent.activity.className
12492                            + " origPrio: " + intent.getPriority());
12493                }
12494                intent.setPriority(0);
12495                return;
12496            }
12497
12498            if (systemActivities == null) {
12499                // the system package is not disabled; we're parsing the system partition
12500                if (isProtectedAction(intent)) {
12501                    if (mDeferProtectedFilters) {
12502                        // We can't deal with these just yet. No component should ever obtain a
12503                        // >0 priority for a protected actions, with ONE exception -- the setup
12504                        // wizard. The setup wizard, however, cannot be known until we're able to
12505                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12506                        // until all intent filters have been processed. Chicken, meet egg.
12507                        // Let the filter temporarily have a high priority and rectify the
12508                        // priorities after all system packages have been scanned.
12509                        mProtectedFilters.add(intent);
12510                        if (DEBUG_FILTERS) {
12511                            Slog.i(TAG, "Protected action; save for later;"
12512                                    + " package: " + applicationInfo.packageName
12513                                    + " activity: " + intent.activity.className
12514                                    + " origPrio: " + intent.getPriority());
12515                        }
12516                        return;
12517                    } else {
12518                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12519                            Slog.i(TAG, "No setup wizard;"
12520                                + " All protected intents capped to priority 0");
12521                        }
12522                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12523                            if (DEBUG_FILTERS) {
12524                                Slog.i(TAG, "Found setup wizard;"
12525                                    + " allow priority " + intent.getPriority() + ";"
12526                                    + " package: " + intent.activity.info.packageName
12527                                    + " activity: " + intent.activity.className
12528                                    + " priority: " + intent.getPriority());
12529                            }
12530                            // setup wizard gets whatever it wants
12531                            return;
12532                        }
12533                        if (DEBUG_FILTERS) {
12534                            Slog.i(TAG, "Protected action; cap priority to 0;"
12535                                    + " package: " + intent.activity.info.packageName
12536                                    + " activity: " + intent.activity.className
12537                                    + " origPrio: " + intent.getPriority());
12538                        }
12539                        intent.setPriority(0);
12540                        return;
12541                    }
12542                }
12543                // privileged apps on the system image get whatever priority they request
12544                return;
12545            }
12546
12547            // privileged app unbundled update ... try to find the same activity
12548            final PackageParser.Activity foundActivity =
12549                    findMatchingActivity(systemActivities, activityInfo);
12550            if (foundActivity == null) {
12551                // this is a new activity; it cannot obtain >0 priority
12552                if (DEBUG_FILTERS) {
12553                    Slog.i(TAG, "New activity; cap priority to 0;"
12554                            + " package: " + applicationInfo.packageName
12555                            + " activity: " + intent.activity.className
12556                            + " origPrio: " + intent.getPriority());
12557                }
12558                intent.setPriority(0);
12559                return;
12560            }
12561
12562            // found activity, now check for filter equivalence
12563
12564            // a shallow copy is enough; we modify the list, not its contents
12565            final List<ActivityIntentInfo> intentListCopy =
12566                    new ArrayList<>(foundActivity.intents);
12567            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12568
12569            // find matching action subsets
12570            final Iterator<String> actionsIterator = intent.actionsIterator();
12571            if (actionsIterator != null) {
12572                getIntentListSubset(
12573                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12574                if (intentListCopy.size() == 0) {
12575                    // no more intents to match; we're not equivalent
12576                    if (DEBUG_FILTERS) {
12577                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12578                                + " package: " + applicationInfo.packageName
12579                                + " activity: " + intent.activity.className
12580                                + " origPrio: " + intent.getPriority());
12581                    }
12582                    intent.setPriority(0);
12583                    return;
12584                }
12585            }
12586
12587            // find matching category subsets
12588            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12589            if (categoriesIterator != null) {
12590                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12591                        categoriesIterator);
12592                if (intentListCopy.size() == 0) {
12593                    // no more intents to match; we're not equivalent
12594                    if (DEBUG_FILTERS) {
12595                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12596                                + " package: " + applicationInfo.packageName
12597                                + " activity: " + intent.activity.className
12598                                + " origPrio: " + intent.getPriority());
12599                    }
12600                    intent.setPriority(0);
12601                    return;
12602                }
12603            }
12604
12605            // find matching schemes subsets
12606            final Iterator<String> schemesIterator = intent.schemesIterator();
12607            if (schemesIterator != null) {
12608                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12609                        schemesIterator);
12610                if (intentListCopy.size() == 0) {
12611                    // no more intents to match; we're not equivalent
12612                    if (DEBUG_FILTERS) {
12613                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12614                                + " package: " + applicationInfo.packageName
12615                                + " activity: " + intent.activity.className
12616                                + " origPrio: " + intent.getPriority());
12617                    }
12618                    intent.setPriority(0);
12619                    return;
12620                }
12621            }
12622
12623            // find matching authorities subsets
12624            final Iterator<IntentFilter.AuthorityEntry>
12625                    authoritiesIterator = intent.authoritiesIterator();
12626            if (authoritiesIterator != null) {
12627                getIntentListSubset(intentListCopy,
12628                        new AuthoritiesIterGenerator(),
12629                        authoritiesIterator);
12630                if (intentListCopy.size() == 0) {
12631                    // no more intents to match; we're not equivalent
12632                    if (DEBUG_FILTERS) {
12633                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12634                                + " package: " + applicationInfo.packageName
12635                                + " activity: " + intent.activity.className
12636                                + " origPrio: " + intent.getPriority());
12637                    }
12638                    intent.setPriority(0);
12639                    return;
12640                }
12641            }
12642
12643            // we found matching filter(s); app gets the max priority of all intents
12644            int cappedPriority = 0;
12645            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12646                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12647            }
12648            if (intent.getPriority() > cappedPriority) {
12649                if (DEBUG_FILTERS) {
12650                    Slog.i(TAG, "Found matching filter(s);"
12651                            + " cap priority to " + cappedPriority + ";"
12652                            + " package: " + applicationInfo.packageName
12653                            + " activity: " + intent.activity.className
12654                            + " origPrio: " + intent.getPriority());
12655                }
12656                intent.setPriority(cappedPriority);
12657                return;
12658            }
12659            // all this for nothing; the requested priority was <= what was on the system
12660        }
12661
12662        public final void addActivity(PackageParser.Activity a, String type) {
12663            mActivities.put(a.getComponentName(), a);
12664            if (DEBUG_SHOW_INFO)
12665                Log.v(
12666                TAG, "  " + type + " " +
12667                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12668            if (DEBUG_SHOW_INFO)
12669                Log.v(TAG, "    Class=" + a.info.name);
12670            final int NI = a.intents.size();
12671            for (int j=0; j<NI; j++) {
12672                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12673                if ("activity".equals(type)) {
12674                    final PackageSetting ps =
12675                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12676                    final List<PackageParser.Activity> systemActivities =
12677                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12678                    adjustPriority(systemActivities, intent);
12679                }
12680                if (DEBUG_SHOW_INFO) {
12681                    Log.v(TAG, "    IntentFilter:");
12682                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12683                }
12684                if (!intent.debugCheck()) {
12685                    Log.w(TAG, "==> For Activity " + a.info.name);
12686                }
12687                addFilter(intent);
12688            }
12689        }
12690
12691        public final void removeActivity(PackageParser.Activity a, String type) {
12692            mActivities.remove(a.getComponentName());
12693            if (DEBUG_SHOW_INFO) {
12694                Log.v(TAG, "  " + type + " "
12695                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12696                                : a.info.name) + ":");
12697                Log.v(TAG, "    Class=" + a.info.name);
12698            }
12699            final int NI = a.intents.size();
12700            for (int j=0; j<NI; j++) {
12701                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12702                if (DEBUG_SHOW_INFO) {
12703                    Log.v(TAG, "    IntentFilter:");
12704                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12705                }
12706                removeFilter(intent);
12707            }
12708        }
12709
12710        @Override
12711        protected boolean allowFilterResult(
12712                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12713            ActivityInfo filterAi = filter.activity.info;
12714            for (int i=dest.size()-1; i>=0; i--) {
12715                ActivityInfo destAi = dest.get(i).activityInfo;
12716                if (destAi.name == filterAi.name
12717                        && destAi.packageName == filterAi.packageName) {
12718                    return false;
12719                }
12720            }
12721            return true;
12722        }
12723
12724        @Override
12725        protected ActivityIntentInfo[] newArray(int size) {
12726            return new ActivityIntentInfo[size];
12727        }
12728
12729        @Override
12730        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12731            if (!sUserManager.exists(userId)) return true;
12732            PackageParser.Package p = filter.activity.owner;
12733            if (p != null) {
12734                PackageSetting ps = (PackageSetting)p.mExtras;
12735                if (ps != null) {
12736                    // System apps are never considered stopped for purposes of
12737                    // filtering, because there may be no way for the user to
12738                    // actually re-launch them.
12739                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12740                            && ps.getStopped(userId);
12741                }
12742            }
12743            return false;
12744        }
12745
12746        @Override
12747        protected boolean isPackageForFilter(String packageName,
12748                PackageParser.ActivityIntentInfo info) {
12749            return packageName.equals(info.activity.owner.packageName);
12750        }
12751
12752        @Override
12753        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12754                int match, int userId) {
12755            if (!sUserManager.exists(userId)) return null;
12756            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12757                return null;
12758            }
12759            final PackageParser.Activity activity = info.activity;
12760            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12761            if (ps == null) {
12762                return null;
12763            }
12764            final PackageUserState userState = ps.readUserState(userId);
12765            ActivityInfo ai =
12766                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12767            if (ai == null) {
12768                return null;
12769            }
12770            final boolean matchExplicitlyVisibleOnly =
12771                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12772            final boolean matchVisibleToInstantApp =
12773                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12774            final boolean componentVisible =
12775                    matchVisibleToInstantApp
12776                    && info.isVisibleToInstantApp()
12777                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12778            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12779            // throw out filters that aren't visible to ephemeral apps
12780            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12781                return null;
12782            }
12783            // throw out instant app filters if we're not explicitly requesting them
12784            if (!matchInstantApp && userState.instantApp) {
12785                return null;
12786            }
12787            // throw out instant app filters if updates are available; will trigger
12788            // instant app resolution
12789            if (userState.instantApp && ps.isUpdateAvailable()) {
12790                return null;
12791            }
12792            final ResolveInfo res = new ResolveInfo();
12793            res.activityInfo = ai;
12794            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12795                res.filter = info;
12796            }
12797            if (info != null) {
12798                res.handleAllWebDataURI = info.handleAllWebDataURI();
12799            }
12800            res.priority = info.getPriority();
12801            res.preferredOrder = activity.owner.mPreferredOrder;
12802            //System.out.println("Result: " + res.activityInfo.className +
12803            //                   " = " + res.priority);
12804            res.match = match;
12805            res.isDefault = info.hasDefault;
12806            res.labelRes = info.labelRes;
12807            res.nonLocalizedLabel = info.nonLocalizedLabel;
12808            if (userNeedsBadging(userId)) {
12809                res.noResourceId = true;
12810            } else {
12811                res.icon = info.icon;
12812            }
12813            res.iconResourceId = info.icon;
12814            res.system = res.activityInfo.applicationInfo.isSystemApp();
12815            res.isInstantAppAvailable = userState.instantApp;
12816            return res;
12817        }
12818
12819        @Override
12820        protected void sortResults(List<ResolveInfo> results) {
12821            Collections.sort(results, mResolvePrioritySorter);
12822        }
12823
12824        @Override
12825        protected void dumpFilter(PrintWriter out, String prefix,
12826                PackageParser.ActivityIntentInfo filter) {
12827            out.print(prefix); out.print(
12828                    Integer.toHexString(System.identityHashCode(filter.activity)));
12829                    out.print(' ');
12830                    filter.activity.printComponentShortName(out);
12831                    out.print(" filter ");
12832                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12833        }
12834
12835        @Override
12836        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12837            return filter.activity;
12838        }
12839
12840        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12841            PackageParser.Activity activity = (PackageParser.Activity)label;
12842            out.print(prefix); out.print(
12843                    Integer.toHexString(System.identityHashCode(activity)));
12844                    out.print(' ');
12845                    activity.printComponentShortName(out);
12846            if (count > 1) {
12847                out.print(" ("); out.print(count); out.print(" filters)");
12848            }
12849            out.println();
12850        }
12851
12852        // Keys are String (activity class name), values are Activity.
12853        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12854                = new ArrayMap<ComponentName, PackageParser.Activity>();
12855        private int mFlags;
12856    }
12857
12858    private final class ServiceIntentResolver
12859            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12860        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12861                boolean defaultOnly, int userId) {
12862            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12863            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12864        }
12865
12866        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12867                int userId) {
12868            if (!sUserManager.exists(userId)) return null;
12869            mFlags = flags;
12870            return super.queryIntent(intent, resolvedType,
12871                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12872                    userId);
12873        }
12874
12875        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12876                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12877            if (!sUserManager.exists(userId)) return null;
12878            if (packageServices == null) {
12879                return null;
12880            }
12881            mFlags = flags;
12882            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12883            final int N = packageServices.size();
12884            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12885                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12886
12887            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12888            for (int i = 0; i < N; ++i) {
12889                intentFilters = packageServices.get(i).intents;
12890                if (intentFilters != null && intentFilters.size() > 0) {
12891                    PackageParser.ServiceIntentInfo[] array =
12892                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12893                    intentFilters.toArray(array);
12894                    listCut.add(array);
12895                }
12896            }
12897            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12898        }
12899
12900        public final void addService(PackageParser.Service s) {
12901            mServices.put(s.getComponentName(), s);
12902            if (DEBUG_SHOW_INFO) {
12903                Log.v(TAG, "  "
12904                        + (s.info.nonLocalizedLabel != null
12905                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12906                Log.v(TAG, "    Class=" + s.info.name);
12907            }
12908            final int NI = s.intents.size();
12909            int j;
12910            for (j=0; j<NI; j++) {
12911                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12912                if (DEBUG_SHOW_INFO) {
12913                    Log.v(TAG, "    IntentFilter:");
12914                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12915                }
12916                if (!intent.debugCheck()) {
12917                    Log.w(TAG, "==> For Service " + s.info.name);
12918                }
12919                addFilter(intent);
12920            }
12921        }
12922
12923        public final void removeService(PackageParser.Service s) {
12924            mServices.remove(s.getComponentName());
12925            if (DEBUG_SHOW_INFO) {
12926                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12927                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12928                Log.v(TAG, "    Class=" + s.info.name);
12929            }
12930            final int NI = s.intents.size();
12931            int j;
12932            for (j=0; j<NI; j++) {
12933                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12934                if (DEBUG_SHOW_INFO) {
12935                    Log.v(TAG, "    IntentFilter:");
12936                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12937                }
12938                removeFilter(intent);
12939            }
12940        }
12941
12942        @Override
12943        protected boolean allowFilterResult(
12944                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12945            ServiceInfo filterSi = filter.service.info;
12946            for (int i=dest.size()-1; i>=0; i--) {
12947                ServiceInfo destAi = dest.get(i).serviceInfo;
12948                if (destAi.name == filterSi.name
12949                        && destAi.packageName == filterSi.packageName) {
12950                    return false;
12951                }
12952            }
12953            return true;
12954        }
12955
12956        @Override
12957        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12958            return new PackageParser.ServiceIntentInfo[size];
12959        }
12960
12961        @Override
12962        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12963            if (!sUserManager.exists(userId)) return true;
12964            PackageParser.Package p = filter.service.owner;
12965            if (p != null) {
12966                PackageSetting ps = (PackageSetting)p.mExtras;
12967                if (ps != null) {
12968                    // System apps are never considered stopped for purposes of
12969                    // filtering, because there may be no way for the user to
12970                    // actually re-launch them.
12971                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12972                            && ps.getStopped(userId);
12973                }
12974            }
12975            return false;
12976        }
12977
12978        @Override
12979        protected boolean isPackageForFilter(String packageName,
12980                PackageParser.ServiceIntentInfo info) {
12981            return packageName.equals(info.service.owner.packageName);
12982        }
12983
12984        @Override
12985        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12986                int match, int userId) {
12987            if (!sUserManager.exists(userId)) return null;
12988            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12989            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12990                return null;
12991            }
12992            final PackageParser.Service service = info.service;
12993            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12994            if (ps == null) {
12995                return null;
12996            }
12997            final PackageUserState userState = ps.readUserState(userId);
12998            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12999                    userState, userId);
13000            if (si == null) {
13001                return null;
13002            }
13003            final boolean matchVisibleToInstantApp =
13004                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13005            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13006            // throw out filters that aren't visible to ephemeral apps
13007            if (matchVisibleToInstantApp
13008                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13009                return null;
13010            }
13011            // throw out ephemeral filters if we're not explicitly requesting them
13012            if (!isInstantApp && userState.instantApp) {
13013                return null;
13014            }
13015            // throw out instant app filters if updates are available; will trigger
13016            // instant app resolution
13017            if (userState.instantApp && ps.isUpdateAvailable()) {
13018                return null;
13019            }
13020            final ResolveInfo res = new ResolveInfo();
13021            res.serviceInfo = si;
13022            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13023                res.filter = filter;
13024            }
13025            res.priority = info.getPriority();
13026            res.preferredOrder = service.owner.mPreferredOrder;
13027            res.match = match;
13028            res.isDefault = info.hasDefault;
13029            res.labelRes = info.labelRes;
13030            res.nonLocalizedLabel = info.nonLocalizedLabel;
13031            res.icon = info.icon;
13032            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13033            return res;
13034        }
13035
13036        @Override
13037        protected void sortResults(List<ResolveInfo> results) {
13038            Collections.sort(results, mResolvePrioritySorter);
13039        }
13040
13041        @Override
13042        protected void dumpFilter(PrintWriter out, String prefix,
13043                PackageParser.ServiceIntentInfo filter) {
13044            out.print(prefix); out.print(
13045                    Integer.toHexString(System.identityHashCode(filter.service)));
13046                    out.print(' ');
13047                    filter.service.printComponentShortName(out);
13048                    out.print(" filter ");
13049                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13050                    if (filter.service.info.permission != null) {
13051                        out.print(" permission "); out.println(filter.service.info.permission);
13052                    } else {
13053                        out.println();
13054                    }
13055        }
13056
13057        @Override
13058        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13059            return filter.service;
13060        }
13061
13062        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13063            PackageParser.Service service = (PackageParser.Service)label;
13064            out.print(prefix); out.print(
13065                    Integer.toHexString(System.identityHashCode(service)));
13066                    out.print(' ');
13067                    service.printComponentShortName(out);
13068            if (count > 1) {
13069                out.print(" ("); out.print(count); out.print(" filters)");
13070            }
13071            out.println();
13072        }
13073
13074//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13075//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13076//            final List<ResolveInfo> retList = Lists.newArrayList();
13077//            while (i.hasNext()) {
13078//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13079//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13080//                    retList.add(resolveInfo);
13081//                }
13082//            }
13083//            return retList;
13084//        }
13085
13086        // Keys are String (activity class name), values are Activity.
13087        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13088                = new ArrayMap<ComponentName, PackageParser.Service>();
13089        private int mFlags;
13090    }
13091
13092    private final class ProviderIntentResolver
13093            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13094        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13095                boolean defaultOnly, int userId) {
13096            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13097            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13098        }
13099
13100        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13101                int userId) {
13102            if (!sUserManager.exists(userId))
13103                return null;
13104            mFlags = flags;
13105            return super.queryIntent(intent, resolvedType,
13106                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13107                    userId);
13108        }
13109
13110        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13111                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13112            if (!sUserManager.exists(userId))
13113                return null;
13114            if (packageProviders == null) {
13115                return null;
13116            }
13117            mFlags = flags;
13118            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13119            final int N = packageProviders.size();
13120            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13121                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13122
13123            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13124            for (int i = 0; i < N; ++i) {
13125                intentFilters = packageProviders.get(i).intents;
13126                if (intentFilters != null && intentFilters.size() > 0) {
13127                    PackageParser.ProviderIntentInfo[] array =
13128                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13129                    intentFilters.toArray(array);
13130                    listCut.add(array);
13131                }
13132            }
13133            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13134        }
13135
13136        public final void addProvider(PackageParser.Provider p) {
13137            if (mProviders.containsKey(p.getComponentName())) {
13138                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13139                return;
13140            }
13141
13142            mProviders.put(p.getComponentName(), p);
13143            if (DEBUG_SHOW_INFO) {
13144                Log.v(TAG, "  "
13145                        + (p.info.nonLocalizedLabel != null
13146                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13147                Log.v(TAG, "    Class=" + p.info.name);
13148            }
13149            final int NI = p.intents.size();
13150            int j;
13151            for (j = 0; j < NI; j++) {
13152                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13153                if (DEBUG_SHOW_INFO) {
13154                    Log.v(TAG, "    IntentFilter:");
13155                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13156                }
13157                if (!intent.debugCheck()) {
13158                    Log.w(TAG, "==> For Provider " + p.info.name);
13159                }
13160                addFilter(intent);
13161            }
13162        }
13163
13164        public final void removeProvider(PackageParser.Provider p) {
13165            mProviders.remove(p.getComponentName());
13166            if (DEBUG_SHOW_INFO) {
13167                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13168                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13169                Log.v(TAG, "    Class=" + p.info.name);
13170            }
13171            final int NI = p.intents.size();
13172            int j;
13173            for (j = 0; j < NI; j++) {
13174                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13175                if (DEBUG_SHOW_INFO) {
13176                    Log.v(TAG, "    IntentFilter:");
13177                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13178                }
13179                removeFilter(intent);
13180            }
13181        }
13182
13183        @Override
13184        protected boolean allowFilterResult(
13185                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13186            ProviderInfo filterPi = filter.provider.info;
13187            for (int i = dest.size() - 1; i >= 0; i--) {
13188                ProviderInfo destPi = dest.get(i).providerInfo;
13189                if (destPi.name == filterPi.name
13190                        && destPi.packageName == filterPi.packageName) {
13191                    return false;
13192                }
13193            }
13194            return true;
13195        }
13196
13197        @Override
13198        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13199            return new PackageParser.ProviderIntentInfo[size];
13200        }
13201
13202        @Override
13203        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13204            if (!sUserManager.exists(userId))
13205                return true;
13206            PackageParser.Package p = filter.provider.owner;
13207            if (p != null) {
13208                PackageSetting ps = (PackageSetting) p.mExtras;
13209                if (ps != null) {
13210                    // System apps are never considered stopped for purposes of
13211                    // filtering, because there may be no way for the user to
13212                    // actually re-launch them.
13213                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13214                            && ps.getStopped(userId);
13215                }
13216            }
13217            return false;
13218        }
13219
13220        @Override
13221        protected boolean isPackageForFilter(String packageName,
13222                PackageParser.ProviderIntentInfo info) {
13223            return packageName.equals(info.provider.owner.packageName);
13224        }
13225
13226        @Override
13227        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13228                int match, int userId) {
13229            if (!sUserManager.exists(userId))
13230                return null;
13231            final PackageParser.ProviderIntentInfo info = filter;
13232            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13233                return null;
13234            }
13235            final PackageParser.Provider provider = info.provider;
13236            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13237            if (ps == null) {
13238                return null;
13239            }
13240            final PackageUserState userState = ps.readUserState(userId);
13241            final boolean matchVisibleToInstantApp =
13242                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13243            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13244            // throw out filters that aren't visible to instant applications
13245            if (matchVisibleToInstantApp
13246                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13247                return null;
13248            }
13249            // throw out instant application filters if we're not explicitly requesting them
13250            if (!isInstantApp && userState.instantApp) {
13251                return null;
13252            }
13253            // throw out instant application filters if updates are available; will trigger
13254            // instant application resolution
13255            if (userState.instantApp && ps.isUpdateAvailable()) {
13256                return null;
13257            }
13258            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13259                    userState, userId);
13260            if (pi == null) {
13261                return null;
13262            }
13263            final ResolveInfo res = new ResolveInfo();
13264            res.providerInfo = pi;
13265            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13266                res.filter = filter;
13267            }
13268            res.priority = info.getPriority();
13269            res.preferredOrder = provider.owner.mPreferredOrder;
13270            res.match = match;
13271            res.isDefault = info.hasDefault;
13272            res.labelRes = info.labelRes;
13273            res.nonLocalizedLabel = info.nonLocalizedLabel;
13274            res.icon = info.icon;
13275            res.system = res.providerInfo.applicationInfo.isSystemApp();
13276            return res;
13277        }
13278
13279        @Override
13280        protected void sortResults(List<ResolveInfo> results) {
13281            Collections.sort(results, mResolvePrioritySorter);
13282        }
13283
13284        @Override
13285        protected void dumpFilter(PrintWriter out, String prefix,
13286                PackageParser.ProviderIntentInfo filter) {
13287            out.print(prefix);
13288            out.print(
13289                    Integer.toHexString(System.identityHashCode(filter.provider)));
13290            out.print(' ');
13291            filter.provider.printComponentShortName(out);
13292            out.print(" filter ");
13293            out.println(Integer.toHexString(System.identityHashCode(filter)));
13294        }
13295
13296        @Override
13297        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13298            return filter.provider;
13299        }
13300
13301        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13302            PackageParser.Provider provider = (PackageParser.Provider)label;
13303            out.print(prefix); out.print(
13304                    Integer.toHexString(System.identityHashCode(provider)));
13305                    out.print(' ');
13306                    provider.printComponentShortName(out);
13307            if (count > 1) {
13308                out.print(" ("); out.print(count); out.print(" filters)");
13309            }
13310            out.println();
13311        }
13312
13313        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13314                = new ArrayMap<ComponentName, PackageParser.Provider>();
13315        private int mFlags;
13316    }
13317
13318    static final class InstantAppIntentResolver
13319            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13320            AuxiliaryResolveInfo.AuxiliaryFilter> {
13321        /**
13322         * The result that has the highest defined order. Ordering applies on a
13323         * per-package basis. Mapping is from package name to Pair of order and
13324         * EphemeralResolveInfo.
13325         * <p>
13326         * NOTE: This is implemented as a field variable for convenience and efficiency.
13327         * By having a field variable, we're able to track filter ordering as soon as
13328         * a non-zero order is defined. Otherwise, multiple loops across the result set
13329         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13330         * this needs to be contained entirely within {@link #filterResults}.
13331         */
13332        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13333
13334        @Override
13335        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13336            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13337        }
13338
13339        @Override
13340        protected boolean isPackageForFilter(String packageName,
13341                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13342            return true;
13343        }
13344
13345        @Override
13346        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13347                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13348            if (!sUserManager.exists(userId)) {
13349                return null;
13350            }
13351            final String packageName = responseObj.resolveInfo.getPackageName();
13352            final Integer order = responseObj.getOrder();
13353            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13354                    mOrderResult.get(packageName);
13355            // ordering is enabled and this item's order isn't high enough
13356            if (lastOrderResult != null && lastOrderResult.first >= order) {
13357                return null;
13358            }
13359            final InstantAppResolveInfo res = responseObj.resolveInfo;
13360            if (order > 0) {
13361                // non-zero order, enable ordering
13362                mOrderResult.put(packageName, new Pair<>(order, res));
13363            }
13364            return responseObj;
13365        }
13366
13367        @Override
13368        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13369            // only do work if ordering is enabled [most of the time it won't be]
13370            if (mOrderResult.size() == 0) {
13371                return;
13372            }
13373            int resultSize = results.size();
13374            for (int i = 0; i < resultSize; i++) {
13375                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13376                final String packageName = info.getPackageName();
13377                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13378                if (savedInfo == null) {
13379                    // package doesn't having ordering
13380                    continue;
13381                }
13382                if (savedInfo.second == info) {
13383                    // circled back to the highest ordered item; remove from order list
13384                    mOrderResult.remove(packageName);
13385                    if (mOrderResult.size() == 0) {
13386                        // no more ordered items
13387                        break;
13388                    }
13389                    continue;
13390                }
13391                // item has a worse order, remove it from the result list
13392                results.remove(i);
13393                resultSize--;
13394                i--;
13395            }
13396        }
13397    }
13398
13399    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13400            new Comparator<ResolveInfo>() {
13401        public int compare(ResolveInfo r1, ResolveInfo r2) {
13402            int v1 = r1.priority;
13403            int v2 = r2.priority;
13404            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13405            if (v1 != v2) {
13406                return (v1 > v2) ? -1 : 1;
13407            }
13408            v1 = r1.preferredOrder;
13409            v2 = r2.preferredOrder;
13410            if (v1 != v2) {
13411                return (v1 > v2) ? -1 : 1;
13412            }
13413            if (r1.isDefault != r2.isDefault) {
13414                return r1.isDefault ? -1 : 1;
13415            }
13416            v1 = r1.match;
13417            v2 = r2.match;
13418            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13419            if (v1 != v2) {
13420                return (v1 > v2) ? -1 : 1;
13421            }
13422            if (r1.system != r2.system) {
13423                return r1.system ? -1 : 1;
13424            }
13425            if (r1.activityInfo != null) {
13426                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13427            }
13428            if (r1.serviceInfo != null) {
13429                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13430            }
13431            if (r1.providerInfo != null) {
13432                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13433            }
13434            return 0;
13435        }
13436    };
13437
13438    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13439            new Comparator<ProviderInfo>() {
13440        public int compare(ProviderInfo p1, ProviderInfo p2) {
13441            final int v1 = p1.initOrder;
13442            final int v2 = p2.initOrder;
13443            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13444        }
13445    };
13446
13447    @Override
13448    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13449            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13450            final int[] userIds, int[] instantUserIds) {
13451        mHandler.post(new Runnable() {
13452            @Override
13453            public void run() {
13454                try {
13455                    final IActivityManager am = ActivityManager.getService();
13456                    if (am == null) return;
13457                    final int[] resolvedUserIds;
13458                    if (userIds == null) {
13459                        resolvedUserIds = am.getRunningUserIds();
13460                    } else {
13461                        resolvedUserIds = userIds;
13462                    }
13463                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13464                            resolvedUserIds, false);
13465                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13466                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13467                                instantUserIds, true);
13468                    }
13469                } catch (RemoteException ex) {
13470                }
13471            }
13472        });
13473    }
13474
13475    @Override
13476    public void notifyPackageAdded(String packageName) {
13477        final PackageListObserver[] observers;
13478        synchronized (mPackages) {
13479            if (mPackageListObservers.size() == 0) {
13480                return;
13481            }
13482            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13483        }
13484        for (int i = observers.length - 1; i >= 0; --i) {
13485            observers[i].onPackageAdded(packageName);
13486        }
13487    }
13488
13489    @Override
13490    public void notifyPackageRemoved(String packageName) {
13491        final PackageListObserver[] observers;
13492        synchronized (mPackages) {
13493            if (mPackageListObservers.size() == 0) {
13494                return;
13495            }
13496            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13497        }
13498        for (int i = observers.length - 1; i >= 0; --i) {
13499            observers[i].onPackageRemoved(packageName);
13500        }
13501    }
13502
13503    /**
13504     * Sends a broadcast for the given action.
13505     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13506     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13507     * the system and applications allowed to see instant applications to receive package
13508     * lifecycle events for instant applications.
13509     */
13510    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13511            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13512            int[] userIds, boolean isInstantApp)
13513                    throws RemoteException {
13514        for (int id : userIds) {
13515            final Intent intent = new Intent(action,
13516                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13517            final String[] requiredPermissions =
13518                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13519            if (extras != null) {
13520                intent.putExtras(extras);
13521            }
13522            if (targetPkg != null) {
13523                intent.setPackage(targetPkg);
13524            }
13525            // Modify the UID when posting to other users
13526            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13527            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13528                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13529                intent.putExtra(Intent.EXTRA_UID, uid);
13530            }
13531            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13532            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13533            if (DEBUG_BROADCASTS) {
13534                RuntimeException here = new RuntimeException("here");
13535                here.fillInStackTrace();
13536                Slog.d(TAG, "Sending to user " + id + ": "
13537                        + intent.toShortString(false, true, false, false)
13538                        + " " + intent.getExtras(), here);
13539            }
13540            am.broadcastIntent(null, intent, null, finishedReceiver,
13541                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13542                    null, finishedReceiver != null, false, id);
13543        }
13544    }
13545
13546    /**
13547     * Check if the external storage media is available. This is true if there
13548     * is a mounted external storage medium or if the external storage is
13549     * emulated.
13550     */
13551    private boolean isExternalMediaAvailable() {
13552        return mMediaMounted || Environment.isExternalStorageEmulated();
13553    }
13554
13555    @Override
13556    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13557        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13558            return null;
13559        }
13560        if (!isExternalMediaAvailable()) {
13561                // If the external storage is no longer mounted at this point,
13562                // the caller may not have been able to delete all of this
13563                // packages files and can not delete any more.  Bail.
13564            return null;
13565        }
13566        synchronized (mPackages) {
13567            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13568            if (lastPackage != null) {
13569                pkgs.remove(lastPackage);
13570            }
13571            if (pkgs.size() > 0) {
13572                return pkgs.get(0);
13573            }
13574        }
13575        return null;
13576    }
13577
13578    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13579        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13580                userId, andCode ? 1 : 0, packageName);
13581        if (mSystemReady) {
13582            msg.sendToTarget();
13583        } else {
13584            if (mPostSystemReadyMessages == null) {
13585                mPostSystemReadyMessages = new ArrayList<>();
13586            }
13587            mPostSystemReadyMessages.add(msg);
13588        }
13589    }
13590
13591    void startCleaningPackages() {
13592        // reader
13593        if (!isExternalMediaAvailable()) {
13594            return;
13595        }
13596        synchronized (mPackages) {
13597            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13598                return;
13599            }
13600        }
13601        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13602        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13603        IActivityManager am = ActivityManager.getService();
13604        if (am != null) {
13605            int dcsUid = -1;
13606            synchronized (mPackages) {
13607                if (!mDefaultContainerWhitelisted) {
13608                    mDefaultContainerWhitelisted = true;
13609                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13610                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13611                }
13612            }
13613            try {
13614                if (dcsUid > 0) {
13615                    am.backgroundWhitelistUid(dcsUid);
13616                }
13617                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13618                        UserHandle.USER_SYSTEM);
13619            } catch (RemoteException e) {
13620            }
13621        }
13622    }
13623
13624    /**
13625     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13626     * it is acting on behalf on an enterprise or the user).
13627     *
13628     * Note that the ordering of the conditionals in this method is important. The checks we perform
13629     * are as follows, in this order:
13630     *
13631     * 1) If the install is being performed by a system app, we can trust the app to have set the
13632     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13633     *    what it is.
13634     * 2) If the install is being performed by a device or profile owner app, the install reason
13635     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13636     *    set the install reason correctly. If the app targets an older SDK version where install
13637     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13638     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13639     * 3) In all other cases, the install is being performed by a regular app that is neither part
13640     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13641     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13642     *    set to enterprise policy and if so, change it to unknown instead.
13643     */
13644    private int fixUpInstallReason(String installerPackageName, int installerUid,
13645            int installReason) {
13646        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13647                == PERMISSION_GRANTED) {
13648            // If the install is being performed by a system app, we trust that app to have set the
13649            // install reason correctly.
13650            return installReason;
13651        }
13652        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13653                UserHandle.getUserId(installerUid));
13654        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13655            // If the install is being performed by a device or profile owner, the install
13656            // reason should be enterprise policy.
13657            return PackageManager.INSTALL_REASON_POLICY;
13658        }
13659
13660
13661        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13662            // If the install is being performed by a regular app (i.e. neither system app nor
13663            // device or profile owner), we have no reason to believe that the app is acting on
13664            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13665            // change it to unknown instead.
13666            return PackageManager.INSTALL_REASON_UNKNOWN;
13667        }
13668
13669        // If the install is being performed by a regular app and the install reason was set to any
13670        // value but enterprise policy, leave the install reason unchanged.
13671        return installReason;
13672    }
13673
13674    /**
13675     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13676     * install commit.
13677     */
13678    void earlyBindToDefContainer() {
13679        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13680    }
13681
13682    void installStage(String packageName, File stagedDir,
13683            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13684            String installerPackageName, int installerUid, UserHandle user,
13685            PackageParser.SigningDetails signingDetails) {
13686        if (DEBUG_INSTANT) {
13687            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13688                Slog.d(TAG, "Ephemeral install of " + packageName);
13689            }
13690        }
13691        final VerificationInfo verificationInfo = new VerificationInfo(
13692                sessionParams.originatingUri, sessionParams.referrerUri,
13693                sessionParams.originatingUid, installerUid);
13694
13695        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13696
13697        final Message msg = mHandler.obtainMessage(INIT_COPY);
13698        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13699                sessionParams.installReason);
13700        final InstallParams params = new InstallParams(origin, null, observer,
13701                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13702                verificationInfo, user, sessionParams.abiOverride,
13703                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13704        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13705        msg.obj = params;
13706
13707        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13708                System.identityHashCode(msg.obj));
13709        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13710                System.identityHashCode(msg.obj));
13711
13712        mHandler.sendMessage(msg);
13713    }
13714
13715    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13716            int userId) {
13717        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13718        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13719        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13720        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13721        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13722                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13723
13724        // Send a session commit broadcast
13725        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13726        info.installReason = pkgSetting.getInstallReason(userId);
13727        info.appPackageName = packageName;
13728        sendSessionCommitBroadcast(info, userId);
13729    }
13730
13731    @Override
13732    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13733            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13734        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13735            return;
13736        }
13737        Bundle extras = new Bundle(1);
13738        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13739        final int uid = UserHandle.getUid(
13740                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13741        extras.putInt(Intent.EXTRA_UID, uid);
13742
13743        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13744                packageName, extras, 0, null, null, userIds, instantUserIds);
13745        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13746            mHandler.post(() -> {
13747                        for (int userId : userIds) {
13748                            sendBootCompletedBroadcastToSystemApp(
13749                                    packageName, includeStopped, userId);
13750                        }
13751                    }
13752            );
13753        }
13754    }
13755
13756    /**
13757     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13758     * automatically without needing an explicit launch.
13759     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13760     */
13761    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13762            int userId) {
13763        // If user is not running, the app didn't miss any broadcast
13764        if (!mUserManagerInternal.isUserRunning(userId)) {
13765            return;
13766        }
13767        final IActivityManager am = ActivityManager.getService();
13768        try {
13769            // Deliver LOCKED_BOOT_COMPLETED first
13770            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13771                    .setPackage(packageName);
13772            if (includeStopped) {
13773                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13774            }
13775            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13776            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13777                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13778
13779            // Deliver BOOT_COMPLETED only if user is unlocked
13780            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13781                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13782                if (includeStopped) {
13783                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13784                }
13785                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13786                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13787            }
13788        } catch (RemoteException e) {
13789            throw e.rethrowFromSystemServer();
13790        }
13791    }
13792
13793    @Override
13794    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13795            int userId) {
13796        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13797        PackageSetting pkgSetting;
13798        final int callingUid = Binder.getCallingUid();
13799        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13800                true /* requireFullPermission */, true /* checkShell */,
13801                "setApplicationHiddenSetting for user " + userId);
13802
13803        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13804            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13805            return false;
13806        }
13807
13808        long callingId = Binder.clearCallingIdentity();
13809        try {
13810            boolean sendAdded = false;
13811            boolean sendRemoved = false;
13812            // writer
13813            synchronized (mPackages) {
13814                pkgSetting = mSettings.mPackages.get(packageName);
13815                if (pkgSetting == null) {
13816                    return false;
13817                }
13818                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13819                    return false;
13820                }
13821                // Do not allow "android" is being disabled
13822                if ("android".equals(packageName)) {
13823                    Slog.w(TAG, "Cannot hide package: android");
13824                    return false;
13825                }
13826                // Cannot hide static shared libs as they are considered
13827                // a part of the using app (emulating static linking). Also
13828                // static libs are installed always on internal storage.
13829                PackageParser.Package pkg = mPackages.get(packageName);
13830                if (pkg != null && pkg.staticSharedLibName != null) {
13831                    Slog.w(TAG, "Cannot hide package: " + packageName
13832                            + " providing static shared library: "
13833                            + pkg.staticSharedLibName);
13834                    return false;
13835                }
13836                // Only allow protected packages to hide themselves.
13837                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13838                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13839                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13840                    return false;
13841                }
13842
13843                if (pkgSetting.getHidden(userId) != hidden) {
13844                    pkgSetting.setHidden(hidden, userId);
13845                    mSettings.writePackageRestrictionsLPr(userId);
13846                    if (hidden) {
13847                        sendRemoved = true;
13848                    } else {
13849                        sendAdded = true;
13850                    }
13851                }
13852            }
13853            if (sendAdded) {
13854                sendPackageAddedForUser(packageName, pkgSetting, userId);
13855                return true;
13856            }
13857            if (sendRemoved) {
13858                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13859                        "hiding pkg");
13860                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13861                return true;
13862            }
13863        } finally {
13864            Binder.restoreCallingIdentity(callingId);
13865        }
13866        return false;
13867    }
13868
13869    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13870            int userId) {
13871        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13872        info.removedPackage = packageName;
13873        info.installerPackageName = pkgSetting.installerPackageName;
13874        info.removedUsers = new int[] {userId};
13875        info.broadcastUsers = new int[] {userId};
13876        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13877        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13878    }
13879
13880    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13881            PersistableBundle launcherExtras) {
13882        if (pkgList.length > 0) {
13883            Bundle extras = new Bundle(1);
13884            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13885            if (launcherExtras != null) {
13886                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13887                        new Bundle(launcherExtras.deepCopy()));
13888            }
13889            sendPackageBroadcast(
13890                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13891                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13892                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13893                    new int[] {userId}, null);
13894        }
13895    }
13896
13897    /**
13898     * Returns true if application is not found or there was an error. Otherwise it returns
13899     * the hidden state of the package for the given user.
13900     */
13901    @Override
13902    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13904        final int callingUid = Binder.getCallingUid();
13905        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13906                true /* requireFullPermission */, false /* checkShell */,
13907                "getApplicationHidden for user " + userId);
13908        PackageSetting ps;
13909        long callingId = Binder.clearCallingIdentity();
13910        try {
13911            // writer
13912            synchronized (mPackages) {
13913                ps = mSettings.mPackages.get(packageName);
13914                if (ps == null) {
13915                    return true;
13916                }
13917                if (filterAppAccessLPr(ps, callingUid, userId)) {
13918                    return true;
13919                }
13920                return ps.getHidden(userId);
13921            }
13922        } finally {
13923            Binder.restoreCallingIdentity(callingId);
13924        }
13925    }
13926
13927    /**
13928     * @hide
13929     */
13930    @Override
13931    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13932            int installReason) {
13933        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13934                null);
13935        PackageSetting pkgSetting;
13936        final int callingUid = Binder.getCallingUid();
13937        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13938                true /* requireFullPermission */, true /* checkShell */,
13939                "installExistingPackage for user " + userId);
13940        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13941            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13942        }
13943
13944        long callingId = Binder.clearCallingIdentity();
13945        try {
13946            boolean installed = false;
13947            final boolean instantApp =
13948                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13949            final boolean fullApp =
13950                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13951
13952            // writer
13953            synchronized (mPackages) {
13954                pkgSetting = mSettings.mPackages.get(packageName);
13955                if (pkgSetting == null) {
13956                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13957                }
13958                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13959                    // only allow the existing package to be used if it's installed as a full
13960                    // application for at least one user
13961                    boolean installAllowed = false;
13962                    for (int checkUserId : sUserManager.getUserIds()) {
13963                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13964                        if (installAllowed) {
13965                            break;
13966                        }
13967                    }
13968                    if (!installAllowed) {
13969                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13970                    }
13971                }
13972                if (!pkgSetting.getInstalled(userId)) {
13973                    pkgSetting.setInstalled(true, userId);
13974                    pkgSetting.setHidden(false, userId);
13975                    pkgSetting.setInstallReason(installReason, userId);
13976                    mSettings.writePackageRestrictionsLPr(userId);
13977                    mSettings.writeKernelMappingLPr(pkgSetting);
13978                    installed = true;
13979                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13980                    // upgrade app from instant to full; we don't allow app downgrade
13981                    installed = true;
13982                }
13983                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13984            }
13985
13986            if (installed) {
13987                if (pkgSetting.pkg != null) {
13988                    synchronized (mInstallLock) {
13989                        // We don't need to freeze for a brand new install
13990                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13991                    }
13992                }
13993                sendPackageAddedForUser(packageName, pkgSetting, userId);
13994                synchronized (mPackages) {
13995                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13996                }
13997            }
13998        } finally {
13999            Binder.restoreCallingIdentity(callingId);
14000        }
14001
14002        return PackageManager.INSTALL_SUCCEEDED;
14003    }
14004
14005    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14006            boolean instantApp, boolean fullApp) {
14007        // no state specified; do nothing
14008        if (!instantApp && !fullApp) {
14009            return;
14010        }
14011        if (userId != UserHandle.USER_ALL) {
14012            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14013                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14014            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14015                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14016            }
14017        } else {
14018            for (int currentUserId : sUserManager.getUserIds()) {
14019                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14020                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14021                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14022                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14023                }
14024            }
14025        }
14026    }
14027
14028    boolean isUserRestricted(int userId, String restrictionKey) {
14029        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14030        if (restrictions.getBoolean(restrictionKey, false)) {
14031            Log.w(TAG, "User is restricted: " + restrictionKey);
14032            return true;
14033        }
14034        return false;
14035    }
14036
14037    @Override
14038    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14039            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14040            String callingPackage, int userId) {
14041        try {
14042            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14043        } catch (SecurityException e) {
14044            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14045                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14046                            + Manifest.permission.MANAGE_USERS);
14047        }
14048        final int callingUid = Binder.getCallingUid();
14049        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14050                true /* requireFullPermission */, true /* checkShell */,
14051                "setPackagesSuspended for user " + userId);
14052        if (callingUid != Process.ROOT_UID &&
14053                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14054            throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not"
14055                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14056        }
14057        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14058                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14059            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14060                    + userId + " has an active DO or PO");
14061        }
14062        if (ArrayUtils.isEmpty(packageNames)) {
14063            return packageNames;
14064        }
14065
14066        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14067        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14068        final long callingId = Binder.clearCallingIdentity();
14069        try {
14070            synchronized (mPackages) {
14071                for (int i = 0; i < packageNames.length; i++) {
14072                    final String packageName = packageNames[i];
14073                    if (callingPackage.equals(packageName)) {
14074                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14075                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14076                        unactionedPackages.add(packageName);
14077                        continue;
14078                    }
14079                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14080                    if (pkgSetting == null
14081                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14082                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14083                                + ". Skipping suspending/un-suspending.");
14084                        unactionedPackages.add(packageName);
14085                        continue;
14086                    }
14087                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14088                        unactionedPackages.add(packageName);
14089                        continue;
14090                    }
14091                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14092                            launcherExtras, userId);
14093                    changedPackagesList.add(packageName);
14094                }
14095            }
14096        } finally {
14097            Binder.restoreCallingIdentity(callingId);
14098        }
14099        if (!changedPackagesList.isEmpty()) {
14100            final String[] changedPackages = changedPackagesList.toArray(
14101                    new String[changedPackagesList.size()]);
14102            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14103            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14104            synchronized (mPackages) {
14105                scheduleWritePackageRestrictionsLocked(userId);
14106            }
14107        }
14108        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14109    }
14110
14111    @Override
14112    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14113        final int callingUid = Binder.getCallingUid();
14114        if (getPackageUid(packageName, 0, userId) != callingUid) {
14115            throw new SecurityException("Calling package " + packageName
14116                    + " does not belong to calling uid " + callingUid);
14117        }
14118        synchronized (mPackages) {
14119            final PackageSetting ps = mSettings.mPackages.get(packageName);
14120            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14121                throw new IllegalArgumentException("Unknown target package: " + packageName);
14122            }
14123            final PackageUserState packageUserState = ps.readUserState(userId);
14124            if (packageUserState.suspended) {
14125                return packageUserState.suspendedAppExtras;
14126            }
14127            return null;
14128        }
14129    }
14130
14131    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14132            PersistableBundle appExtras, int userId) {
14133        final String action;
14134        final Bundle intentExtras = new Bundle();
14135        if (suspended) {
14136            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14137            if (appExtras != null) {
14138                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14139                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14140            }
14141        } else {
14142            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14143        }
14144        mHandler.post(new Runnable() {
14145            @Override
14146            public void run() {
14147                try {
14148                    final IActivityManager am = ActivityManager.getService();
14149                    if (am == null) {
14150                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14151                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14152                        return;
14153                    }
14154                    final int[] targetUserIds = new int[] {userId};
14155                    for (String packageName : affectedPackages) {
14156                        doSendBroadcast(am, action, null, intentExtras,
14157                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14158                                targetUserIds, false);
14159                    }
14160                } catch (RemoteException ex) {
14161                    // Shouldn't happen as AMS is in the same process.
14162                }
14163            }
14164        });
14165    }
14166
14167    @Override
14168    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14169        final int callingUid = Binder.getCallingUid();
14170        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14171                true /* requireFullPermission */, false /* checkShell */,
14172                "isPackageSuspendedForUser for user " + userId);
14173        synchronized (mPackages) {
14174            final PackageSetting ps = mSettings.mPackages.get(packageName);
14175            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14176                throw new IllegalArgumentException("Unknown target package: " + packageName);
14177            }
14178            return ps.getSuspended(userId);
14179        }
14180    }
14181
14182    void onSuspendingPackageRemoved(String packageName, int removedForUser) {
14183        final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14184                : new int[] {removedForUser};
14185        for (int userId : userIds) {
14186            List<String> affectedPackages = new ArrayList<>();
14187            synchronized (mPackages) {
14188                for (PackageSetting ps : mSettings.mPackages.values()) {
14189                    final PackageUserState pus = ps.readUserState(userId);
14190                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14191                        ps.setSuspended(false, null, null, null, null, userId);
14192                        affectedPackages.add(ps.name);
14193                    }
14194                }
14195            }
14196            if (!affectedPackages.isEmpty()) {
14197                final String[] packageArray = affectedPackages.toArray(
14198                        new String[affectedPackages.size()]);
14199                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14200                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14201            }
14202        }
14203    }
14204
14205    @GuardedBy("mPackages")
14206    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14207        if (isPackageDeviceAdmin(packageName, userId)) {
14208            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14209                    + "\": has an active device admin");
14210            return false;
14211        }
14212
14213        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14214        if (packageName.equals(activeLauncherPackageName)) {
14215            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14216                    + "\": contains the active launcher");
14217            return false;
14218        }
14219
14220        if (packageName.equals(mRequiredInstallerPackage)) {
14221            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14222                    + "\": required for package installation");
14223            return false;
14224        }
14225
14226        if (packageName.equals(mRequiredUninstallerPackage)) {
14227            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14228                    + "\": required for package uninstallation");
14229            return false;
14230        }
14231
14232        if (packageName.equals(mRequiredVerifierPackage)) {
14233            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14234                    + "\": required for package verification");
14235            return false;
14236        }
14237
14238        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14239            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14240                    + "\": is the default dialer");
14241            return false;
14242        }
14243
14244        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14245            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14246                    + "\": protected package");
14247            return false;
14248        }
14249
14250        // Cannot suspend static shared libs as they are considered
14251        // a part of the using app (emulating static linking). Also
14252        // static libs are installed always on internal storage.
14253        PackageParser.Package pkg = mPackages.get(packageName);
14254        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14255            Slog.w(TAG, "Cannot suspend package: " + packageName
14256                    + " providing static shared library: "
14257                    + pkg.staticSharedLibName);
14258            return false;
14259        }
14260
14261        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14262            Slog.w(TAG, "Cannot suspend package: " + packageName);
14263            return false;
14264        }
14265
14266        return true;
14267    }
14268
14269    private String getActiveLauncherPackageName(int userId) {
14270        Intent intent = new Intent(Intent.ACTION_MAIN);
14271        intent.addCategory(Intent.CATEGORY_HOME);
14272        ResolveInfo resolveInfo = resolveIntent(
14273                intent,
14274                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14275                PackageManager.MATCH_DEFAULT_ONLY,
14276                userId);
14277
14278        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14279    }
14280
14281    private String getDefaultDialerPackageName(int userId) {
14282        synchronized (mPackages) {
14283            return mSettings.getDefaultDialerPackageNameLPw(userId);
14284        }
14285    }
14286
14287    @Override
14288    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14289        mContext.enforceCallingOrSelfPermission(
14290                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14291                "Only package verification agents can verify applications");
14292
14293        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14294        final PackageVerificationResponse response = new PackageVerificationResponse(
14295                verificationCode, Binder.getCallingUid());
14296        msg.arg1 = id;
14297        msg.obj = response;
14298        mHandler.sendMessage(msg);
14299    }
14300
14301    @Override
14302    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14303            long millisecondsToDelay) {
14304        mContext.enforceCallingOrSelfPermission(
14305                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14306                "Only package verification agents can extend verification timeouts");
14307
14308        final PackageVerificationState state = mPendingVerification.get(id);
14309        final PackageVerificationResponse response = new PackageVerificationResponse(
14310                verificationCodeAtTimeout, Binder.getCallingUid());
14311
14312        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14313            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14314        }
14315        if (millisecondsToDelay < 0) {
14316            millisecondsToDelay = 0;
14317        }
14318        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14319                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14320            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14321        }
14322
14323        if ((state != null) && !state.timeoutExtended()) {
14324            state.extendTimeout();
14325
14326            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14327            msg.arg1 = id;
14328            msg.obj = response;
14329            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14330        }
14331    }
14332
14333    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14334            int verificationCode, UserHandle user) {
14335        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14336        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14337        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14338        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14339        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14340
14341        mContext.sendBroadcastAsUser(intent, user,
14342                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14343    }
14344
14345    private ComponentName matchComponentForVerifier(String packageName,
14346            List<ResolveInfo> receivers) {
14347        ActivityInfo targetReceiver = null;
14348
14349        final int NR = receivers.size();
14350        for (int i = 0; i < NR; i++) {
14351            final ResolveInfo info = receivers.get(i);
14352            if (info.activityInfo == null) {
14353                continue;
14354            }
14355
14356            if (packageName.equals(info.activityInfo.packageName)) {
14357                targetReceiver = info.activityInfo;
14358                break;
14359            }
14360        }
14361
14362        if (targetReceiver == null) {
14363            return null;
14364        }
14365
14366        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14367    }
14368
14369    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14370            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14371        if (pkgInfo.verifiers.length == 0) {
14372            return null;
14373        }
14374
14375        final int N = pkgInfo.verifiers.length;
14376        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14377        for (int i = 0; i < N; i++) {
14378            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14379
14380            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14381                    receivers);
14382            if (comp == null) {
14383                continue;
14384            }
14385
14386            final int verifierUid = getUidForVerifier(verifierInfo);
14387            if (verifierUid == -1) {
14388                continue;
14389            }
14390
14391            if (DEBUG_VERIFY) {
14392                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14393                        + " with the correct signature");
14394            }
14395            sufficientVerifiers.add(comp);
14396            verificationState.addSufficientVerifier(verifierUid);
14397        }
14398
14399        return sufficientVerifiers;
14400    }
14401
14402    private int getUidForVerifier(VerifierInfo verifierInfo) {
14403        synchronized (mPackages) {
14404            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14405            if (pkg == null) {
14406                return -1;
14407            } else if (pkg.mSigningDetails.signatures.length != 1) {
14408                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14409                        + " has more than one signature; ignoring");
14410                return -1;
14411            }
14412
14413            /*
14414             * If the public key of the package's signature does not match
14415             * our expected public key, then this is a different package and
14416             * we should skip.
14417             */
14418
14419            final byte[] expectedPublicKey;
14420            try {
14421                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14422                final PublicKey publicKey = verifierSig.getPublicKey();
14423                expectedPublicKey = publicKey.getEncoded();
14424            } catch (CertificateException e) {
14425                return -1;
14426            }
14427
14428            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14429
14430            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14431                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14432                        + " does not have the expected public key; ignoring");
14433                return -1;
14434            }
14435
14436            return pkg.applicationInfo.uid;
14437        }
14438    }
14439
14440    @Override
14441    public void finishPackageInstall(int token, boolean didLaunch) {
14442        enforceSystemOrRoot("Only the system is allowed to finish installs");
14443
14444        if (DEBUG_INSTALL) {
14445            Slog.v(TAG, "BM finishing package install for " + token);
14446        }
14447        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14448
14449        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14450        mHandler.sendMessage(msg);
14451    }
14452
14453    /**
14454     * Get the verification agent timeout.  Used for both the APK verifier and the
14455     * intent filter verifier.
14456     *
14457     * @return verification timeout in milliseconds
14458     */
14459    private long getVerificationTimeout() {
14460        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14461                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14462                DEFAULT_VERIFICATION_TIMEOUT);
14463    }
14464
14465    /**
14466     * Get the default verification agent response code.
14467     *
14468     * @return default verification response code
14469     */
14470    private int getDefaultVerificationResponse(UserHandle user) {
14471        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14472            return PackageManager.VERIFICATION_REJECT;
14473        }
14474        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14475                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14476                DEFAULT_VERIFICATION_RESPONSE);
14477    }
14478
14479    /**
14480     * Check whether or not package verification has been enabled.
14481     *
14482     * @return true if verification should be performed
14483     */
14484    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14485        if (!DEFAULT_VERIFY_ENABLE) {
14486            return false;
14487        }
14488
14489        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14490
14491        // Check if installing from ADB
14492        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14493            // Do not run verification in a test harness environment
14494            if (ActivityManager.isRunningInTestHarness()) {
14495                return false;
14496            }
14497            if (ensureVerifyAppsEnabled) {
14498                return true;
14499            }
14500            // Check if the developer does not want package verification for ADB installs
14501            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14502                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14503                return false;
14504            }
14505        } else {
14506            // only when not installed from ADB, skip verification for instant apps when
14507            // the installer and verifier are the same.
14508            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14509                if (mInstantAppInstallerActivity != null
14510                        && mInstantAppInstallerActivity.packageName.equals(
14511                                mRequiredVerifierPackage)) {
14512                    try {
14513                        mContext.getSystemService(AppOpsManager.class)
14514                                .checkPackage(installerUid, mRequiredVerifierPackage);
14515                        if (DEBUG_VERIFY) {
14516                            Slog.i(TAG, "disable verification for instant app");
14517                        }
14518                        return false;
14519                    } catch (SecurityException ignore) { }
14520                }
14521            }
14522        }
14523
14524        if (ensureVerifyAppsEnabled) {
14525            return true;
14526        }
14527
14528        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14529                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14530    }
14531
14532    @Override
14533    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14534            throws RemoteException {
14535        mContext.enforceCallingOrSelfPermission(
14536                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14537                "Only intentfilter verification agents can verify applications");
14538
14539        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14540        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14541                Binder.getCallingUid(), verificationCode, failedDomains);
14542        msg.arg1 = id;
14543        msg.obj = response;
14544        mHandler.sendMessage(msg);
14545    }
14546
14547    @Override
14548    public int getIntentVerificationStatus(String packageName, int userId) {
14549        final int callingUid = Binder.getCallingUid();
14550        if (UserHandle.getUserId(callingUid) != userId) {
14551            mContext.enforceCallingOrSelfPermission(
14552                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14553                    "getIntentVerificationStatus" + userId);
14554        }
14555        if (getInstantAppPackageName(callingUid) != null) {
14556            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14557        }
14558        synchronized (mPackages) {
14559            final PackageSetting ps = mSettings.mPackages.get(packageName);
14560            if (ps == null
14561                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14562                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14563            }
14564            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14565        }
14566    }
14567
14568    @Override
14569    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14570        mContext.enforceCallingOrSelfPermission(
14571                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14572
14573        boolean result = false;
14574        synchronized (mPackages) {
14575            final PackageSetting ps = mSettings.mPackages.get(packageName);
14576            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14577                return false;
14578            }
14579            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14580        }
14581        if (result) {
14582            scheduleWritePackageRestrictionsLocked(userId);
14583        }
14584        return result;
14585    }
14586
14587    @Override
14588    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14589            String packageName) {
14590        final int callingUid = Binder.getCallingUid();
14591        if (getInstantAppPackageName(callingUid) != null) {
14592            return ParceledListSlice.emptyList();
14593        }
14594        synchronized (mPackages) {
14595            final PackageSetting ps = mSettings.mPackages.get(packageName);
14596            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14597                return ParceledListSlice.emptyList();
14598            }
14599            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14600        }
14601    }
14602
14603    @Override
14604    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14605        if (TextUtils.isEmpty(packageName)) {
14606            return ParceledListSlice.emptyList();
14607        }
14608        final int callingUid = Binder.getCallingUid();
14609        final int callingUserId = UserHandle.getUserId(callingUid);
14610        synchronized (mPackages) {
14611            PackageParser.Package pkg = mPackages.get(packageName);
14612            if (pkg == null || pkg.activities == null) {
14613                return ParceledListSlice.emptyList();
14614            }
14615            if (pkg.mExtras == null) {
14616                return ParceledListSlice.emptyList();
14617            }
14618            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14619            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14620                return ParceledListSlice.emptyList();
14621            }
14622            final int count = pkg.activities.size();
14623            ArrayList<IntentFilter> result = new ArrayList<>();
14624            for (int n=0; n<count; n++) {
14625                PackageParser.Activity activity = pkg.activities.get(n);
14626                if (activity.intents != null && activity.intents.size() > 0) {
14627                    result.addAll(activity.intents);
14628                }
14629            }
14630            return new ParceledListSlice<>(result);
14631        }
14632    }
14633
14634    @Override
14635    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14636        mContext.enforceCallingOrSelfPermission(
14637                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14638        if (UserHandle.getCallingUserId() != userId) {
14639            mContext.enforceCallingOrSelfPermission(
14640                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14641        }
14642
14643        synchronized (mPackages) {
14644            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14645            if (packageName != null) {
14646                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14647                        packageName, userId);
14648            }
14649            return result;
14650        }
14651    }
14652
14653    @Override
14654    public String getDefaultBrowserPackageName(int userId) {
14655        if (UserHandle.getCallingUserId() != userId) {
14656            mContext.enforceCallingOrSelfPermission(
14657                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14658        }
14659        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14660            return null;
14661        }
14662        synchronized (mPackages) {
14663            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14664        }
14665    }
14666
14667    /**
14668     * Get the "allow unknown sources" setting.
14669     *
14670     * @return the current "allow unknown sources" setting
14671     */
14672    private int getUnknownSourcesSettings() {
14673        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14674                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14675                -1);
14676    }
14677
14678    @Override
14679    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14680        final int callingUid = Binder.getCallingUid();
14681        if (getInstantAppPackageName(callingUid) != null) {
14682            return;
14683        }
14684        // writer
14685        synchronized (mPackages) {
14686            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14687            if (targetPackageSetting == null
14688                    || filterAppAccessLPr(
14689                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14690                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14691            }
14692
14693            PackageSetting installerPackageSetting;
14694            if (installerPackageName != null) {
14695                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14696                if (installerPackageSetting == null) {
14697                    throw new IllegalArgumentException("Unknown installer package: "
14698                            + installerPackageName);
14699                }
14700            } else {
14701                installerPackageSetting = null;
14702            }
14703
14704            Signature[] callerSignature;
14705            Object obj = mSettings.getUserIdLPr(callingUid);
14706            if (obj != null) {
14707                if (obj instanceof SharedUserSetting) {
14708                    callerSignature =
14709                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14710                } else if (obj instanceof PackageSetting) {
14711                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14712                } else {
14713                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14714                }
14715            } else {
14716                throw new SecurityException("Unknown calling UID: " + callingUid);
14717            }
14718
14719            // Verify: can't set installerPackageName to a package that is
14720            // not signed with the same cert as the caller.
14721            if (installerPackageSetting != null) {
14722                if (compareSignatures(callerSignature,
14723                        installerPackageSetting.signatures.mSigningDetails.signatures)
14724                        != PackageManager.SIGNATURE_MATCH) {
14725                    throw new SecurityException(
14726                            "Caller does not have same cert as new installer package "
14727                            + installerPackageName);
14728                }
14729            }
14730
14731            // Verify: if target already has an installer package, it must
14732            // be signed with the same cert as the caller.
14733            if (targetPackageSetting.installerPackageName != null) {
14734                PackageSetting setting = mSettings.mPackages.get(
14735                        targetPackageSetting.installerPackageName);
14736                // If the currently set package isn't valid, then it's always
14737                // okay to change it.
14738                if (setting != null) {
14739                    if (compareSignatures(callerSignature,
14740                            setting.signatures.mSigningDetails.signatures)
14741                            != PackageManager.SIGNATURE_MATCH) {
14742                        throw new SecurityException(
14743                                "Caller does not have same cert as old installer package "
14744                                + targetPackageSetting.installerPackageName);
14745                    }
14746                }
14747            }
14748
14749            // Okay!
14750            targetPackageSetting.installerPackageName = installerPackageName;
14751            if (installerPackageName != null) {
14752                mSettings.mInstallerPackages.add(installerPackageName);
14753            }
14754            scheduleWriteSettingsLocked();
14755        }
14756    }
14757
14758    @Override
14759    public void setApplicationCategoryHint(String packageName, int categoryHint,
14760            String callerPackageName) {
14761        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14762            throw new SecurityException("Instant applications don't have access to this method");
14763        }
14764        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14765                callerPackageName);
14766        synchronized (mPackages) {
14767            PackageSetting ps = mSettings.mPackages.get(packageName);
14768            if (ps == null) {
14769                throw new IllegalArgumentException("Unknown target package " + packageName);
14770            }
14771            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14772                throw new IllegalArgumentException("Unknown target package " + packageName);
14773            }
14774            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14775                throw new IllegalArgumentException("Calling package " + callerPackageName
14776                        + " is not installer for " + packageName);
14777            }
14778
14779            if (ps.categoryHint != categoryHint) {
14780                ps.categoryHint = categoryHint;
14781                scheduleWriteSettingsLocked();
14782            }
14783        }
14784    }
14785
14786    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14787        // Queue up an async operation since the package installation may take a little while.
14788        mHandler.post(new Runnable() {
14789            public void run() {
14790                mHandler.removeCallbacks(this);
14791                 // Result object to be returned
14792                PackageInstalledInfo res = new PackageInstalledInfo();
14793                res.setReturnCode(currentStatus);
14794                res.uid = -1;
14795                res.pkg = null;
14796                res.removedInfo = null;
14797                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14798                    args.doPreInstall(res.returnCode);
14799                    synchronized (mInstallLock) {
14800                        installPackageTracedLI(args, res);
14801                    }
14802                    args.doPostInstall(res.returnCode, res.uid);
14803                }
14804
14805                // A restore should be performed at this point if (a) the install
14806                // succeeded, (b) the operation is not an update, and (c) the new
14807                // package has not opted out of backup participation.
14808                final boolean update = res.removedInfo != null
14809                        && res.removedInfo.removedPackage != null;
14810                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14811                boolean doRestore = !update
14812                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14813
14814                // Set up the post-install work request bookkeeping.  This will be used
14815                // and cleaned up by the post-install event handling regardless of whether
14816                // there's a restore pass performed.  Token values are >= 1.
14817                int token;
14818                if (mNextInstallToken < 0) mNextInstallToken = 1;
14819                token = mNextInstallToken++;
14820
14821                PostInstallData data = new PostInstallData(args, res);
14822                mRunningInstalls.put(token, data);
14823                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14824
14825                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14826                    // Pass responsibility to the Backup Manager.  It will perform a
14827                    // restore if appropriate, then pass responsibility back to the
14828                    // Package Manager to run the post-install observer callbacks
14829                    // and broadcasts.
14830                    IBackupManager bm = IBackupManager.Stub.asInterface(
14831                            ServiceManager.getService(Context.BACKUP_SERVICE));
14832                    if (bm != null) {
14833                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14834                                + " to BM for possible restore");
14835                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14836                        try {
14837                            // TODO: http://b/22388012
14838                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14839                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14840                            } else {
14841                                doRestore = false;
14842                            }
14843                        } catch (RemoteException e) {
14844                            // can't happen; the backup manager is local
14845                        } catch (Exception e) {
14846                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14847                            doRestore = false;
14848                        }
14849                    } else {
14850                        Slog.e(TAG, "Backup Manager not found!");
14851                        doRestore = false;
14852                    }
14853                }
14854
14855                if (!doRestore) {
14856                    // No restore possible, or the Backup Manager was mysteriously not
14857                    // available -- just fire the post-install work request directly.
14858                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14859
14860                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14861
14862                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14863                    mHandler.sendMessage(msg);
14864                }
14865            }
14866        });
14867    }
14868
14869    /**
14870     * Callback from PackageSettings whenever an app is first transitioned out of the
14871     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14872     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14873     * here whether the app is the target of an ongoing install, and only send the
14874     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14875     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14876     * handling.
14877     */
14878    void notifyFirstLaunch(final String packageName, final String installerPackage,
14879            final int userId) {
14880        // Serialize this with the rest of the install-process message chain.  In the
14881        // restore-at-install case, this Runnable will necessarily run before the
14882        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14883        // are coherent.  In the non-restore case, the app has already completed install
14884        // and been launched through some other means, so it is not in a problematic
14885        // state for observers to see the FIRST_LAUNCH signal.
14886        mHandler.post(new Runnable() {
14887            @Override
14888            public void run() {
14889                for (int i = 0; i < mRunningInstalls.size(); i++) {
14890                    final PostInstallData data = mRunningInstalls.valueAt(i);
14891                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14892                        continue;
14893                    }
14894                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14895                        // right package; but is it for the right user?
14896                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14897                            if (userId == data.res.newUsers[uIndex]) {
14898                                if (DEBUG_BACKUP) {
14899                                    Slog.i(TAG, "Package " + packageName
14900                                            + " being restored so deferring FIRST_LAUNCH");
14901                                }
14902                                return;
14903                            }
14904                        }
14905                    }
14906                }
14907                // didn't find it, so not being restored
14908                if (DEBUG_BACKUP) {
14909                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14910                }
14911                final boolean isInstantApp = isInstantApp(packageName, userId);
14912                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14913                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14914                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14915            }
14916        });
14917    }
14918
14919    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14920            int[] userIds, int[] instantUserIds) {
14921        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14922                installerPkg, null, userIds, instantUserIds);
14923    }
14924
14925    private abstract class HandlerParams {
14926        private static final int MAX_RETRIES = 4;
14927
14928        /**
14929         * Number of times startCopy() has been attempted and had a non-fatal
14930         * error.
14931         */
14932        private int mRetries = 0;
14933
14934        /** User handle for the user requesting the information or installation. */
14935        private final UserHandle mUser;
14936        String traceMethod;
14937        int traceCookie;
14938
14939        HandlerParams(UserHandle user) {
14940            mUser = user;
14941        }
14942
14943        UserHandle getUser() {
14944            return mUser;
14945        }
14946
14947        HandlerParams setTraceMethod(String traceMethod) {
14948            this.traceMethod = traceMethod;
14949            return this;
14950        }
14951
14952        HandlerParams setTraceCookie(int traceCookie) {
14953            this.traceCookie = traceCookie;
14954            return this;
14955        }
14956
14957        final boolean startCopy() {
14958            boolean res;
14959            try {
14960                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14961
14962                if (++mRetries > MAX_RETRIES) {
14963                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14964                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14965                    handleServiceError();
14966                    return false;
14967                } else {
14968                    handleStartCopy();
14969                    res = true;
14970                }
14971            } catch (RemoteException e) {
14972                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14973                mHandler.sendEmptyMessage(MCS_RECONNECT);
14974                res = false;
14975            }
14976            handleReturnCode();
14977            return res;
14978        }
14979
14980        final void serviceError() {
14981            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14982            handleServiceError();
14983            handleReturnCode();
14984        }
14985
14986        abstract void handleStartCopy() throws RemoteException;
14987        abstract void handleServiceError();
14988        abstract void handleReturnCode();
14989    }
14990
14991    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14992        for (File path : paths) {
14993            try {
14994                mcs.clearDirectory(path.getAbsolutePath());
14995            } catch (RemoteException e) {
14996            }
14997        }
14998    }
14999
15000    static class OriginInfo {
15001        /**
15002         * Location where install is coming from, before it has been
15003         * copied/renamed into place. This could be a single monolithic APK
15004         * file, or a cluster directory. This location may be untrusted.
15005         */
15006        final File file;
15007
15008        /**
15009         * Flag indicating that {@link #file} or {@link #cid} has already been
15010         * staged, meaning downstream users don't need to defensively copy the
15011         * contents.
15012         */
15013        final boolean staged;
15014
15015        /**
15016         * Flag indicating that {@link #file} or {@link #cid} is an already
15017         * installed app that is being moved.
15018         */
15019        final boolean existing;
15020
15021        final String resolvedPath;
15022        final File resolvedFile;
15023
15024        static OriginInfo fromNothing() {
15025            return new OriginInfo(null, false, false);
15026        }
15027
15028        static OriginInfo fromUntrustedFile(File file) {
15029            return new OriginInfo(file, false, false);
15030        }
15031
15032        static OriginInfo fromExistingFile(File file) {
15033            return new OriginInfo(file, false, true);
15034        }
15035
15036        static OriginInfo fromStagedFile(File file) {
15037            return new OriginInfo(file, true, false);
15038        }
15039
15040        private OriginInfo(File file, boolean staged, boolean existing) {
15041            this.file = file;
15042            this.staged = staged;
15043            this.existing = existing;
15044
15045            if (file != null) {
15046                resolvedPath = file.getAbsolutePath();
15047                resolvedFile = file;
15048            } else {
15049                resolvedPath = null;
15050                resolvedFile = null;
15051            }
15052        }
15053    }
15054
15055    static class MoveInfo {
15056        final int moveId;
15057        final String fromUuid;
15058        final String toUuid;
15059        final String packageName;
15060        final String dataAppName;
15061        final int appId;
15062        final String seinfo;
15063        final int targetSdkVersion;
15064
15065        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15066                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15067            this.moveId = moveId;
15068            this.fromUuid = fromUuid;
15069            this.toUuid = toUuid;
15070            this.packageName = packageName;
15071            this.dataAppName = dataAppName;
15072            this.appId = appId;
15073            this.seinfo = seinfo;
15074            this.targetSdkVersion = targetSdkVersion;
15075        }
15076    }
15077
15078    static class VerificationInfo {
15079        /** A constant used to indicate that a uid value is not present. */
15080        public static final int NO_UID = -1;
15081
15082        /** URI referencing where the package was downloaded from. */
15083        final Uri originatingUri;
15084
15085        /** HTTP referrer URI associated with the originatingURI. */
15086        final Uri referrer;
15087
15088        /** UID of the application that the install request originated from. */
15089        final int originatingUid;
15090
15091        /** UID of application requesting the install */
15092        final int installerUid;
15093
15094        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15095            this.originatingUri = originatingUri;
15096            this.referrer = referrer;
15097            this.originatingUid = originatingUid;
15098            this.installerUid = installerUid;
15099        }
15100    }
15101
15102    class InstallParams extends HandlerParams {
15103        final OriginInfo origin;
15104        final MoveInfo move;
15105        final IPackageInstallObserver2 observer;
15106        int installFlags;
15107        final String installerPackageName;
15108        final String volumeUuid;
15109        private InstallArgs mArgs;
15110        private int mRet;
15111        final String packageAbiOverride;
15112        final String[] grantedRuntimePermissions;
15113        final VerificationInfo verificationInfo;
15114        final PackageParser.SigningDetails signingDetails;
15115        final int installReason;
15116
15117        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15118                int installFlags, String installerPackageName, String volumeUuid,
15119                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15120                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15121            super(user);
15122            this.origin = origin;
15123            this.move = move;
15124            this.observer = observer;
15125            this.installFlags = installFlags;
15126            this.installerPackageName = installerPackageName;
15127            this.volumeUuid = volumeUuid;
15128            this.verificationInfo = verificationInfo;
15129            this.packageAbiOverride = packageAbiOverride;
15130            this.grantedRuntimePermissions = grantedPermissions;
15131            this.signingDetails = signingDetails;
15132            this.installReason = installReason;
15133        }
15134
15135        @Override
15136        public String toString() {
15137            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15138                    + " file=" + origin.file + "}";
15139        }
15140
15141        private int installLocationPolicy(PackageInfoLite pkgLite) {
15142            String packageName = pkgLite.packageName;
15143            int installLocation = pkgLite.installLocation;
15144            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15145            // reader
15146            synchronized (mPackages) {
15147                // Currently installed package which the new package is attempting to replace or
15148                // null if no such package is installed.
15149                PackageParser.Package installedPkg = mPackages.get(packageName);
15150                // Package which currently owns the data which the new package will own if installed.
15151                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15152                // will be null whereas dataOwnerPkg will contain information about the package
15153                // which was uninstalled while keeping its data.
15154                PackageParser.Package dataOwnerPkg = installedPkg;
15155                if (dataOwnerPkg  == null) {
15156                    PackageSetting ps = mSettings.mPackages.get(packageName);
15157                    if (ps != null) {
15158                        dataOwnerPkg = ps.pkg;
15159                    }
15160                }
15161
15162                if (dataOwnerPkg != null) {
15163                    // If installed, the package will get access to data left on the device by its
15164                    // predecessor. As a security measure, this is permited only if this is not a
15165                    // version downgrade or if the predecessor package is marked as debuggable and
15166                    // a downgrade is explicitly requested.
15167                    //
15168                    // On debuggable platform builds, downgrades are permitted even for
15169                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15170                    // not offer security guarantees and thus it's OK to disable some security
15171                    // mechanisms to make debugging/testing easier on those builds. However, even on
15172                    // debuggable builds downgrades of packages are permitted only if requested via
15173                    // installFlags. This is because we aim to keep the behavior of debuggable
15174                    // platform builds as close as possible to the behavior of non-debuggable
15175                    // platform builds.
15176                    final boolean downgradeRequested =
15177                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15178                    final boolean packageDebuggable =
15179                                (dataOwnerPkg.applicationInfo.flags
15180                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15181                    final boolean downgradePermitted =
15182                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15183                    if (!downgradePermitted) {
15184                        try {
15185                            checkDowngrade(dataOwnerPkg, pkgLite);
15186                        } catch (PackageManagerException e) {
15187                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15188                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15189                        }
15190                    }
15191                }
15192
15193                if (installedPkg != null) {
15194                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15195                        // Check for updated system application.
15196                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15197                            if (onSd) {
15198                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15199                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15200                            }
15201                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15202                        } else {
15203                            if (onSd) {
15204                                // Install flag overrides everything.
15205                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15206                            }
15207                            // If current upgrade specifies particular preference
15208                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15209                                // Application explicitly specified internal.
15210                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15211                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15212                                // App explictly prefers external. Let policy decide
15213                            } else {
15214                                // Prefer previous location
15215                                if (isExternal(installedPkg)) {
15216                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15217                                }
15218                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15219                            }
15220                        }
15221                    } else {
15222                        // Invalid install. Return error code
15223                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15224                    }
15225                }
15226            }
15227            // All the special cases have been taken care of.
15228            // Return result based on recommended install location.
15229            if (onSd) {
15230                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15231            }
15232            return pkgLite.recommendedInstallLocation;
15233        }
15234
15235        /*
15236         * Invoke remote method to get package information and install
15237         * location values. Override install location based on default
15238         * policy if needed and then create install arguments based
15239         * on the install location.
15240         */
15241        public void handleStartCopy() throws RemoteException {
15242            int ret = PackageManager.INSTALL_SUCCEEDED;
15243
15244            // If we're already staged, we've firmly committed to an install location
15245            if (origin.staged) {
15246                if (origin.file != null) {
15247                    installFlags |= PackageManager.INSTALL_INTERNAL;
15248                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15249                } else {
15250                    throw new IllegalStateException("Invalid stage location");
15251                }
15252            }
15253
15254            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15255            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15256            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15257            PackageInfoLite pkgLite = null;
15258
15259            if (onInt && onSd) {
15260                // Check if both bits are set.
15261                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15262                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15263            } else if (onSd && ephemeral) {
15264                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15265                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15266            } else {
15267                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15268                        packageAbiOverride);
15269
15270                if (DEBUG_INSTANT && ephemeral) {
15271                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15272                }
15273
15274                /*
15275                 * If we have too little free space, try to free cache
15276                 * before giving up.
15277                 */
15278                if (!origin.staged && pkgLite.recommendedInstallLocation
15279                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15280                    // TODO: focus freeing disk space on the target device
15281                    final StorageManager storage = StorageManager.from(mContext);
15282                    final long lowThreshold = storage.getStorageLowBytes(
15283                            Environment.getDataDirectory());
15284
15285                    final long sizeBytes = mContainerService.calculateInstalledSize(
15286                            origin.resolvedPath, packageAbiOverride);
15287
15288                    try {
15289                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15290                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15291                                installFlags, packageAbiOverride);
15292                    } catch (InstallerException e) {
15293                        Slog.w(TAG, "Failed to free cache", e);
15294                    }
15295
15296                    /*
15297                     * The cache free must have deleted the file we
15298                     * downloaded to install.
15299                     *
15300                     * TODO: fix the "freeCache" call to not delete
15301                     *       the file we care about.
15302                     */
15303                    if (pkgLite.recommendedInstallLocation
15304                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15305                        pkgLite.recommendedInstallLocation
15306                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15307                    }
15308                }
15309            }
15310
15311            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15312                int loc = pkgLite.recommendedInstallLocation;
15313                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15314                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15315                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15316                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15317                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15318                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15319                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15320                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15321                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15322                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15323                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15324                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15325                } else {
15326                    // Override with defaults if needed.
15327                    loc = installLocationPolicy(pkgLite);
15328                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15329                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15330                    } else if (!onSd && !onInt) {
15331                        // Override install location with flags
15332                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15333                            // Set the flag to install on external media.
15334                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15335                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15336                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15337                            if (DEBUG_INSTANT) {
15338                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15339                            }
15340                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15341                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15342                                    |PackageManager.INSTALL_INTERNAL);
15343                        } else {
15344                            // Make sure the flag for installing on external
15345                            // media is unset
15346                            installFlags |= PackageManager.INSTALL_INTERNAL;
15347                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15348                        }
15349                    }
15350                }
15351            }
15352
15353            final InstallArgs args = createInstallArgs(this);
15354            mArgs = args;
15355
15356            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15357                // TODO: http://b/22976637
15358                // Apps installed for "all" users use the device owner to verify the app
15359                UserHandle verifierUser = getUser();
15360                if (verifierUser == UserHandle.ALL) {
15361                    verifierUser = UserHandle.SYSTEM;
15362                }
15363
15364                /*
15365                 * Determine if we have any installed package verifiers. If we
15366                 * do, then we'll defer to them to verify the packages.
15367                 */
15368                final int requiredUid = mRequiredVerifierPackage == null ? -1
15369                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15370                                verifierUser.getIdentifier());
15371                final int installerUid =
15372                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15373                if (!origin.existing && requiredUid != -1
15374                        && isVerificationEnabled(
15375                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15376                    final Intent verification = new Intent(
15377                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15378                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15379                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15380                            PACKAGE_MIME_TYPE);
15381                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15382
15383                    // Query all live verifiers based on current user state
15384                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15385                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15386                            false /*allowDynamicSplits*/);
15387
15388                    if (DEBUG_VERIFY) {
15389                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15390                                + verification.toString() + " with " + pkgLite.verifiers.length
15391                                + " optional verifiers");
15392                    }
15393
15394                    final int verificationId = mPendingVerificationToken++;
15395
15396                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15397
15398                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15399                            installerPackageName);
15400
15401                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15402                            installFlags);
15403
15404                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15405                            pkgLite.packageName);
15406
15407                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15408                            pkgLite.versionCode);
15409
15410                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15411                            pkgLite.getLongVersionCode());
15412
15413                    if (verificationInfo != null) {
15414                        if (verificationInfo.originatingUri != null) {
15415                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15416                                    verificationInfo.originatingUri);
15417                        }
15418                        if (verificationInfo.referrer != null) {
15419                            verification.putExtra(Intent.EXTRA_REFERRER,
15420                                    verificationInfo.referrer);
15421                        }
15422                        if (verificationInfo.originatingUid >= 0) {
15423                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15424                                    verificationInfo.originatingUid);
15425                        }
15426                        if (verificationInfo.installerUid >= 0) {
15427                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15428                                    verificationInfo.installerUid);
15429                        }
15430                    }
15431
15432                    final PackageVerificationState verificationState = new PackageVerificationState(
15433                            requiredUid, args);
15434
15435                    mPendingVerification.append(verificationId, verificationState);
15436
15437                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15438                            receivers, verificationState);
15439
15440                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15441                    final long idleDuration = getVerificationTimeout();
15442
15443                    /*
15444                     * If any sufficient verifiers were listed in the package
15445                     * manifest, attempt to ask them.
15446                     */
15447                    if (sufficientVerifiers != null) {
15448                        final int N = sufficientVerifiers.size();
15449                        if (N == 0) {
15450                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15451                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15452                        } else {
15453                            for (int i = 0; i < N; i++) {
15454                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15455                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15456                                        verifierComponent.getPackageName(), idleDuration,
15457                                        verifierUser.getIdentifier(), false, "package verifier");
15458
15459                                final Intent sufficientIntent = new Intent(verification);
15460                                sufficientIntent.setComponent(verifierComponent);
15461                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15462                            }
15463                        }
15464                    }
15465
15466                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15467                            mRequiredVerifierPackage, receivers);
15468                    if (ret == PackageManager.INSTALL_SUCCEEDED
15469                            && mRequiredVerifierPackage != null) {
15470                        Trace.asyncTraceBegin(
15471                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15472                        /*
15473                         * Send the intent to the required verification agent,
15474                         * but only start the verification timeout after the
15475                         * target BroadcastReceivers have run.
15476                         */
15477                        verification.setComponent(requiredVerifierComponent);
15478                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15479                                mRequiredVerifierPackage, idleDuration,
15480                                verifierUser.getIdentifier(), false, "package verifier");
15481                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15482                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15483                                new BroadcastReceiver() {
15484                                    @Override
15485                                    public void onReceive(Context context, Intent intent) {
15486                                        final Message msg = mHandler
15487                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15488                                        msg.arg1 = verificationId;
15489                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15490                                    }
15491                                }, null, 0, null, null);
15492
15493                        /*
15494                         * We don't want the copy to proceed until verification
15495                         * succeeds, so null out this field.
15496                         */
15497                        mArgs = null;
15498                    }
15499                } else {
15500                    /*
15501                     * No package verification is enabled, so immediately start
15502                     * the remote call to initiate copy using temporary file.
15503                     */
15504                    ret = args.copyApk(mContainerService, true);
15505                }
15506            }
15507
15508            mRet = ret;
15509        }
15510
15511        @Override
15512        void handleReturnCode() {
15513            // If mArgs is null, then MCS couldn't be reached. When it
15514            // reconnects, it will try again to install. At that point, this
15515            // will succeed.
15516            if (mArgs != null) {
15517                processPendingInstall(mArgs, mRet);
15518            }
15519        }
15520
15521        @Override
15522        void handleServiceError() {
15523            mArgs = createInstallArgs(this);
15524            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15525        }
15526    }
15527
15528    private InstallArgs createInstallArgs(InstallParams params) {
15529        if (params.move != null) {
15530            return new MoveInstallArgs(params);
15531        } else {
15532            return new FileInstallArgs(params);
15533        }
15534    }
15535
15536    /**
15537     * Create args that describe an existing installed package. Typically used
15538     * when cleaning up old installs, or used as a move source.
15539     */
15540    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15541            String resourcePath, String[] instructionSets) {
15542        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15543    }
15544
15545    static abstract class InstallArgs {
15546        /** @see InstallParams#origin */
15547        final OriginInfo origin;
15548        /** @see InstallParams#move */
15549        final MoveInfo move;
15550
15551        final IPackageInstallObserver2 observer;
15552        // Always refers to PackageManager flags only
15553        final int installFlags;
15554        final String installerPackageName;
15555        final String volumeUuid;
15556        final UserHandle user;
15557        final String abiOverride;
15558        final String[] installGrantPermissions;
15559        /** If non-null, drop an async trace when the install completes */
15560        final String traceMethod;
15561        final int traceCookie;
15562        final PackageParser.SigningDetails signingDetails;
15563        final int installReason;
15564
15565        // The list of instruction sets supported by this app. This is currently
15566        // only used during the rmdex() phase to clean up resources. We can get rid of this
15567        // if we move dex files under the common app path.
15568        /* nullable */ String[] instructionSets;
15569
15570        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15571                int installFlags, String installerPackageName, String volumeUuid,
15572                UserHandle user, String[] instructionSets,
15573                String abiOverride, String[] installGrantPermissions,
15574                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15575                int installReason) {
15576            this.origin = origin;
15577            this.move = move;
15578            this.installFlags = installFlags;
15579            this.observer = observer;
15580            this.installerPackageName = installerPackageName;
15581            this.volumeUuid = volumeUuid;
15582            this.user = user;
15583            this.instructionSets = instructionSets;
15584            this.abiOverride = abiOverride;
15585            this.installGrantPermissions = installGrantPermissions;
15586            this.traceMethod = traceMethod;
15587            this.traceCookie = traceCookie;
15588            this.signingDetails = signingDetails;
15589            this.installReason = installReason;
15590        }
15591
15592        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15593        abstract int doPreInstall(int status);
15594
15595        /**
15596         * Rename package into final resting place. All paths on the given
15597         * scanned package should be updated to reflect the rename.
15598         */
15599        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15600        abstract int doPostInstall(int status, int uid);
15601
15602        /** @see PackageSettingBase#codePathString */
15603        abstract String getCodePath();
15604        /** @see PackageSettingBase#resourcePathString */
15605        abstract String getResourcePath();
15606
15607        // Need installer lock especially for dex file removal.
15608        abstract void cleanUpResourcesLI();
15609        abstract boolean doPostDeleteLI(boolean delete);
15610
15611        /**
15612         * Called before the source arguments are copied. This is used mostly
15613         * for MoveParams when it needs to read the source file to put it in the
15614         * destination.
15615         */
15616        int doPreCopy() {
15617            return PackageManager.INSTALL_SUCCEEDED;
15618        }
15619
15620        /**
15621         * Called after the source arguments are copied. This is used mostly for
15622         * MoveParams when it needs to read the source file to put it in the
15623         * destination.
15624         */
15625        int doPostCopy(int uid) {
15626            return PackageManager.INSTALL_SUCCEEDED;
15627        }
15628
15629        protected boolean isFwdLocked() {
15630            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15631        }
15632
15633        protected boolean isExternalAsec() {
15634            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15635        }
15636
15637        protected boolean isEphemeral() {
15638            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15639        }
15640
15641        UserHandle getUser() {
15642            return user;
15643        }
15644    }
15645
15646    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15647        if (!allCodePaths.isEmpty()) {
15648            if (instructionSets == null) {
15649                throw new IllegalStateException("instructionSet == null");
15650            }
15651            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15652            for (String codePath : allCodePaths) {
15653                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15654                    try {
15655                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15656                    } catch (InstallerException ignored) {
15657                    }
15658                }
15659            }
15660        }
15661    }
15662
15663    /**
15664     * Logic to handle installation of non-ASEC applications, including copying
15665     * and renaming logic.
15666     */
15667    class FileInstallArgs extends InstallArgs {
15668        private File codeFile;
15669        private File resourceFile;
15670
15671        // Example topology:
15672        // /data/app/com.example/base.apk
15673        // /data/app/com.example/split_foo.apk
15674        // /data/app/com.example/lib/arm/libfoo.so
15675        // /data/app/com.example/lib/arm64/libfoo.so
15676        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15677
15678        /** New install */
15679        FileInstallArgs(InstallParams params) {
15680            super(params.origin, params.move, params.observer, params.installFlags,
15681                    params.installerPackageName, params.volumeUuid,
15682                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15683                    params.grantedRuntimePermissions,
15684                    params.traceMethod, params.traceCookie, params.signingDetails,
15685                    params.installReason);
15686            if (isFwdLocked()) {
15687                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15688            }
15689        }
15690
15691        /** Existing install */
15692        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15693            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15694                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15695                    PackageManager.INSTALL_REASON_UNKNOWN);
15696            this.codeFile = (codePath != null) ? new File(codePath) : null;
15697            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15698        }
15699
15700        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15701            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15702            try {
15703                return doCopyApk(imcs, temp);
15704            } finally {
15705                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15706            }
15707        }
15708
15709        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15710            if (origin.staged) {
15711                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15712                codeFile = origin.file;
15713                resourceFile = origin.file;
15714                return PackageManager.INSTALL_SUCCEEDED;
15715            }
15716
15717            try {
15718                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15719                final File tempDir =
15720                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15721                codeFile = tempDir;
15722                resourceFile = tempDir;
15723            } catch (IOException e) {
15724                Slog.w(TAG, "Failed to create copy file: " + e);
15725                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15726            }
15727
15728            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15729                @Override
15730                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15731                    if (!FileUtils.isValidExtFilename(name)) {
15732                        throw new IllegalArgumentException("Invalid filename: " + name);
15733                    }
15734                    try {
15735                        final File file = new File(codeFile, name);
15736                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15737                                O_RDWR | O_CREAT, 0644);
15738                        Os.chmod(file.getAbsolutePath(), 0644);
15739                        return new ParcelFileDescriptor(fd);
15740                    } catch (ErrnoException e) {
15741                        throw new RemoteException("Failed to open: " + e.getMessage());
15742                    }
15743                }
15744            };
15745
15746            int ret = PackageManager.INSTALL_SUCCEEDED;
15747            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15748            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15749                Slog.e(TAG, "Failed to copy package");
15750                return ret;
15751            }
15752
15753            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15754            NativeLibraryHelper.Handle handle = null;
15755            try {
15756                handle = NativeLibraryHelper.Handle.create(codeFile);
15757                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15758                        abiOverride);
15759            } catch (IOException e) {
15760                Slog.e(TAG, "Copying native libraries failed", e);
15761                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15762            } finally {
15763                IoUtils.closeQuietly(handle);
15764            }
15765
15766            return ret;
15767        }
15768
15769        int doPreInstall(int status) {
15770            if (status != PackageManager.INSTALL_SUCCEEDED) {
15771                cleanUp();
15772            }
15773            return status;
15774        }
15775
15776        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15777            if (status != PackageManager.INSTALL_SUCCEEDED) {
15778                cleanUp();
15779                return false;
15780            }
15781
15782            final File targetDir = codeFile.getParentFile();
15783            final File beforeCodeFile = codeFile;
15784            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15785
15786            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15787            try {
15788                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15789            } catch (ErrnoException e) {
15790                Slog.w(TAG, "Failed to rename", e);
15791                return false;
15792            }
15793
15794            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15795                Slog.w(TAG, "Failed to restorecon");
15796                return false;
15797            }
15798
15799            // Reflect the rename internally
15800            codeFile = afterCodeFile;
15801            resourceFile = afterCodeFile;
15802
15803            // Reflect the rename in scanned details
15804            try {
15805                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15806            } catch (IOException e) {
15807                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15808                return false;
15809            }
15810            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15811                    afterCodeFile, pkg.baseCodePath));
15812            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15813                    afterCodeFile, pkg.splitCodePaths));
15814
15815            // Reflect the rename in app info
15816            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15817            pkg.setApplicationInfoCodePath(pkg.codePath);
15818            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15819            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15820            pkg.setApplicationInfoResourcePath(pkg.codePath);
15821            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15822            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15823
15824            return true;
15825        }
15826
15827        int doPostInstall(int status, int uid) {
15828            if (status != PackageManager.INSTALL_SUCCEEDED) {
15829                cleanUp();
15830            }
15831            return status;
15832        }
15833
15834        @Override
15835        String getCodePath() {
15836            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15837        }
15838
15839        @Override
15840        String getResourcePath() {
15841            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15842        }
15843
15844        private boolean cleanUp() {
15845            if (codeFile == null || !codeFile.exists()) {
15846                return false;
15847            }
15848
15849            removeCodePathLI(codeFile);
15850
15851            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15852                resourceFile.delete();
15853            }
15854
15855            return true;
15856        }
15857
15858        void cleanUpResourcesLI() {
15859            // Try enumerating all code paths before deleting
15860            List<String> allCodePaths = Collections.EMPTY_LIST;
15861            if (codeFile != null && codeFile.exists()) {
15862                try {
15863                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15864                    allCodePaths = pkg.getAllCodePaths();
15865                } catch (PackageParserException e) {
15866                    // Ignored; we tried our best
15867                }
15868            }
15869
15870            cleanUp();
15871            removeDexFiles(allCodePaths, instructionSets);
15872        }
15873
15874        boolean doPostDeleteLI(boolean delete) {
15875            // XXX err, shouldn't we respect the delete flag?
15876            cleanUpResourcesLI();
15877            return true;
15878        }
15879    }
15880
15881    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15882            PackageManagerException {
15883        if (copyRet < 0) {
15884            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15885                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15886                throw new PackageManagerException(copyRet, message);
15887            }
15888        }
15889    }
15890
15891    /**
15892     * Extract the StorageManagerService "container ID" from the full code path of an
15893     * .apk.
15894     */
15895    static String cidFromCodePath(String fullCodePath) {
15896        int eidx = fullCodePath.lastIndexOf("/");
15897        String subStr1 = fullCodePath.substring(0, eidx);
15898        int sidx = subStr1.lastIndexOf("/");
15899        return subStr1.substring(sidx+1, eidx);
15900    }
15901
15902    /**
15903     * Logic to handle movement of existing installed applications.
15904     */
15905    class MoveInstallArgs extends InstallArgs {
15906        private File codeFile;
15907        private File resourceFile;
15908
15909        /** New install */
15910        MoveInstallArgs(InstallParams params) {
15911            super(params.origin, params.move, params.observer, params.installFlags,
15912                    params.installerPackageName, params.volumeUuid,
15913                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15914                    params.grantedRuntimePermissions,
15915                    params.traceMethod, params.traceCookie, params.signingDetails,
15916                    params.installReason);
15917        }
15918
15919        int copyApk(IMediaContainerService imcs, boolean temp) {
15920            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15921                    + move.fromUuid + " to " + move.toUuid);
15922            synchronized (mInstaller) {
15923                try {
15924                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15925                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15926                } catch (InstallerException e) {
15927                    Slog.w(TAG, "Failed to move app", e);
15928                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15929                }
15930            }
15931
15932            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15933            resourceFile = codeFile;
15934            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15935
15936            return PackageManager.INSTALL_SUCCEEDED;
15937        }
15938
15939        int doPreInstall(int status) {
15940            if (status != PackageManager.INSTALL_SUCCEEDED) {
15941                cleanUp(move.toUuid);
15942            }
15943            return status;
15944        }
15945
15946        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15947            if (status != PackageManager.INSTALL_SUCCEEDED) {
15948                cleanUp(move.toUuid);
15949                return false;
15950            }
15951
15952            // Reflect the move in app info
15953            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15954            pkg.setApplicationInfoCodePath(pkg.codePath);
15955            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15956            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15957            pkg.setApplicationInfoResourcePath(pkg.codePath);
15958            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15959            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15960
15961            return true;
15962        }
15963
15964        int doPostInstall(int status, int uid) {
15965            if (status == PackageManager.INSTALL_SUCCEEDED) {
15966                cleanUp(move.fromUuid);
15967            } else {
15968                cleanUp(move.toUuid);
15969            }
15970            return status;
15971        }
15972
15973        @Override
15974        String getCodePath() {
15975            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15976        }
15977
15978        @Override
15979        String getResourcePath() {
15980            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15981        }
15982
15983        private boolean cleanUp(String volumeUuid) {
15984            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15985                    move.dataAppName);
15986            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15987            final int[] userIds = sUserManager.getUserIds();
15988            synchronized (mInstallLock) {
15989                // Clean up both app data and code
15990                // All package moves are frozen until finished
15991                for (int userId : userIds) {
15992                    try {
15993                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15994                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15995                    } catch (InstallerException e) {
15996                        Slog.w(TAG, String.valueOf(e));
15997                    }
15998                }
15999                removeCodePathLI(codeFile);
16000            }
16001            return true;
16002        }
16003
16004        void cleanUpResourcesLI() {
16005            throw new UnsupportedOperationException();
16006        }
16007
16008        boolean doPostDeleteLI(boolean delete) {
16009            throw new UnsupportedOperationException();
16010        }
16011    }
16012
16013    static String getAsecPackageName(String packageCid) {
16014        int idx = packageCid.lastIndexOf("-");
16015        if (idx == -1) {
16016            return packageCid;
16017        }
16018        return packageCid.substring(0, idx);
16019    }
16020
16021    // Utility method used to create code paths based on package name and available index.
16022    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16023        String idxStr = "";
16024        int idx = 1;
16025        // Fall back to default value of idx=1 if prefix is not
16026        // part of oldCodePath
16027        if (oldCodePath != null) {
16028            String subStr = oldCodePath;
16029            // Drop the suffix right away
16030            if (suffix != null && subStr.endsWith(suffix)) {
16031                subStr = subStr.substring(0, subStr.length() - suffix.length());
16032            }
16033            // If oldCodePath already contains prefix find out the
16034            // ending index to either increment or decrement.
16035            int sidx = subStr.lastIndexOf(prefix);
16036            if (sidx != -1) {
16037                subStr = subStr.substring(sidx + prefix.length());
16038                if (subStr != null) {
16039                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16040                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16041                    }
16042                    try {
16043                        idx = Integer.parseInt(subStr);
16044                        if (idx <= 1) {
16045                            idx++;
16046                        } else {
16047                            idx--;
16048                        }
16049                    } catch(NumberFormatException e) {
16050                    }
16051                }
16052            }
16053        }
16054        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16055        return prefix + idxStr;
16056    }
16057
16058    private File getNextCodePath(File targetDir, String packageName) {
16059        File result;
16060        SecureRandom random = new SecureRandom();
16061        byte[] bytes = new byte[16];
16062        do {
16063            random.nextBytes(bytes);
16064            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16065            result = new File(targetDir, packageName + "-" + suffix);
16066        } while (result.exists());
16067        return result;
16068    }
16069
16070    // Utility method that returns the relative package path with respect
16071    // to the installation directory. Like say for /data/data/com.test-1.apk
16072    // string com.test-1 is returned.
16073    static String deriveCodePathName(String codePath) {
16074        if (codePath == null) {
16075            return null;
16076        }
16077        final File codeFile = new File(codePath);
16078        final String name = codeFile.getName();
16079        if (codeFile.isDirectory()) {
16080            return name;
16081        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16082            final int lastDot = name.lastIndexOf('.');
16083            return name.substring(0, lastDot);
16084        } else {
16085            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16086            return null;
16087        }
16088    }
16089
16090    static class PackageInstalledInfo {
16091        String name;
16092        int uid;
16093        // The set of users that originally had this package installed.
16094        int[] origUsers;
16095        // The set of users that now have this package installed.
16096        int[] newUsers;
16097        PackageParser.Package pkg;
16098        int returnCode;
16099        String returnMsg;
16100        String installerPackageName;
16101        PackageRemovedInfo removedInfo;
16102        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16103
16104        public void setError(int code, String msg) {
16105            setReturnCode(code);
16106            setReturnMessage(msg);
16107            Slog.w(TAG, msg);
16108        }
16109
16110        public void setError(String msg, PackageParserException e) {
16111            setReturnCode(e.error);
16112            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16113            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16114            for (int i = 0; i < childCount; i++) {
16115                addedChildPackages.valueAt(i).setError(msg, e);
16116            }
16117            Slog.w(TAG, msg, e);
16118        }
16119
16120        public void setError(String msg, PackageManagerException e) {
16121            returnCode = e.error;
16122            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16123            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16124            for (int i = 0; i < childCount; i++) {
16125                addedChildPackages.valueAt(i).setError(msg, e);
16126            }
16127            Slog.w(TAG, msg, e);
16128        }
16129
16130        public void setReturnCode(int returnCode) {
16131            this.returnCode = returnCode;
16132            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16133            for (int i = 0; i < childCount; i++) {
16134                addedChildPackages.valueAt(i).returnCode = returnCode;
16135            }
16136        }
16137
16138        private void setReturnMessage(String returnMsg) {
16139            this.returnMsg = returnMsg;
16140            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16141            for (int i = 0; i < childCount; i++) {
16142                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16143            }
16144        }
16145
16146        // In some error cases we want to convey more info back to the observer
16147        String origPackage;
16148        String origPermission;
16149    }
16150
16151    /*
16152     * Install a non-existing package.
16153     */
16154    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16155            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16156            String volumeUuid, PackageInstalledInfo res, int installReason) {
16157        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16158
16159        // Remember this for later, in case we need to rollback this install
16160        String pkgName = pkg.packageName;
16161
16162        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16163
16164        synchronized(mPackages) {
16165            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16166            if (renamedPackage != null) {
16167                // A package with the same name is already installed, though
16168                // it has been renamed to an older name.  The package we
16169                // are trying to install should be installed as an update to
16170                // the existing one, but that has not been requested, so bail.
16171                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16172                        + " without first uninstalling package running as "
16173                        + renamedPackage);
16174                return;
16175            }
16176            if (mPackages.containsKey(pkgName)) {
16177                // Don't allow installation over an existing package with the same name.
16178                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16179                        + " without first uninstalling.");
16180                return;
16181            }
16182        }
16183
16184        try {
16185            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16186                    System.currentTimeMillis(), user);
16187
16188            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16189
16190            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16191                prepareAppDataAfterInstallLIF(newPackage);
16192
16193            } else {
16194                // Remove package from internal structures, but keep around any
16195                // data that might have already existed
16196                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16197                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16198            }
16199        } catch (PackageManagerException e) {
16200            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16201        }
16202
16203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16204    }
16205
16206    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16207        try (DigestInputStream digestStream =
16208                new DigestInputStream(new FileInputStream(file), digest)) {
16209            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16210        }
16211    }
16212
16213    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16214            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16215            PackageInstalledInfo res, int installReason) {
16216        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16217
16218        final PackageParser.Package oldPackage;
16219        final PackageSetting ps;
16220        final String pkgName = pkg.packageName;
16221        final int[] allUsers;
16222        final int[] installedUsers;
16223
16224        synchronized(mPackages) {
16225            oldPackage = mPackages.get(pkgName);
16226            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16227
16228            // don't allow upgrade to target a release SDK from a pre-release SDK
16229            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16230                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16231            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16232                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16233            if (oldTargetsPreRelease
16234                    && !newTargetsPreRelease
16235                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16236                Slog.w(TAG, "Can't install package targeting released sdk");
16237                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16238                return;
16239            }
16240
16241            ps = mSettings.mPackages.get(pkgName);
16242
16243            // verify signatures are valid
16244            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16245            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16246                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16247                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16248                            "New package not signed by keys specified by upgrade-keysets: "
16249                                    + pkgName);
16250                    return;
16251                }
16252            } else {
16253
16254                // default to original signature matching
16255                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16256                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16257                                && !oldPackage.mSigningDetails.checkCapability(
16258                                        pkg.mSigningDetails,
16259                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16260                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16261                            "New package has a different signature: " + pkgName);
16262                    return;
16263                }
16264            }
16265
16266            // don't allow a system upgrade unless the upgrade hash matches
16267            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16268                byte[] digestBytes = null;
16269                try {
16270                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16271                    updateDigest(digest, new File(pkg.baseCodePath));
16272                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16273                        for (String path : pkg.splitCodePaths) {
16274                            updateDigest(digest, new File(path));
16275                        }
16276                    }
16277                    digestBytes = digest.digest();
16278                } catch (NoSuchAlgorithmException | IOException e) {
16279                    res.setError(INSTALL_FAILED_INVALID_APK,
16280                            "Could not compute hash: " + pkgName);
16281                    return;
16282                }
16283                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16284                    res.setError(INSTALL_FAILED_INVALID_APK,
16285                            "New package fails restrict-update check: " + pkgName);
16286                    return;
16287                }
16288                // retain upgrade restriction
16289                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16290            }
16291
16292            // Check for shared user id changes
16293            String invalidPackageName =
16294                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16295            if (invalidPackageName != null) {
16296                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16297                        "Package " + invalidPackageName + " tried to change user "
16298                                + oldPackage.mSharedUserId);
16299                return;
16300            }
16301
16302            // check if the new package supports all of the abis which the old package supports
16303            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16304            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16305            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16306                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16307                        "Update to package " + pkgName + " doesn't support multi arch");
16308                return;
16309            }
16310
16311            // In case of rollback, remember per-user/profile install state
16312            allUsers = sUserManager.getUserIds();
16313            installedUsers = ps.queryInstalledUsers(allUsers, true);
16314
16315            // don't allow an upgrade from full to ephemeral
16316            if (isInstantApp) {
16317                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16318                    for (int currentUser : allUsers) {
16319                        if (!ps.getInstantApp(currentUser)) {
16320                            // can't downgrade from full to instant
16321                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16322                                    + " for user: " + currentUser);
16323                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16324                            return;
16325                        }
16326                    }
16327                } else if (!ps.getInstantApp(user.getIdentifier())) {
16328                    // can't downgrade from full to instant
16329                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16330                            + " for user: " + user.getIdentifier());
16331                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16332                    return;
16333                }
16334            }
16335        }
16336
16337        // Update what is removed
16338        res.removedInfo = new PackageRemovedInfo(this);
16339        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16340        res.removedInfo.removedPackage = oldPackage.packageName;
16341        res.removedInfo.installerPackageName = ps.installerPackageName;
16342        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16343        res.removedInfo.isUpdate = true;
16344        res.removedInfo.origUsers = installedUsers;
16345        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16346        for (int i = 0; i < installedUsers.length; i++) {
16347            final int userId = installedUsers[i];
16348            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16349        }
16350
16351        final int childCount = (oldPackage.childPackages != null)
16352                ? oldPackage.childPackages.size() : 0;
16353        for (int i = 0; i < childCount; i++) {
16354            boolean childPackageUpdated = false;
16355            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16356            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16357            if (res.addedChildPackages != null) {
16358                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16359                if (childRes != null) {
16360                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16361                    childRes.removedInfo.removedPackage = childPkg.packageName;
16362                    if (childPs != null) {
16363                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16364                    }
16365                    childRes.removedInfo.isUpdate = true;
16366                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16367                    childPackageUpdated = true;
16368                }
16369            }
16370            if (!childPackageUpdated) {
16371                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16372                childRemovedRes.removedPackage = childPkg.packageName;
16373                if (childPs != null) {
16374                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16375                }
16376                childRemovedRes.isUpdate = false;
16377                childRemovedRes.dataRemoved = true;
16378                synchronized (mPackages) {
16379                    if (childPs != null) {
16380                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16381                    }
16382                }
16383                if (res.removedInfo.removedChildPackages == null) {
16384                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16385                }
16386                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16387            }
16388        }
16389
16390        boolean sysPkg = (isSystemApp(oldPackage));
16391        if (sysPkg) {
16392            // Set the system/privileged/oem/vendor/product flags as needed
16393            final boolean privileged =
16394                    (oldPackage.applicationInfo.privateFlags
16395                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16396            final boolean oem =
16397                    (oldPackage.applicationInfo.privateFlags
16398                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16399            final boolean vendor =
16400                    (oldPackage.applicationInfo.privateFlags
16401                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16402            final boolean product =
16403                    (oldPackage.applicationInfo.privateFlags
16404                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16405            final @ParseFlags int systemParseFlags = parseFlags;
16406            final @ScanFlags int systemScanFlags = scanFlags
16407                    | SCAN_AS_SYSTEM
16408                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16409                    | (oem ? SCAN_AS_OEM : 0)
16410                    | (vendor ? SCAN_AS_VENDOR : 0)
16411                    | (product ? SCAN_AS_PRODUCT : 0);
16412
16413            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16414                    user, allUsers, installerPackageName, res, installReason);
16415        } else {
16416            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16417                    user, allUsers, installerPackageName, res, installReason);
16418        }
16419    }
16420
16421    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16422            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16423            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16424            String installerPackageName, PackageInstalledInfo res, int installReason) {
16425        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16426                + deletedPackage);
16427
16428        String pkgName = deletedPackage.packageName;
16429        boolean deletedPkg = true;
16430        boolean addedPkg = false;
16431        boolean updatedSettings = false;
16432        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16433        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16434                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16435
16436        final long origUpdateTime = (pkg.mExtras != null)
16437                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16438
16439        // First delete the existing package while retaining the data directory
16440        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16441                res.removedInfo, true, pkg)) {
16442            // If the existing package wasn't successfully deleted
16443            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16444            deletedPkg = false;
16445        } else {
16446            // Successfully deleted the old package; proceed with replace.
16447
16448            // If deleted package lived in a container, give users a chance to
16449            // relinquish resources before killing.
16450            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16451                if (DEBUG_INSTALL) {
16452                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16453                }
16454                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16455                final ArrayList<String> pkgList = new ArrayList<String>(1);
16456                pkgList.add(deletedPackage.applicationInfo.packageName);
16457                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16458            }
16459
16460            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16461                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16462
16463            try {
16464                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16465                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16466                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16467                        installReason);
16468
16469                // Update the in-memory copy of the previous code paths.
16470                PackageSetting ps = mSettings.mPackages.get(pkgName);
16471                if (!killApp) {
16472                    if (ps.oldCodePaths == null) {
16473                        ps.oldCodePaths = new ArraySet<>();
16474                    }
16475                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16476                    if (deletedPackage.splitCodePaths != null) {
16477                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16478                    }
16479                } else {
16480                    ps.oldCodePaths = null;
16481                }
16482                if (ps.childPackageNames != null) {
16483                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16484                        final String childPkgName = ps.childPackageNames.get(i);
16485                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16486                        childPs.oldCodePaths = ps.oldCodePaths;
16487                    }
16488                }
16489                prepareAppDataAfterInstallLIF(newPackage);
16490                addedPkg = true;
16491                mDexManager.notifyPackageUpdated(newPackage.packageName,
16492                        newPackage.baseCodePath, newPackage.splitCodePaths);
16493            } catch (PackageManagerException e) {
16494                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16495            }
16496        }
16497
16498        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16499            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16500
16501            // Revert all internal state mutations and added folders for the failed install
16502            if (addedPkg) {
16503                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16504                        res.removedInfo, true, null);
16505            }
16506
16507            // Restore the old package
16508            if (deletedPkg) {
16509                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16510                File restoreFile = new File(deletedPackage.codePath);
16511                // Parse old package
16512                boolean oldExternal = isExternal(deletedPackage);
16513                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16514                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16515                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16516                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16517                try {
16518                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16519                            null);
16520                } catch (PackageManagerException e) {
16521                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16522                            + e.getMessage());
16523                    return;
16524                }
16525
16526                synchronized (mPackages) {
16527                    // Ensure the installer package name up to date
16528                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16529
16530                    // Update permissions for restored package
16531                    mPermissionManager.updatePermissions(
16532                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16533                            mPermissionCallback);
16534
16535                    mSettings.writeLPr();
16536                }
16537
16538                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16539            }
16540        } else {
16541            synchronized (mPackages) {
16542                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16543                if (ps != null) {
16544                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16545                    if (res.removedInfo.removedChildPackages != null) {
16546                        final int childCount = res.removedInfo.removedChildPackages.size();
16547                        // Iterate in reverse as we may modify the collection
16548                        for (int i = childCount - 1; i >= 0; i--) {
16549                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16550                            if (res.addedChildPackages.containsKey(childPackageName)) {
16551                                res.removedInfo.removedChildPackages.removeAt(i);
16552                            } else {
16553                                PackageRemovedInfo childInfo = res.removedInfo
16554                                        .removedChildPackages.valueAt(i);
16555                                childInfo.removedForAllUsers = mPackages.get(
16556                                        childInfo.removedPackage) == null;
16557                            }
16558                        }
16559                    }
16560                }
16561            }
16562        }
16563    }
16564
16565    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16566            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16567            final @ScanFlags int scanFlags, UserHandle user,
16568            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16569            int installReason) {
16570        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16571                + ", old=" + deletedPackage);
16572
16573        final boolean disabledSystem;
16574
16575        // Remove existing system package
16576        removePackageLI(deletedPackage, true);
16577
16578        synchronized (mPackages) {
16579            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16580        }
16581        if (!disabledSystem) {
16582            // We didn't need to disable the .apk as a current system package,
16583            // which means we are replacing another update that is already
16584            // installed.  We need to make sure to delete the older one's .apk.
16585            res.removedInfo.args = createInstallArgsForExisting(0,
16586                    deletedPackage.applicationInfo.getCodePath(),
16587                    deletedPackage.applicationInfo.getResourcePath(),
16588                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16589        } else {
16590            res.removedInfo.args = null;
16591        }
16592
16593        // Successfully disabled the old package. Now proceed with re-installation
16594        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16595                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16596
16597        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16598        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16599                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16600
16601        PackageParser.Package newPackage = null;
16602        try {
16603            // Add the package to the internal data structures
16604            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16605
16606            // Set the update and install times
16607            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16608            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16609                    System.currentTimeMillis());
16610
16611            // Update the package dynamic state if succeeded
16612            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16613                // Now that the install succeeded make sure we remove data
16614                // directories for any child package the update removed.
16615                final int deletedChildCount = (deletedPackage.childPackages != null)
16616                        ? deletedPackage.childPackages.size() : 0;
16617                final int newChildCount = (newPackage.childPackages != null)
16618                        ? newPackage.childPackages.size() : 0;
16619                for (int i = 0; i < deletedChildCount; i++) {
16620                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16621                    boolean childPackageDeleted = true;
16622                    for (int j = 0; j < newChildCount; j++) {
16623                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16624                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16625                            childPackageDeleted = false;
16626                            break;
16627                        }
16628                    }
16629                    if (childPackageDeleted) {
16630                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16631                                deletedChildPkg.packageName);
16632                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16633                            PackageRemovedInfo removedChildRes = res.removedInfo
16634                                    .removedChildPackages.get(deletedChildPkg.packageName);
16635                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16636                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16637                        }
16638                    }
16639                }
16640
16641                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16642                        installReason);
16643                prepareAppDataAfterInstallLIF(newPackage);
16644
16645                mDexManager.notifyPackageUpdated(newPackage.packageName,
16646                            newPackage.baseCodePath, newPackage.splitCodePaths);
16647            }
16648        } catch (PackageManagerException e) {
16649            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16650            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16651        }
16652
16653        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16654            // Re installation failed. Restore old information
16655            // Remove new pkg information
16656            if (newPackage != null) {
16657                removeInstalledPackageLI(newPackage, true);
16658            }
16659            // Add back the old system package
16660            try {
16661                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16662            } catch (PackageManagerException e) {
16663                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16664            }
16665
16666            synchronized (mPackages) {
16667                if (disabledSystem) {
16668                    enableSystemPackageLPw(deletedPackage);
16669                }
16670
16671                // Ensure the installer package name up to date
16672                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16673
16674                // Update permissions for restored package
16675                mPermissionManager.updatePermissions(
16676                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16677                        mPermissionCallback);
16678
16679                mSettings.writeLPr();
16680            }
16681
16682            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16683                    + " after failed upgrade");
16684        }
16685    }
16686
16687    /**
16688     * Checks whether the parent or any of the child packages have a change shared
16689     * user. For a package to be a valid update the shred users of the parent and
16690     * the children should match. We may later support changing child shared users.
16691     * @param oldPkg The updated package.
16692     * @param newPkg The update package.
16693     * @return The shared user that change between the versions.
16694     */
16695    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16696            PackageParser.Package newPkg) {
16697        // Check parent shared user
16698        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16699            return newPkg.packageName;
16700        }
16701        // Check child shared users
16702        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16703        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16704        for (int i = 0; i < newChildCount; i++) {
16705            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16706            // If this child was present, did it have the same shared user?
16707            for (int j = 0; j < oldChildCount; j++) {
16708                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16709                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16710                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16711                    return newChildPkg.packageName;
16712                }
16713            }
16714        }
16715        return null;
16716    }
16717
16718    private void removeNativeBinariesLI(PackageSetting ps) {
16719        // Remove the lib path for the parent package
16720        if (ps != null) {
16721            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16722            // Remove the lib path for the child packages
16723            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16724            for (int i = 0; i < childCount; i++) {
16725                PackageSetting childPs = null;
16726                synchronized (mPackages) {
16727                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16728                }
16729                if (childPs != null) {
16730                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16731                            .legacyNativeLibraryPathString);
16732                }
16733            }
16734        }
16735    }
16736
16737    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16738        // Enable the parent package
16739        mSettings.enableSystemPackageLPw(pkg.packageName);
16740        // Enable the child packages
16741        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16742        for (int i = 0; i < childCount; i++) {
16743            PackageParser.Package childPkg = pkg.childPackages.get(i);
16744            mSettings.enableSystemPackageLPw(childPkg.packageName);
16745        }
16746    }
16747
16748    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16749            PackageParser.Package newPkg) {
16750        // Disable the parent package (parent always replaced)
16751        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16752        // Disable the child packages
16753        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16754        for (int i = 0; i < childCount; i++) {
16755            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16756            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16757            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16758        }
16759        return disabled;
16760    }
16761
16762    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16763            String installerPackageName) {
16764        // Enable the parent package
16765        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16766        // Enable the child packages
16767        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16768        for (int i = 0; i < childCount; i++) {
16769            PackageParser.Package childPkg = pkg.childPackages.get(i);
16770            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16771        }
16772    }
16773
16774    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16775            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16776        // Update the parent package setting
16777        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16778                res, user, installReason);
16779        // Update the child packages setting
16780        final int childCount = (newPackage.childPackages != null)
16781                ? newPackage.childPackages.size() : 0;
16782        for (int i = 0; i < childCount; i++) {
16783            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16784            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16785            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16786                    childRes.origUsers, childRes, user, installReason);
16787        }
16788    }
16789
16790    private void updateSettingsInternalLI(PackageParser.Package pkg,
16791            String installerPackageName, int[] allUsers, int[] installedForUsers,
16792            PackageInstalledInfo res, UserHandle user, int installReason) {
16793        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16794
16795        final String pkgName = pkg.packageName;
16796
16797        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16798        synchronized (mPackages) {
16799// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16800            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16801                    mPermissionCallback);
16802            // For system-bundled packages, we assume that installing an upgraded version
16803            // of the package implies that the user actually wants to run that new code,
16804            // so we enable the package.
16805            PackageSetting ps = mSettings.mPackages.get(pkgName);
16806            final int userId = user.getIdentifier();
16807            if (ps != null) {
16808                if (isSystemApp(pkg)) {
16809                    if (DEBUG_INSTALL) {
16810                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16811                    }
16812                    // Enable system package for requested users
16813                    if (res.origUsers != null) {
16814                        for (int origUserId : res.origUsers) {
16815                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16816                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16817                                        origUserId, installerPackageName);
16818                            }
16819                        }
16820                    }
16821                    // Also convey the prior install/uninstall state
16822                    if (allUsers != null && installedForUsers != null) {
16823                        for (int currentUserId : allUsers) {
16824                            final boolean installed = ArrayUtils.contains(
16825                                    installedForUsers, currentUserId);
16826                            if (DEBUG_INSTALL) {
16827                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16828                            }
16829                            ps.setInstalled(installed, currentUserId);
16830                        }
16831                        // these install state changes will be persisted in the
16832                        // upcoming call to mSettings.writeLPr().
16833                    }
16834                }
16835                // It's implied that when a user requests installation, they want the app to be
16836                // installed and enabled.
16837                if (userId != UserHandle.USER_ALL) {
16838                    ps.setInstalled(true, userId);
16839                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16840                }
16841
16842                // When replacing an existing package, preserve the original install reason for all
16843                // users that had the package installed before.
16844                final Set<Integer> previousUserIds = new ArraySet<>();
16845                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16846                    final int installReasonCount = res.removedInfo.installReasons.size();
16847                    for (int i = 0; i < installReasonCount; i++) {
16848                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16849                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16850                        ps.setInstallReason(previousInstallReason, previousUserId);
16851                        previousUserIds.add(previousUserId);
16852                    }
16853                }
16854
16855                // Set install reason for users that are having the package newly installed.
16856                if (userId == UserHandle.USER_ALL) {
16857                    for (int currentUserId : sUserManager.getUserIds()) {
16858                        if (!previousUserIds.contains(currentUserId)) {
16859                            ps.setInstallReason(installReason, currentUserId);
16860                        }
16861                    }
16862                } else if (!previousUserIds.contains(userId)) {
16863                    ps.setInstallReason(installReason, userId);
16864                }
16865                mSettings.writeKernelMappingLPr(ps);
16866            }
16867            res.name = pkgName;
16868            res.uid = pkg.applicationInfo.uid;
16869            res.pkg = pkg;
16870            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16871            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16872            //to update install status
16873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16874            mSettings.writeLPr();
16875            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16876        }
16877
16878        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16879    }
16880
16881    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16882        try {
16883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16884            installPackageLI(args, res);
16885        } finally {
16886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16887        }
16888    }
16889
16890    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16891        final int installFlags = args.installFlags;
16892        final String installerPackageName = args.installerPackageName;
16893        final String volumeUuid = args.volumeUuid;
16894        final File tmpPackageFile = new File(args.getCodePath());
16895        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16896        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16897                || (args.volumeUuid != null));
16898        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16899        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16900        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16901        final boolean virtualPreload =
16902                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16903        boolean replace = false;
16904        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16905        if (args.move != null) {
16906            // moving a complete application; perform an initial scan on the new install location
16907            scanFlags |= SCAN_INITIAL;
16908        }
16909        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16910            scanFlags |= SCAN_DONT_KILL_APP;
16911        }
16912        if (instantApp) {
16913            scanFlags |= SCAN_AS_INSTANT_APP;
16914        }
16915        if (fullApp) {
16916            scanFlags |= SCAN_AS_FULL_APP;
16917        }
16918        if (virtualPreload) {
16919            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16920        }
16921
16922        // Result object to be returned
16923        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16924        res.installerPackageName = installerPackageName;
16925
16926        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16927
16928        // Sanity check
16929        if (instantApp && (forwardLocked || onExternal)) {
16930            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16931                    + " external=" + onExternal);
16932            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16933            return;
16934        }
16935
16936        // Retrieve PackageSettings and parse package
16937        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16938                | PackageParser.PARSE_ENFORCE_CODE
16939                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16940                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16941                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16942        PackageParser pp = new PackageParser();
16943        pp.setSeparateProcesses(mSeparateProcesses);
16944        pp.setDisplayMetrics(mMetrics);
16945        pp.setCallback(mPackageParserCallback);
16946
16947        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16948        final PackageParser.Package pkg;
16949        try {
16950            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16951            DexMetadataHelper.validatePackageDexMetadata(pkg);
16952        } catch (PackageParserException e) {
16953            res.setError("Failed parse during installPackageLI", e);
16954            return;
16955        } finally {
16956            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16957        }
16958
16959        // Instant apps have several additional install-time checks.
16960        if (instantApp) {
16961            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16962                Slog.w(TAG,
16963                        "Instant app package " + pkg.packageName + " does not target at least O");
16964                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16965                        "Instant app package must target at least O");
16966                return;
16967            }
16968            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16969                Slog.w(TAG, "Instant app package " + pkg.packageName
16970                        + " does not target targetSandboxVersion 2");
16971                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16972                        "Instant app package must use targetSandboxVersion 2");
16973                return;
16974            }
16975            if (pkg.mSharedUserId != null) {
16976                Slog.w(TAG, "Instant app package " + pkg.packageName
16977                        + " may not declare sharedUserId.");
16978                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16979                        "Instant app package may not declare a sharedUserId");
16980                return;
16981            }
16982        }
16983
16984        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16985            // Static shared libraries have synthetic package names
16986            renameStaticSharedLibraryPackage(pkg);
16987
16988            // No static shared libs on external storage
16989            if (onExternal) {
16990                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16991                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16992                        "Packages declaring static-shared libs cannot be updated");
16993                return;
16994            }
16995        }
16996
16997        // If we are installing a clustered package add results for the children
16998        if (pkg.childPackages != null) {
16999            synchronized (mPackages) {
17000                final int childCount = pkg.childPackages.size();
17001                for (int i = 0; i < childCount; i++) {
17002                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17003                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17004                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17005                    childRes.pkg = childPkg;
17006                    childRes.name = childPkg.packageName;
17007                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17008                    if (childPs != null) {
17009                        childRes.origUsers = childPs.queryInstalledUsers(
17010                                sUserManager.getUserIds(), true);
17011                    }
17012                    if ((mPackages.containsKey(childPkg.packageName))) {
17013                        childRes.removedInfo = new PackageRemovedInfo(this);
17014                        childRes.removedInfo.removedPackage = childPkg.packageName;
17015                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17016                    }
17017                    if (res.addedChildPackages == null) {
17018                        res.addedChildPackages = new ArrayMap<>();
17019                    }
17020                    res.addedChildPackages.put(childPkg.packageName, childRes);
17021                }
17022            }
17023        }
17024
17025        // If package doesn't declare API override, mark that we have an install
17026        // time CPU ABI override.
17027        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17028            pkg.cpuAbiOverride = args.abiOverride;
17029        }
17030
17031        String pkgName = res.name = pkg.packageName;
17032        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17033            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17034                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17035                return;
17036            }
17037        }
17038
17039        try {
17040            // either use what we've been given or parse directly from the APK
17041            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17042                pkg.setSigningDetails(args.signingDetails);
17043            } else {
17044                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17045            }
17046        } catch (PackageParserException e) {
17047            res.setError("Failed collect during installPackageLI", e);
17048            return;
17049        }
17050
17051        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17052                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17053            Slog.w(TAG, "Instant app package " + pkg.packageName
17054                    + " is not signed with at least APK Signature Scheme v2");
17055            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17056                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17057            return;
17058        }
17059
17060        // Get rid of all references to package scan path via parser.
17061        pp = null;
17062        String oldCodePath = null;
17063        boolean systemApp = false;
17064        synchronized (mPackages) {
17065            // Check if installing already existing package
17066            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17067                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17068                if (pkg.mOriginalPackages != null
17069                        && pkg.mOriginalPackages.contains(oldName)
17070                        && mPackages.containsKey(oldName)) {
17071                    // This package is derived from an original package,
17072                    // and this device has been updating from that original
17073                    // name.  We must continue using the original name, so
17074                    // rename the new package here.
17075                    pkg.setPackageName(oldName);
17076                    pkgName = pkg.packageName;
17077                    replace = true;
17078                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17079                            + oldName + " pkgName=" + pkgName);
17080                } else if (mPackages.containsKey(pkgName)) {
17081                    // This package, under its official name, already exists
17082                    // on the device; we should replace it.
17083                    replace = true;
17084                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17085                }
17086
17087                // Child packages are installed through the parent package
17088                if (pkg.parentPackage != null) {
17089                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17090                            "Package " + pkg.packageName + " is child of package "
17091                                    + pkg.parentPackage.parentPackage + ". Child packages "
17092                                    + "can be updated only through the parent package.");
17093                    return;
17094                }
17095
17096                if (replace) {
17097                    // Prevent apps opting out from runtime permissions
17098                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17099                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17100                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17101                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17102                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17103                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17104                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17105                                        + " doesn't support runtime permissions but the old"
17106                                        + " target SDK " + oldTargetSdk + " does.");
17107                        return;
17108                    }
17109                    // Prevent persistent apps from being updated
17110                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17111                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17112                                "Package " + oldPackage.packageName + " is a persistent app. "
17113                                        + "Persistent apps are not updateable.");
17114                        return;
17115                    }
17116                    // Prevent apps from downgrading their targetSandbox.
17117                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17118                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17119                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17120                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17121                                "Package " + pkg.packageName + " new target sandbox "
17122                                + newTargetSandbox + " is incompatible with the previous value of"
17123                                + oldTargetSandbox + ".");
17124                        return;
17125                    }
17126
17127                    // Prevent installing of child packages
17128                    if (oldPackage.parentPackage != null) {
17129                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17130                                "Package " + pkg.packageName + " is child of package "
17131                                        + oldPackage.parentPackage + ". Child packages "
17132                                        + "can be updated only through the parent package.");
17133                        return;
17134                    }
17135                }
17136            }
17137
17138            PackageSetting ps = mSettings.mPackages.get(pkgName);
17139            if (ps != null) {
17140                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17141
17142                // Static shared libs have same package with different versions where
17143                // we internally use a synthetic package name to allow multiple versions
17144                // of the same package, therefore we need to compare signatures against
17145                // the package setting for the latest library version.
17146                PackageSetting signatureCheckPs = ps;
17147                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17148                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17149                    if (libraryEntry != null) {
17150                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17151                    }
17152                }
17153
17154                // Quick sanity check that we're signed correctly if updating;
17155                // we'll check this again later when scanning, but we want to
17156                // bail early here before tripping over redefined permissions.
17157                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17158                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17159                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17160                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17161                                + pkg.packageName + " upgrade keys do not match the "
17162                                + "previously installed version");
17163                        return;
17164                    }
17165                } else {
17166                    try {
17167                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17168                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17169                        // We don't care about disabledPkgSetting on install for now.
17170                        final boolean compatMatch = verifySignatures(
17171                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17172                                compareRecover);
17173                        // The new KeySets will be re-added later in the scanning process.
17174                        if (compatMatch) {
17175                            synchronized (mPackages) {
17176                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17177                            }
17178                        }
17179                    } catch (PackageManagerException e) {
17180                        res.setError(e.error, e.getMessage());
17181                        return;
17182                    }
17183                }
17184
17185                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17186                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17187                    systemApp = (ps.pkg.applicationInfo.flags &
17188                            ApplicationInfo.FLAG_SYSTEM) != 0;
17189                }
17190                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17191            }
17192
17193            int N = pkg.permissions.size();
17194            for (int i = N-1; i >= 0; i--) {
17195                final PackageParser.Permission perm = pkg.permissions.get(i);
17196                final BasePermission bp =
17197                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17198
17199                // Don't allow anyone but the system to define ephemeral permissions.
17200                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17201                        && !systemApp) {
17202                    Slog.w(TAG, "Non-System package " + pkg.packageName
17203                            + " attempting to delcare ephemeral permission "
17204                            + perm.info.name + "; Removing ephemeral.");
17205                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17206                }
17207
17208                // Check whether the newly-scanned package wants to define an already-defined perm
17209                if (bp != null) {
17210                    // If the defining package is signed with our cert, it's okay.  This
17211                    // also includes the "updating the same package" case, of course.
17212                    // "updating same package" could also involve key-rotation.
17213                    final boolean sigsOk;
17214                    final String sourcePackageName = bp.getSourcePackageName();
17215                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17216                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17217                    if (sourcePackageName.equals(pkg.packageName)
17218                            && (ksms.shouldCheckUpgradeKeySetLocked(
17219                                    sourcePackageSetting, scanFlags))) {
17220                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17221                    } else {
17222
17223                        // in the event of signing certificate rotation, we need to see if the
17224                        // package's certificate has rotated from the current one, or if it is an
17225                        // older certificate with which the current is ok with sharing permissions
17226                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17227                                        pkg.mSigningDetails,
17228                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17229                            sigsOk = true;
17230                        } else if (pkg.mSigningDetails.checkCapability(
17231                                        sourcePackageSetting.signatures.mSigningDetails,
17232                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17233
17234                            // the scanned package checks out, has signing certificate rotation
17235                            // history, and is newer; bring it over
17236                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17237                            sigsOk = true;
17238                        } else {
17239                            sigsOk = false;
17240                        }
17241                    }
17242                    if (!sigsOk) {
17243                        // If the owning package is the system itself, we log but allow
17244                        // install to proceed; we fail the install on all other permission
17245                        // redefinitions.
17246                        if (!sourcePackageName.equals("android")) {
17247                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17248                                    + pkg.packageName + " attempting to redeclare permission "
17249                                    + perm.info.name + " already owned by " + sourcePackageName);
17250                            res.origPermission = perm.info.name;
17251                            res.origPackage = sourcePackageName;
17252                            return;
17253                        } else {
17254                            Slog.w(TAG, "Package " + pkg.packageName
17255                                    + " attempting to redeclare system permission "
17256                                    + perm.info.name + "; ignoring new declaration");
17257                            pkg.permissions.remove(i);
17258                        }
17259                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17260                        // Prevent apps to change protection level to dangerous from any other
17261                        // type as this would allow a privilege escalation where an app adds a
17262                        // normal/signature permission in other app's group and later redefines
17263                        // it as dangerous leading to the group auto-grant.
17264                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17265                                == PermissionInfo.PROTECTION_DANGEROUS) {
17266                            if (bp != null && !bp.isRuntime()) {
17267                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17268                                        + "non-runtime permission " + perm.info.name
17269                                        + " to runtime; keeping old protection level");
17270                                perm.info.protectionLevel = bp.getProtectionLevel();
17271                            }
17272                        }
17273                    }
17274                }
17275            }
17276        }
17277
17278        if (systemApp) {
17279            if (onExternal) {
17280                // Abort update; system app can't be replaced with app on sdcard
17281                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17282                        "Cannot install updates to system apps on sdcard");
17283                return;
17284            } else if (instantApp) {
17285                // Abort update; system app can't be replaced with an instant app
17286                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17287                        "Cannot update a system app with an instant app");
17288                return;
17289            }
17290        }
17291
17292        if (args.move != null) {
17293            // We did an in-place move, so dex is ready to roll
17294            scanFlags |= SCAN_NO_DEX;
17295            scanFlags |= SCAN_MOVE;
17296
17297            synchronized (mPackages) {
17298                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17299                if (ps == null) {
17300                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17301                            "Missing settings for moved package " + pkgName);
17302                }
17303
17304                // We moved the entire application as-is, so bring over the
17305                // previously derived ABI information.
17306                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17307                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17308            }
17309
17310        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17311            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17312            scanFlags |= SCAN_NO_DEX;
17313
17314            try {
17315                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17316                    args.abiOverride : pkg.cpuAbiOverride);
17317                final boolean extractNativeLibs = !pkg.isLibrary();
17318                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17319            } catch (PackageManagerException pme) {
17320                Slog.e(TAG, "Error deriving application ABI", pme);
17321                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17322                return;
17323            }
17324
17325            // Shared libraries for the package need to be updated.
17326            synchronized (mPackages) {
17327                try {
17328                    updateSharedLibrariesLPr(pkg, null);
17329                } catch (PackageManagerException e) {
17330                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17331                }
17332            }
17333        }
17334
17335        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17336            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17337            return;
17338        }
17339
17340        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17341            String apkPath = null;
17342            synchronized (mPackages) {
17343                // Note that if the attacker managed to skip verify setup, for example by tampering
17344                // with the package settings, upon reboot we will do full apk verification when
17345                // verity is not detected.
17346                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17347                if (ps != null && ps.isPrivileged()) {
17348                    apkPath = pkg.baseCodePath;
17349                }
17350            }
17351
17352            if (apkPath != null) {
17353                final VerityUtils.SetupResult result =
17354                        VerityUtils.generateApkVeritySetupData(apkPath);
17355                if (result.isOk()) {
17356                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17357                    FileDescriptor fd = result.getUnownedFileDescriptor();
17358                    try {
17359                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17360                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17361                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17362                    } catch (InstallerException | IOException | DigestException |
17363                             NoSuchAlgorithmException e) {
17364                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17365                                "Failed to set up verity: " + e);
17366                        return;
17367                    } finally {
17368                        IoUtils.closeQuietly(fd);
17369                    }
17370                } else if (result.isFailed()) {
17371                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17372                    return;
17373                } else {
17374                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17375                    // reboot.
17376                }
17377            }
17378        }
17379
17380        if (!instantApp) {
17381            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17382        } else {
17383            if (DEBUG_DOMAIN_VERIFICATION) {
17384                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17385            }
17386        }
17387
17388        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17389                "installPackageLI")) {
17390            if (replace) {
17391                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17392                    // Static libs have a synthetic package name containing the version
17393                    // and cannot be updated as an update would get a new package name,
17394                    // unless this is the exact same version code which is useful for
17395                    // development.
17396                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17397                    if (existingPkg != null &&
17398                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17399                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17400                                + "static-shared libs cannot be updated");
17401                        return;
17402                    }
17403                }
17404                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17405                        installerPackageName, res, args.installReason);
17406            } else {
17407                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17408                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17409            }
17410        }
17411
17412        // Prepare the application profiles for the new code paths.
17413        // This needs to be done before invoking dexopt so that any install-time profile
17414        // can be used for optimizations.
17415        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17416
17417        // Check whether we need to dexopt the app.
17418        //
17419        // NOTE: it is IMPORTANT to call dexopt:
17420        //   - after doRename which will sync the package data from PackageParser.Package and its
17421        //     corresponding ApplicationInfo.
17422        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17423        //     uid of the application (pkg.applicationInfo.uid).
17424        //     This update happens in place!
17425        //
17426        // We only need to dexopt if the package meets ALL of the following conditions:
17427        //   1) it is not forward locked.
17428        //   2) it is not on on an external ASEC container.
17429        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17430        //   4) it is not debuggable.
17431        //
17432        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17433        // complete, so we skip this step during installation. Instead, we'll take extra time
17434        // the first time the instant app starts. It's preferred to do it this way to provide
17435        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17436        // middle of running an instant app. The default behaviour can be overridden
17437        // via gservices.
17438        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17439                && !forwardLocked
17440                && !pkg.applicationInfo.isExternalAsec()
17441                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17442                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17443                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17444
17445        if (performDexopt) {
17446            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17447            // Do not run PackageDexOptimizer through the local performDexOpt
17448            // method because `pkg` may not be in `mPackages` yet.
17449            //
17450            // Also, don't fail application installs if the dexopt step fails.
17451            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17452                    REASON_INSTALL,
17453                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17454                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17455            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17456                    null /* instructionSets */,
17457                    getOrCreateCompilerPackageStats(pkg),
17458                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17459                    dexoptOptions);
17460            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17461        }
17462
17463        // Notify BackgroundDexOptService that the package has been changed.
17464        // If this is an update of a package which used to fail to compile,
17465        // BackgroundDexOptService will remove it from its blacklist.
17466        // TODO: Layering violation
17467        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17468
17469        synchronized (mPackages) {
17470            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17471            if (ps != null) {
17472                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17473                ps.setUpdateAvailable(false /*updateAvailable*/);
17474            }
17475
17476            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17477            for (int i = 0; i < childCount; i++) {
17478                PackageParser.Package childPkg = pkg.childPackages.get(i);
17479                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17480                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17481                if (childPs != null) {
17482                    childRes.newUsers = childPs.queryInstalledUsers(
17483                            sUserManager.getUserIds(), true);
17484                }
17485            }
17486
17487            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17488                updateSequenceNumberLP(ps, res.newUsers);
17489                updateInstantAppInstallerLocked(pkgName);
17490            }
17491        }
17492    }
17493
17494    private void startIntentFilterVerifications(int userId, boolean replacing,
17495            PackageParser.Package pkg) {
17496        if (mIntentFilterVerifierComponent == null) {
17497            Slog.w(TAG, "No IntentFilter verification will not be done as "
17498                    + "there is no IntentFilterVerifier available!");
17499            return;
17500        }
17501
17502        final int verifierUid = getPackageUid(
17503                mIntentFilterVerifierComponent.getPackageName(),
17504                MATCH_DEBUG_TRIAGED_MISSING,
17505                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17506
17507        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17508        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17509        mHandler.sendMessage(msg);
17510
17511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17512        for (int i = 0; i < childCount; i++) {
17513            PackageParser.Package childPkg = pkg.childPackages.get(i);
17514            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17515            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17516            mHandler.sendMessage(msg);
17517        }
17518    }
17519
17520    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17521            PackageParser.Package pkg) {
17522        int size = pkg.activities.size();
17523        if (size == 0) {
17524            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17525                    "No activity, so no need to verify any IntentFilter!");
17526            return;
17527        }
17528
17529        final boolean hasDomainURLs = hasDomainURLs(pkg);
17530        if (!hasDomainURLs) {
17531            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17532                    "No domain URLs, so no need to verify any IntentFilter!");
17533            return;
17534        }
17535
17536        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17537                + " if any IntentFilter from the " + size
17538                + " Activities needs verification ...");
17539
17540        int count = 0;
17541        final String packageName = pkg.packageName;
17542
17543        synchronized (mPackages) {
17544            // If this is a new install and we see that we've already run verification for this
17545            // package, we have nothing to do: it means the state was restored from backup.
17546            if (!replacing) {
17547                IntentFilterVerificationInfo ivi =
17548                        mSettings.getIntentFilterVerificationLPr(packageName);
17549                if (ivi != null) {
17550                    if (DEBUG_DOMAIN_VERIFICATION) {
17551                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17552                                + ivi.getStatusString());
17553                    }
17554                    return;
17555                }
17556            }
17557
17558            // If any filters need to be verified, then all need to be.
17559            boolean needToVerify = false;
17560            for (PackageParser.Activity a : pkg.activities) {
17561                for (ActivityIntentInfo filter : a.intents) {
17562                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17563                        if (DEBUG_DOMAIN_VERIFICATION) {
17564                            Slog.d(TAG,
17565                                    "Intent filter needs verification, so processing all filters");
17566                        }
17567                        needToVerify = true;
17568                        break;
17569                    }
17570                }
17571            }
17572
17573            if (needToVerify) {
17574                final int verificationId = mIntentFilterVerificationToken++;
17575                for (PackageParser.Activity a : pkg.activities) {
17576                    for (ActivityIntentInfo filter : a.intents) {
17577                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17578                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17579                                    "Verification needed for IntentFilter:" + filter.toString());
17580                            mIntentFilterVerifier.addOneIntentFilterVerification(
17581                                    verifierUid, userId, verificationId, filter, packageName);
17582                            count++;
17583                        }
17584                    }
17585                }
17586            }
17587        }
17588
17589        if (count > 0) {
17590            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17591                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17592                    +  " for userId:" + userId);
17593            mIntentFilterVerifier.startVerifications(userId);
17594        } else {
17595            if (DEBUG_DOMAIN_VERIFICATION) {
17596                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17597            }
17598        }
17599    }
17600
17601    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17602        final ComponentName cn  = filter.activity.getComponentName();
17603        final String packageName = cn.getPackageName();
17604
17605        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17606                packageName);
17607        if (ivi == null) {
17608            return true;
17609        }
17610        int status = ivi.getStatus();
17611        switch (status) {
17612            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17613            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17614                return true;
17615
17616            default:
17617                // Nothing to do
17618                return false;
17619        }
17620    }
17621
17622    private static boolean isMultiArch(ApplicationInfo info) {
17623        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17624    }
17625
17626    private static boolean isExternal(PackageParser.Package pkg) {
17627        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17628    }
17629
17630    private static boolean isExternal(PackageSetting ps) {
17631        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17632    }
17633
17634    private static boolean isSystemApp(PackageParser.Package pkg) {
17635        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17636    }
17637
17638    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17639        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17640    }
17641
17642    private static boolean isOemApp(PackageParser.Package pkg) {
17643        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17644    }
17645
17646    private static boolean isVendorApp(PackageParser.Package pkg) {
17647        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17648    }
17649
17650    private static boolean isProductApp(PackageParser.Package pkg) {
17651        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17652    }
17653
17654    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17655        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17656    }
17657
17658    private static boolean isSystemApp(PackageSetting ps) {
17659        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17660    }
17661
17662    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17663        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17664    }
17665
17666    private int packageFlagsToInstallFlags(PackageSetting ps) {
17667        int installFlags = 0;
17668        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17669            // This existing package was an external ASEC install when we have
17670            // the external flag without a UUID
17671            installFlags |= PackageManager.INSTALL_EXTERNAL;
17672        }
17673        if (ps.isForwardLocked()) {
17674            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17675        }
17676        return installFlags;
17677    }
17678
17679    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17680        if (isExternal(pkg)) {
17681            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17682                return mSettings.getExternalVersion();
17683            } else {
17684                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17685            }
17686        } else {
17687            return mSettings.getInternalVersion();
17688        }
17689    }
17690
17691    private void deleteTempPackageFiles() {
17692        final FilenameFilter filter = new FilenameFilter() {
17693            public boolean accept(File dir, String name) {
17694                return name.startsWith("vmdl") && name.endsWith(".tmp");
17695            }
17696        };
17697        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17698            file.delete();
17699        }
17700    }
17701
17702    @Override
17703    public void deletePackageAsUser(String packageName, int versionCode,
17704            IPackageDeleteObserver observer, int userId, int flags) {
17705        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17706                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17707    }
17708
17709    @Override
17710    public void deletePackageVersioned(VersionedPackage versionedPackage,
17711            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17712        final int callingUid = Binder.getCallingUid();
17713        mContext.enforceCallingOrSelfPermission(
17714                android.Manifest.permission.DELETE_PACKAGES, null);
17715        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17716        Preconditions.checkNotNull(versionedPackage);
17717        Preconditions.checkNotNull(observer);
17718        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17719                PackageManager.VERSION_CODE_HIGHEST,
17720                Long.MAX_VALUE, "versionCode must be >= -1");
17721
17722        final String packageName = versionedPackage.getPackageName();
17723        final long versionCode = versionedPackage.getLongVersionCode();
17724        final String internalPackageName;
17725        synchronized (mPackages) {
17726            // Normalize package name to handle renamed packages and static libs
17727            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17728        }
17729
17730        final int uid = Binder.getCallingUid();
17731        if (!isOrphaned(internalPackageName)
17732                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17733            try {
17734                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17735                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17736                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17737                observer.onUserActionRequired(intent);
17738            } catch (RemoteException re) {
17739            }
17740            return;
17741        }
17742        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17743        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17744        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17745            mContext.enforceCallingOrSelfPermission(
17746                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17747                    "deletePackage for user " + userId);
17748        }
17749
17750        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17751            try {
17752                observer.onPackageDeleted(packageName,
17753                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17754            } catch (RemoteException re) {
17755            }
17756            return;
17757        }
17758
17759        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17760            try {
17761                observer.onPackageDeleted(packageName,
17762                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17763            } catch (RemoteException re) {
17764            }
17765            return;
17766        }
17767
17768        if (DEBUG_REMOVE) {
17769            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17770                    + " deleteAllUsers: " + deleteAllUsers + " version="
17771                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17772                    ? "VERSION_CODE_HIGHEST" : versionCode));
17773        }
17774        // Queue up an async operation since the package deletion may take a little while.
17775        mHandler.post(new Runnable() {
17776            public void run() {
17777                mHandler.removeCallbacks(this);
17778                int returnCode;
17779                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17780                boolean doDeletePackage = true;
17781                if (ps != null) {
17782                    final boolean targetIsInstantApp =
17783                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17784                    doDeletePackage = !targetIsInstantApp
17785                            || canViewInstantApps;
17786                }
17787                if (doDeletePackage) {
17788                    if (!deleteAllUsers) {
17789                        returnCode = deletePackageX(internalPackageName, versionCode,
17790                                userId, deleteFlags);
17791                    } else {
17792                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17793                                internalPackageName, users);
17794                        // If nobody is blocking uninstall, proceed with delete for all users
17795                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17796                            returnCode = deletePackageX(internalPackageName, versionCode,
17797                                    userId, deleteFlags);
17798                        } else {
17799                            // Otherwise uninstall individually for users with blockUninstalls=false
17800                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17801                            for (int userId : users) {
17802                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17803                                    returnCode = deletePackageX(internalPackageName, versionCode,
17804                                            userId, userFlags);
17805                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17806                                        Slog.w(TAG, "Package delete failed for user " + userId
17807                                                + ", returnCode " + returnCode);
17808                                    }
17809                                }
17810                            }
17811                            // The app has only been marked uninstalled for certain users.
17812                            // We still need to report that delete was blocked
17813                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17814                        }
17815                    }
17816                } else {
17817                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17818                }
17819                try {
17820                    observer.onPackageDeleted(packageName, returnCode, null);
17821                } catch (RemoteException e) {
17822                    Log.i(TAG, "Observer no longer exists.");
17823                } //end catch
17824            } //end run
17825        });
17826    }
17827
17828    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17829        if (pkg.staticSharedLibName != null) {
17830            return pkg.manifestPackageName;
17831        }
17832        return pkg.packageName;
17833    }
17834
17835    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17836        // Handle renamed packages
17837        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17838        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17839
17840        // Is this a static library?
17841        LongSparseArray<SharedLibraryEntry> versionedLib =
17842                mStaticLibsByDeclaringPackage.get(packageName);
17843        if (versionedLib == null || versionedLib.size() <= 0) {
17844            return packageName;
17845        }
17846
17847        // Figure out which lib versions the caller can see
17848        LongSparseLongArray versionsCallerCanSee = null;
17849        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17850        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17851                && callingAppId != Process.ROOT_UID) {
17852            versionsCallerCanSee = new LongSparseLongArray();
17853            String libName = versionedLib.valueAt(0).info.getName();
17854            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17855            if (uidPackages != null) {
17856                for (String uidPackage : uidPackages) {
17857                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17858                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17859                    if (libIdx >= 0) {
17860                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17861                        versionsCallerCanSee.append(libVersion, libVersion);
17862                    }
17863                }
17864            }
17865        }
17866
17867        // Caller can see nothing - done
17868        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17869            return packageName;
17870        }
17871
17872        // Find the version the caller can see and the app version code
17873        SharedLibraryEntry highestVersion = null;
17874        final int versionCount = versionedLib.size();
17875        for (int i = 0; i < versionCount; i++) {
17876            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17877            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17878                    libEntry.info.getLongVersion()) < 0) {
17879                continue;
17880            }
17881            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17882            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17883                if (libVersionCode == versionCode) {
17884                    return libEntry.apk;
17885                }
17886            } else if (highestVersion == null) {
17887                highestVersion = libEntry;
17888            } else if (libVersionCode  > highestVersion.info
17889                    .getDeclaringPackage().getLongVersionCode()) {
17890                highestVersion = libEntry;
17891            }
17892        }
17893
17894        if (highestVersion != null) {
17895            return highestVersion.apk;
17896        }
17897
17898        return packageName;
17899    }
17900
17901    boolean isCallerVerifier(int callingUid) {
17902        final int callingUserId = UserHandle.getUserId(callingUid);
17903        return mRequiredVerifierPackage != null &&
17904                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17905    }
17906
17907    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17908        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17909              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17910            return true;
17911        }
17912        final int callingUserId = UserHandle.getUserId(callingUid);
17913        // If the caller installed the pkgName, then allow it to silently uninstall.
17914        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17915            return true;
17916        }
17917
17918        // Allow package verifier to silently uninstall.
17919        if (mRequiredVerifierPackage != null &&
17920                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17921            return true;
17922        }
17923
17924        // Allow package uninstaller to silently uninstall.
17925        if (mRequiredUninstallerPackage != null &&
17926                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17927            return true;
17928        }
17929
17930        // Allow storage manager to silently uninstall.
17931        if (mStorageManagerPackage != null &&
17932                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17933            return true;
17934        }
17935
17936        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17937        // uninstall for device owner provisioning.
17938        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17939                == PERMISSION_GRANTED) {
17940            return true;
17941        }
17942
17943        return false;
17944    }
17945
17946    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17947        int[] result = EMPTY_INT_ARRAY;
17948        for (int userId : userIds) {
17949            if (getBlockUninstallForUser(packageName, userId)) {
17950                result = ArrayUtils.appendInt(result, userId);
17951            }
17952        }
17953        return result;
17954    }
17955
17956    @Override
17957    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17958        final int callingUid = Binder.getCallingUid();
17959        if (getInstantAppPackageName(callingUid) != null
17960                && !isCallerSameApp(packageName, callingUid)) {
17961            return false;
17962        }
17963        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17964    }
17965
17966    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17967        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17968                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17969        try {
17970            if (dpm != null) {
17971                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17972                        /* callingUserOnly =*/ false);
17973                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17974                        : deviceOwnerComponentName.getPackageName();
17975                // Does the package contains the device owner?
17976                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17977                // this check is probably not needed, since DO should be registered as a device
17978                // admin on some user too. (Original bug for this: b/17657954)
17979                if (packageName.equals(deviceOwnerPackageName)) {
17980                    return true;
17981                }
17982                // Does it contain a device admin for any user?
17983                int[] users;
17984                if (userId == UserHandle.USER_ALL) {
17985                    users = sUserManager.getUserIds();
17986                } else {
17987                    users = new int[]{userId};
17988                }
17989                for (int i = 0; i < users.length; ++i) {
17990                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17991                        return true;
17992                    }
17993                }
17994            }
17995        } catch (RemoteException e) {
17996        }
17997        return false;
17998    }
17999
18000    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18001        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18002    }
18003
18004    /**
18005     *  This method is an internal method that could be get invoked either
18006     *  to delete an installed package or to clean up a failed installation.
18007     *  After deleting an installed package, a broadcast is sent to notify any
18008     *  listeners that the package has been removed. For cleaning up a failed
18009     *  installation, the broadcast is not necessary since the package's
18010     *  installation wouldn't have sent the initial broadcast either
18011     *  The key steps in deleting a package are
18012     *  deleting the package information in internal structures like mPackages,
18013     *  deleting the packages base directories through installd
18014     *  updating mSettings to reflect current status
18015     *  persisting settings for later use
18016     *  sending a broadcast if necessary
18017     */
18018    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18019        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18020        final boolean res;
18021
18022        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18023                ? UserHandle.USER_ALL : userId;
18024
18025        if (isPackageDeviceAdmin(packageName, removeUser)) {
18026            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18027            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18028        }
18029
18030        PackageSetting uninstalledPs = null;
18031        PackageParser.Package pkg = null;
18032
18033        // for the uninstall-updates case and restricted profiles, remember the per-
18034        // user handle installed state
18035        int[] allUsers;
18036        synchronized (mPackages) {
18037            uninstalledPs = mSettings.mPackages.get(packageName);
18038            if (uninstalledPs == null) {
18039                Slog.w(TAG, "Not removing non-existent package " + packageName);
18040                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18041            }
18042
18043            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18044                    && uninstalledPs.versionCode != versionCode) {
18045                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18046                        + uninstalledPs.versionCode + " != " + versionCode);
18047                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18048            }
18049
18050            // Static shared libs can be declared by any package, so let us not
18051            // allow removing a package if it provides a lib others depend on.
18052            pkg = mPackages.get(packageName);
18053
18054            allUsers = sUserManager.getUserIds();
18055
18056            if (pkg != null && pkg.staticSharedLibName != null) {
18057                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18058                        pkg.staticSharedLibVersion);
18059                if (libEntry != null) {
18060                    for (int currUserId : allUsers) {
18061                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18062                            continue;
18063                        }
18064                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18065                                libEntry.info, 0, currUserId);
18066                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18067                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18068                                    + " hosting lib " + libEntry.info.getName() + " version "
18069                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18070                                    + " for user " + currUserId);
18071                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18072                        }
18073                    }
18074                }
18075            }
18076
18077            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18078        }
18079
18080        final int freezeUser;
18081        if (isUpdatedSystemApp(uninstalledPs)
18082                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18083            // We're downgrading a system app, which will apply to all users, so
18084            // freeze them all during the downgrade
18085            freezeUser = UserHandle.USER_ALL;
18086        } else {
18087            freezeUser = removeUser;
18088        }
18089
18090        synchronized (mInstallLock) {
18091            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18092            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18093                    deleteFlags, "deletePackageX")) {
18094                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18095                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18096            }
18097            synchronized (mPackages) {
18098                if (res) {
18099                    if (pkg != null) {
18100                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18101                    }
18102                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18103                    updateInstantAppInstallerLocked(packageName);
18104                }
18105            }
18106        }
18107
18108        if (res) {
18109            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18110            info.sendPackageRemovedBroadcasts(killApp);
18111            info.sendSystemPackageUpdatedBroadcasts();
18112            info.sendSystemPackageAppearedBroadcasts();
18113        }
18114        // Force a gc here.
18115        Runtime.getRuntime().gc();
18116        // Delete the resources here after sending the broadcast to let
18117        // other processes clean up before deleting resources.
18118        if (info.args != null) {
18119            synchronized (mInstallLock) {
18120                info.args.doPostDeleteLI(true);
18121            }
18122        }
18123
18124        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18125    }
18126
18127    static class PackageRemovedInfo {
18128        final PackageSender packageSender;
18129        String removedPackage;
18130        String installerPackageName;
18131        int uid = -1;
18132        int removedAppId = -1;
18133        int[] origUsers;
18134        int[] removedUsers = null;
18135        int[] broadcastUsers = null;
18136        int[] instantUserIds = null;
18137        SparseArray<Integer> installReasons;
18138        boolean isRemovedPackageSystemUpdate = false;
18139        boolean isUpdate;
18140        boolean dataRemoved;
18141        boolean removedForAllUsers;
18142        boolean isStaticSharedLib;
18143        // Clean up resources deleted packages.
18144        InstallArgs args = null;
18145        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18146        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18147
18148        PackageRemovedInfo(PackageSender packageSender) {
18149            this.packageSender = packageSender;
18150        }
18151
18152        void sendPackageRemovedBroadcasts(boolean killApp) {
18153            sendPackageRemovedBroadcastInternal(killApp);
18154            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18155            for (int i = 0; i < childCount; i++) {
18156                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18157                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18158            }
18159        }
18160
18161        void sendSystemPackageUpdatedBroadcasts() {
18162            if (isRemovedPackageSystemUpdate) {
18163                sendSystemPackageUpdatedBroadcastsInternal();
18164                final int childCount = (removedChildPackages != null)
18165                        ? removedChildPackages.size() : 0;
18166                for (int i = 0; i < childCount; i++) {
18167                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18168                    if (childInfo.isRemovedPackageSystemUpdate) {
18169                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18170                    }
18171                }
18172            }
18173        }
18174
18175        void sendSystemPackageAppearedBroadcasts() {
18176            final int packageCount = (appearedChildPackages != null)
18177                    ? appearedChildPackages.size() : 0;
18178            for (int i = 0; i < packageCount; i++) {
18179                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18180                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18181                    true /*sendBootCompleted*/, false /*startReceiver*/,
18182                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18183            }
18184        }
18185
18186        private void sendSystemPackageUpdatedBroadcastsInternal() {
18187            Bundle extras = new Bundle(2);
18188            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18189            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18190            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18191                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18192            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18193                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18194            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18195                null, null, 0, removedPackage, null, null, null);
18196            if (installerPackageName != null) {
18197                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18198                        removedPackage, extras, 0 /*flags*/,
18199                        installerPackageName, null, null, null);
18200                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18201                        removedPackage, extras, 0 /*flags*/,
18202                        installerPackageName, null, null, null);
18203            }
18204        }
18205
18206        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18207            // Don't send static shared library removal broadcasts as these
18208            // libs are visible only the the apps that depend on them an one
18209            // cannot remove the library if it has a dependency.
18210            if (isStaticSharedLib) {
18211                return;
18212            }
18213            Bundle extras = new Bundle(2);
18214            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18215            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18216            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18217            if (isUpdate || isRemovedPackageSystemUpdate) {
18218                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18219            }
18220            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18221            if (removedPackage != null) {
18222                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18223                    removedPackage, extras, 0, null /*targetPackage*/, null,
18224                    broadcastUsers, instantUserIds);
18225                if (installerPackageName != null) {
18226                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18227                            removedPackage, extras, 0 /*flags*/,
18228                            installerPackageName, null, broadcastUsers, instantUserIds);
18229                }
18230                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18231                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18232                        removedPackage, extras,
18233                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18234                        null, null, broadcastUsers, instantUserIds);
18235                    packageSender.notifyPackageRemoved(removedPackage);
18236                }
18237            }
18238            if (removedAppId >= 0) {
18239                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18240                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18241                    null, null, broadcastUsers, instantUserIds);
18242            }
18243        }
18244
18245        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18246            removedUsers = userIds;
18247            if (removedUsers == null) {
18248                broadcastUsers = null;
18249                return;
18250            }
18251
18252            broadcastUsers = EMPTY_INT_ARRAY;
18253            instantUserIds = EMPTY_INT_ARRAY;
18254            for (int i = userIds.length - 1; i >= 0; --i) {
18255                final int userId = userIds[i];
18256                if (deletedPackageSetting.getInstantApp(userId)) {
18257                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18258                } else {
18259                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18260                }
18261            }
18262        }
18263    }
18264
18265    /*
18266     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18267     * flag is not set, the data directory is removed as well.
18268     * make sure this flag is set for partially installed apps. If not its meaningless to
18269     * delete a partially installed application.
18270     */
18271    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18272            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18273        String packageName = ps.name;
18274        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18275        // Retrieve object to delete permissions for shared user later on
18276        final PackageParser.Package deletedPkg;
18277        final PackageSetting deletedPs;
18278        // reader
18279        synchronized (mPackages) {
18280            deletedPkg = mPackages.get(packageName);
18281            deletedPs = mSettings.mPackages.get(packageName);
18282            if (outInfo != null) {
18283                outInfo.removedPackage = packageName;
18284                outInfo.installerPackageName = ps.installerPackageName;
18285                outInfo.isStaticSharedLib = deletedPkg != null
18286                        && deletedPkg.staticSharedLibName != null;
18287                outInfo.populateUsers(deletedPs == null ? null
18288                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18289            }
18290        }
18291
18292        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18293
18294        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18295            final PackageParser.Package resolvedPkg;
18296            if (deletedPkg != null) {
18297                resolvedPkg = deletedPkg;
18298            } else {
18299                // We don't have a parsed package when it lives on an ejected
18300                // adopted storage device, so fake something together
18301                resolvedPkg = new PackageParser.Package(ps.name);
18302                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18303            }
18304            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18305                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18306            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18307            if (outInfo != null) {
18308                outInfo.dataRemoved = true;
18309            }
18310            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18311        }
18312
18313        int removedAppId = -1;
18314
18315        // writer
18316        synchronized (mPackages) {
18317            boolean installedStateChanged = false;
18318            if (deletedPs != null) {
18319                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18320                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18321                    clearDefaultBrowserIfNeeded(packageName);
18322                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18323                    removedAppId = mSettings.removePackageLPw(packageName);
18324                    if (outInfo != null) {
18325                        outInfo.removedAppId = removedAppId;
18326                    }
18327                    mPermissionManager.updatePermissions(
18328                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18329                    if (deletedPs.sharedUser != null) {
18330                        // Remove permissions associated with package. Since runtime
18331                        // permissions are per user we have to kill the removed package
18332                        // or packages running under the shared user of the removed
18333                        // package if revoking the permissions requested only by the removed
18334                        // package is successful and this causes a change in gids.
18335                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18336                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18337                                    userId);
18338                            if (userIdToKill == UserHandle.USER_ALL
18339                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18340                                // If gids changed for this user, kill all affected packages.
18341                                mHandler.post(new Runnable() {
18342                                    @Override
18343                                    public void run() {
18344                                        // This has to happen with no lock held.
18345                                        killApplication(deletedPs.name, deletedPs.appId,
18346                                                KILL_APP_REASON_GIDS_CHANGED);
18347                                    }
18348                                });
18349                                break;
18350                            }
18351                        }
18352                    }
18353                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18354                }
18355                // make sure to preserve per-user disabled state if this removal was just
18356                // a downgrade of a system app to the factory package
18357                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18358                    if (DEBUG_REMOVE) {
18359                        Slog.d(TAG, "Propagating install state across downgrade");
18360                    }
18361                    for (int userId : allUserHandles) {
18362                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18363                        if (DEBUG_REMOVE) {
18364                            Slog.d(TAG, "    user " + userId + " => " + installed);
18365                        }
18366                        if (installed != ps.getInstalled(userId)) {
18367                            installedStateChanged = true;
18368                        }
18369                        ps.setInstalled(installed, userId);
18370                    }
18371                }
18372            }
18373            // can downgrade to reader
18374            if (writeSettings) {
18375                // Save settings now
18376                mSettings.writeLPr();
18377            }
18378            if (installedStateChanged) {
18379                mSettings.writeKernelMappingLPr(ps);
18380            }
18381        }
18382        if (removedAppId != -1) {
18383            // A user ID was deleted here. Go through all users and remove it
18384            // from KeyStore.
18385            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18386        }
18387    }
18388
18389    static boolean locationIsPrivileged(String path) {
18390        try {
18391            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18392            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18393            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18394            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18395            return path.startsWith(privilegedAppDir.getCanonicalPath())
18396                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18397                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18398                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18399        } catch (IOException e) {
18400            Slog.e(TAG, "Unable to access code path " + path);
18401        }
18402        return false;
18403    }
18404
18405    static boolean locationIsOem(String path) {
18406        try {
18407            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18408        } catch (IOException e) {
18409            Slog.e(TAG, "Unable to access code path " + path);
18410        }
18411        return false;
18412    }
18413
18414    static boolean locationIsVendor(String path) {
18415        try {
18416            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18417                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18418        } catch (IOException e) {
18419            Slog.e(TAG, "Unable to access code path " + path);
18420        }
18421        return false;
18422    }
18423
18424    static boolean locationIsProduct(String path) {
18425        try {
18426            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18427        } catch (IOException e) {
18428            Slog.e(TAG, "Unable to access code path " + path);
18429        }
18430        return false;
18431    }
18432
18433    /*
18434     * Tries to delete system package.
18435     */
18436    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18437            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18438            boolean writeSettings) {
18439        if (deletedPs.parentPackageName != null) {
18440            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18441            return false;
18442        }
18443
18444        final boolean applyUserRestrictions
18445                = (allUserHandles != null) && (outInfo.origUsers != null);
18446        final PackageSetting disabledPs;
18447        // Confirm if the system package has been updated
18448        // An updated system app can be deleted. This will also have to restore
18449        // the system pkg from system partition
18450        // reader
18451        synchronized (mPackages) {
18452            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18453        }
18454
18455        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18456                + " disabledPs=" + disabledPs);
18457
18458        if (disabledPs == null) {
18459            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18460            return false;
18461        } else if (DEBUG_REMOVE) {
18462            Slog.d(TAG, "Deleting system pkg from data partition");
18463        }
18464
18465        if (DEBUG_REMOVE) {
18466            if (applyUserRestrictions) {
18467                Slog.d(TAG, "Remembering install states:");
18468                for (int userId : allUserHandles) {
18469                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18470                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18471                }
18472            }
18473        }
18474
18475        // Delete the updated package
18476        outInfo.isRemovedPackageSystemUpdate = true;
18477        if (outInfo.removedChildPackages != null) {
18478            final int childCount = (deletedPs.childPackageNames != null)
18479                    ? deletedPs.childPackageNames.size() : 0;
18480            for (int i = 0; i < childCount; i++) {
18481                String childPackageName = deletedPs.childPackageNames.get(i);
18482                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18483                        .contains(childPackageName)) {
18484                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18485                            childPackageName);
18486                    if (childInfo != null) {
18487                        childInfo.isRemovedPackageSystemUpdate = true;
18488                    }
18489                }
18490            }
18491        }
18492
18493        if (disabledPs.versionCode < deletedPs.versionCode) {
18494            // Delete data for downgrades
18495            flags &= ~PackageManager.DELETE_KEEP_DATA;
18496        } else {
18497            // Preserve data by setting flag
18498            flags |= PackageManager.DELETE_KEEP_DATA;
18499        }
18500
18501        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18502                outInfo, writeSettings, disabledPs.pkg);
18503        if (!ret) {
18504            return false;
18505        }
18506
18507        // writer
18508        synchronized (mPackages) {
18509            // NOTE: The system package always needs to be enabled; even if it's for
18510            // a compressed stub. If we don't, installing the system package fails
18511            // during scan [scanning checks the disabled packages]. We will reverse
18512            // this later, after we've "installed" the stub.
18513            // Reinstate the old system package
18514            enableSystemPackageLPw(disabledPs.pkg);
18515            // Remove any native libraries from the upgraded package.
18516            removeNativeBinariesLI(deletedPs);
18517        }
18518
18519        // Install the system package
18520        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18521        try {
18522            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18523                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18524        } catch (PackageManagerException e) {
18525            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18526                    + e.getMessage());
18527            return false;
18528        } finally {
18529            if (disabledPs.pkg.isStub) {
18530                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18531            }
18532        }
18533        return true;
18534    }
18535
18536    /**
18537     * Installs a package that's already on the system partition.
18538     */
18539    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18540            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18541            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18542                    throws PackageManagerException {
18543        @ParseFlags int parseFlags =
18544                mDefParseFlags
18545                | PackageParser.PARSE_MUST_BE_APK
18546                | PackageParser.PARSE_IS_SYSTEM_DIR;
18547        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18548        if (isPrivileged || locationIsPrivileged(codePathString)) {
18549            scanFlags |= SCAN_AS_PRIVILEGED;
18550        }
18551        if (locationIsOem(codePathString)) {
18552            scanFlags |= SCAN_AS_OEM;
18553        }
18554        if (locationIsVendor(codePathString)) {
18555            scanFlags |= SCAN_AS_VENDOR;
18556        }
18557        if (locationIsProduct(codePathString)) {
18558            scanFlags |= SCAN_AS_PRODUCT;
18559        }
18560
18561        final File codePath = new File(codePathString);
18562        final PackageParser.Package pkg =
18563                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18564
18565        try {
18566            // update shared libraries for the newly re-installed system package
18567            updateSharedLibrariesLPr(pkg, null);
18568        } catch (PackageManagerException e) {
18569            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18570        }
18571
18572        prepareAppDataAfterInstallLIF(pkg);
18573
18574        // writer
18575        synchronized (mPackages) {
18576            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18577
18578            // Propagate the permissions state as we do not want to drop on the floor
18579            // runtime permissions. The update permissions method below will take
18580            // care of removing obsolete permissions and grant install permissions.
18581            if (origPermissionState != null) {
18582                ps.getPermissionsState().copyFrom(origPermissionState);
18583            }
18584            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18585                    mPermissionCallback);
18586
18587            final boolean applyUserRestrictions
18588                    = (allUserHandles != null) && (origUserHandles != null);
18589            if (applyUserRestrictions) {
18590                boolean installedStateChanged = false;
18591                if (DEBUG_REMOVE) {
18592                    Slog.d(TAG, "Propagating install state across reinstall");
18593                }
18594                for (int userId : allUserHandles) {
18595                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18596                    if (DEBUG_REMOVE) {
18597                        Slog.d(TAG, "    user " + userId + " => " + installed);
18598                    }
18599                    if (installed != ps.getInstalled(userId)) {
18600                        installedStateChanged = true;
18601                    }
18602                    ps.setInstalled(installed, userId);
18603
18604                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18605                }
18606                // Regardless of writeSettings we need to ensure that this restriction
18607                // state propagation is persisted
18608                mSettings.writeAllUsersPackageRestrictionsLPr();
18609                if (installedStateChanged) {
18610                    mSettings.writeKernelMappingLPr(ps);
18611                }
18612            }
18613            // can downgrade to reader here
18614            if (writeSettings) {
18615                mSettings.writeLPr();
18616            }
18617        }
18618        return pkg;
18619    }
18620
18621    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18622            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18623            PackageRemovedInfo outInfo, boolean writeSettings,
18624            PackageParser.Package replacingPackage) {
18625        synchronized (mPackages) {
18626            if (outInfo != null) {
18627                outInfo.uid = ps.appId;
18628            }
18629
18630            if (outInfo != null && outInfo.removedChildPackages != null) {
18631                final int childCount = (ps.childPackageNames != null)
18632                        ? ps.childPackageNames.size() : 0;
18633                for (int i = 0; i < childCount; i++) {
18634                    String childPackageName = ps.childPackageNames.get(i);
18635                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18636                    if (childPs == null) {
18637                        return false;
18638                    }
18639                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18640                            childPackageName);
18641                    if (childInfo != null) {
18642                        childInfo.uid = childPs.appId;
18643                    }
18644                }
18645            }
18646        }
18647
18648        // Delete package data from internal structures and also remove data if flag is set
18649        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18650
18651        // Delete the child packages data
18652        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18653        for (int i = 0; i < childCount; i++) {
18654            PackageSetting childPs;
18655            synchronized (mPackages) {
18656                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18657            }
18658            if (childPs != null) {
18659                PackageRemovedInfo childOutInfo = (outInfo != null
18660                        && outInfo.removedChildPackages != null)
18661                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18662                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18663                        && (replacingPackage != null
18664                        && !replacingPackage.hasChildPackage(childPs.name))
18665                        ? flags & ~DELETE_KEEP_DATA : flags;
18666                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18667                        deleteFlags, writeSettings);
18668            }
18669        }
18670
18671        // Delete application code and resources only for parent packages
18672        if (ps.parentPackageName == null) {
18673            if (deleteCodeAndResources && (outInfo != null)) {
18674                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18675                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18676                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18677            }
18678        }
18679
18680        return true;
18681    }
18682
18683    @Override
18684    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18685            int userId) {
18686        mContext.enforceCallingOrSelfPermission(
18687                android.Manifest.permission.DELETE_PACKAGES, null);
18688        synchronized (mPackages) {
18689            // Cannot block uninstall of static shared libs as they are
18690            // considered a part of the using app (emulating static linking).
18691            // Also static libs are installed always on internal storage.
18692            PackageParser.Package pkg = mPackages.get(packageName);
18693            if (pkg != null && pkg.staticSharedLibName != null) {
18694                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18695                        + " providing static shared library: " + pkg.staticSharedLibName);
18696                return false;
18697            }
18698            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18699            mSettings.writePackageRestrictionsLPr(userId);
18700        }
18701        return true;
18702    }
18703
18704    @Override
18705    public boolean getBlockUninstallForUser(String packageName, int userId) {
18706        synchronized (mPackages) {
18707            final PackageSetting ps = mSettings.mPackages.get(packageName);
18708            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18709                return false;
18710            }
18711            return mSettings.getBlockUninstallLPr(userId, packageName);
18712        }
18713    }
18714
18715    @Override
18716    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18717        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18718        synchronized (mPackages) {
18719            PackageSetting ps = mSettings.mPackages.get(packageName);
18720            if (ps == null) {
18721                Log.w(TAG, "Package doesn't exist: " + packageName);
18722                return false;
18723            }
18724            if (systemUserApp) {
18725                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18726            } else {
18727                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18728            }
18729            mSettings.writeLPr();
18730        }
18731        return true;
18732    }
18733
18734    /*
18735     * This method handles package deletion in general
18736     */
18737    private boolean deletePackageLIF(String packageName, UserHandle user,
18738            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18739            PackageRemovedInfo outInfo, boolean writeSettings,
18740            PackageParser.Package replacingPackage) {
18741        if (packageName == null) {
18742            Slog.w(TAG, "Attempt to delete null packageName.");
18743            return false;
18744        }
18745
18746        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18747
18748        PackageSetting ps;
18749        synchronized (mPackages) {
18750            ps = mSettings.mPackages.get(packageName);
18751            if (ps == null) {
18752                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18753                return false;
18754            }
18755
18756            if (ps.parentPackageName != null && (!isSystemApp(ps)
18757                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18758                if (DEBUG_REMOVE) {
18759                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18760                            + ((user == null) ? UserHandle.USER_ALL : user));
18761                }
18762                final int removedUserId = (user != null) ? user.getIdentifier()
18763                        : UserHandle.USER_ALL;
18764
18765                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18766                    return false;
18767                }
18768                markPackageUninstalledForUserLPw(ps, user);
18769                scheduleWritePackageRestrictionsLocked(user);
18770                return true;
18771            }
18772        }
18773
18774        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18775        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18776            onSuspendingPackageRemoved(packageName, userId);
18777        }
18778
18779
18780        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18781                && user.getIdentifier() != UserHandle.USER_ALL)) {
18782            // The caller is asking that the package only be deleted for a single
18783            // user.  To do this, we just mark its uninstalled state and delete
18784            // its data. If this is a system app, we only allow this to happen if
18785            // they have set the special DELETE_SYSTEM_APP which requests different
18786            // semantics than normal for uninstalling system apps.
18787            markPackageUninstalledForUserLPw(ps, user);
18788
18789            if (!isSystemApp(ps)) {
18790                // Do not uninstall the APK if an app should be cached
18791                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18792                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18793                    // Other user still have this package installed, so all
18794                    // we need to do is clear this user's data and save that
18795                    // it is uninstalled.
18796                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18797                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18798                        return false;
18799                    }
18800                    scheduleWritePackageRestrictionsLocked(user);
18801                    return true;
18802                } else {
18803                    // We need to set it back to 'installed' so the uninstall
18804                    // broadcasts will be sent correctly.
18805                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18806                    ps.setInstalled(true, user.getIdentifier());
18807                    mSettings.writeKernelMappingLPr(ps);
18808                }
18809            } else {
18810                // This is a system app, so we assume that the
18811                // other users still have this package installed, so all
18812                // we need to do is clear this user's data and save that
18813                // it is uninstalled.
18814                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18815                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18816                    return false;
18817                }
18818                scheduleWritePackageRestrictionsLocked(user);
18819                return true;
18820            }
18821        }
18822
18823        // If we are deleting a composite package for all users, keep track
18824        // of result for each child.
18825        if (ps.childPackageNames != null && outInfo != null) {
18826            synchronized (mPackages) {
18827                final int childCount = ps.childPackageNames.size();
18828                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18829                for (int i = 0; i < childCount; i++) {
18830                    String childPackageName = ps.childPackageNames.get(i);
18831                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18832                    childInfo.removedPackage = childPackageName;
18833                    childInfo.installerPackageName = ps.installerPackageName;
18834                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18835                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18836                    if (childPs != null) {
18837                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18838                    }
18839                }
18840            }
18841        }
18842
18843        boolean ret = false;
18844        if (isSystemApp(ps)) {
18845            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18846            // When an updated system application is deleted we delete the existing resources
18847            // as well and fall back to existing code in system partition
18848            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18849        } else {
18850            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18851            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18852                    outInfo, writeSettings, replacingPackage);
18853        }
18854
18855        // Take a note whether we deleted the package for all users
18856        if (outInfo != null) {
18857            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18858            if (outInfo.removedChildPackages != null) {
18859                synchronized (mPackages) {
18860                    final int childCount = outInfo.removedChildPackages.size();
18861                    for (int i = 0; i < childCount; i++) {
18862                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18863                        if (childInfo != null) {
18864                            childInfo.removedForAllUsers = mPackages.get(
18865                                    childInfo.removedPackage) == null;
18866                        }
18867                    }
18868                }
18869            }
18870            // If we uninstalled an update to a system app there may be some
18871            // child packages that appeared as they are declared in the system
18872            // app but were not declared in the update.
18873            if (isSystemApp(ps)) {
18874                synchronized (mPackages) {
18875                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18876                    final int childCount = (updatedPs.childPackageNames != null)
18877                            ? updatedPs.childPackageNames.size() : 0;
18878                    for (int i = 0; i < childCount; i++) {
18879                        String childPackageName = updatedPs.childPackageNames.get(i);
18880                        if (outInfo.removedChildPackages == null
18881                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18882                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18883                            if (childPs == null) {
18884                                continue;
18885                            }
18886                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18887                            installRes.name = childPackageName;
18888                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18889                            installRes.pkg = mPackages.get(childPackageName);
18890                            installRes.uid = childPs.pkg.applicationInfo.uid;
18891                            if (outInfo.appearedChildPackages == null) {
18892                                outInfo.appearedChildPackages = new ArrayMap<>();
18893                            }
18894                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18895                        }
18896                    }
18897                }
18898            }
18899        }
18900
18901        return ret;
18902    }
18903
18904    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18905        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18906                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18907        for (int nextUserId : userIds) {
18908            if (DEBUG_REMOVE) {
18909                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18910            }
18911            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18912                    false /*installed*/,
18913                    true /*stopped*/,
18914                    true /*notLaunched*/,
18915                    false /*hidden*/,
18916                    false /*suspended*/,
18917                    null, /*suspendingPackage*/
18918                    null, /*dialogMessage*/
18919                    null, /*suspendedAppExtras*/
18920                    null, /*suspendedLauncherExtras*/
18921                    false /*instantApp*/,
18922                    false /*virtualPreload*/,
18923                    null /*lastDisableAppCaller*/,
18924                    null /*enabledComponents*/,
18925                    null /*disabledComponents*/,
18926                    ps.readUserState(nextUserId).domainVerificationStatus,
18927                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18928                    null /*harmfulAppWarning*/);
18929        }
18930        mSettings.writeKernelMappingLPr(ps);
18931    }
18932
18933    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18934            PackageRemovedInfo outInfo) {
18935        final PackageParser.Package pkg;
18936        synchronized (mPackages) {
18937            pkg = mPackages.get(ps.name);
18938        }
18939
18940        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18941                : new int[] {userId};
18942        for (int nextUserId : userIds) {
18943            if (DEBUG_REMOVE) {
18944                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18945                        + nextUserId);
18946            }
18947
18948            destroyAppDataLIF(pkg, userId,
18949                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18950            destroyAppProfilesLIF(pkg, userId);
18951            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18952            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18953            schedulePackageCleaning(ps.name, nextUserId, false);
18954            synchronized (mPackages) {
18955                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18956                    scheduleWritePackageRestrictionsLocked(nextUserId);
18957                }
18958                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18959            }
18960        }
18961
18962        if (outInfo != null) {
18963            outInfo.removedPackage = ps.name;
18964            outInfo.installerPackageName = ps.installerPackageName;
18965            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18966            outInfo.removedAppId = ps.appId;
18967            outInfo.removedUsers = userIds;
18968            outInfo.broadcastUsers = userIds;
18969        }
18970
18971        return true;
18972    }
18973
18974    private final class ClearStorageConnection implements ServiceConnection {
18975        IMediaContainerService mContainerService;
18976
18977        @Override
18978        public void onServiceConnected(ComponentName name, IBinder service) {
18979            synchronized (this) {
18980                mContainerService = IMediaContainerService.Stub
18981                        .asInterface(Binder.allowBlocking(service));
18982                notifyAll();
18983            }
18984        }
18985
18986        @Override
18987        public void onServiceDisconnected(ComponentName name) {
18988        }
18989    }
18990
18991    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18992        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18993
18994        final boolean mounted;
18995        if (Environment.isExternalStorageEmulated()) {
18996            mounted = true;
18997        } else {
18998            final String status = Environment.getExternalStorageState();
18999
19000            mounted = status.equals(Environment.MEDIA_MOUNTED)
19001                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19002        }
19003
19004        if (!mounted) {
19005            return;
19006        }
19007
19008        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19009        int[] users;
19010        if (userId == UserHandle.USER_ALL) {
19011            users = sUserManager.getUserIds();
19012        } else {
19013            users = new int[] { userId };
19014        }
19015        final ClearStorageConnection conn = new ClearStorageConnection();
19016        if (mContext.bindServiceAsUser(
19017                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19018            try {
19019                for (int curUser : users) {
19020                    long timeout = SystemClock.uptimeMillis() + 5000;
19021                    synchronized (conn) {
19022                        long now;
19023                        while (conn.mContainerService == null &&
19024                                (now = SystemClock.uptimeMillis()) < timeout) {
19025                            try {
19026                                conn.wait(timeout - now);
19027                            } catch (InterruptedException e) {
19028                            }
19029                        }
19030                    }
19031                    if (conn.mContainerService == null) {
19032                        return;
19033                    }
19034
19035                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19036                    clearDirectory(conn.mContainerService,
19037                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19038                    if (allData) {
19039                        clearDirectory(conn.mContainerService,
19040                                userEnv.buildExternalStorageAppDataDirs(packageName));
19041                        clearDirectory(conn.mContainerService,
19042                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19043                    }
19044                }
19045            } finally {
19046                mContext.unbindService(conn);
19047            }
19048        }
19049    }
19050
19051    @Override
19052    public void clearApplicationProfileData(String packageName) {
19053        enforceSystemOrRoot("Only the system can clear all profile data");
19054
19055        final PackageParser.Package pkg;
19056        synchronized (mPackages) {
19057            pkg = mPackages.get(packageName);
19058        }
19059
19060        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19061            synchronized (mInstallLock) {
19062                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19063            }
19064        }
19065    }
19066
19067    @Override
19068    public void clearApplicationUserData(final String packageName,
19069            final IPackageDataObserver observer, final int userId) {
19070        mContext.enforceCallingOrSelfPermission(
19071                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19072
19073        final int callingUid = Binder.getCallingUid();
19074        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19075                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19076
19077        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19078        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19079        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19080            throw new SecurityException("Cannot clear data for a protected package: "
19081                    + packageName);
19082        }
19083        // Queue up an async operation since the package deletion may take a little while.
19084        mHandler.post(new Runnable() {
19085            public void run() {
19086                mHandler.removeCallbacks(this);
19087                final boolean succeeded;
19088                if (!filterApp) {
19089                    try (PackageFreezer freezer = freezePackage(packageName,
19090                            "clearApplicationUserData")) {
19091                        synchronized (mInstallLock) {
19092                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19093                        }
19094                        clearExternalStorageDataSync(packageName, userId, true);
19095                        synchronized (mPackages) {
19096                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19097                                    packageName, userId);
19098                        }
19099                    }
19100                    if (succeeded) {
19101                        // invoke DeviceStorageMonitor's update method to clear any notifications
19102                        DeviceStorageMonitorInternal dsm = LocalServices
19103                                .getService(DeviceStorageMonitorInternal.class);
19104                        if (dsm != null) {
19105                            dsm.checkMemory();
19106                        }
19107                    }
19108                } else {
19109                    succeeded = false;
19110                }
19111                if (observer != null) {
19112                    try {
19113                        observer.onRemoveCompleted(packageName, succeeded);
19114                    } catch (RemoteException e) {
19115                        Log.i(TAG, "Observer no longer exists.");
19116                    }
19117                } //end if observer
19118            } //end run
19119        });
19120    }
19121
19122    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19123        if (packageName == null) {
19124            Slog.w(TAG, "Attempt to delete null packageName.");
19125            return false;
19126        }
19127
19128        // Try finding details about the requested package
19129        PackageParser.Package pkg;
19130        synchronized (mPackages) {
19131            pkg = mPackages.get(packageName);
19132            if (pkg == null) {
19133                final PackageSetting ps = mSettings.mPackages.get(packageName);
19134                if (ps != null) {
19135                    pkg = ps.pkg;
19136                }
19137            }
19138
19139            if (pkg == null) {
19140                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19141                return false;
19142            }
19143
19144            PackageSetting ps = (PackageSetting) pkg.mExtras;
19145            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19146        }
19147
19148        clearAppDataLIF(pkg, userId,
19149                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19150
19151        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19152        removeKeystoreDataIfNeeded(userId, appId);
19153
19154        UserManagerInternal umInternal = getUserManagerInternal();
19155        final int flags;
19156        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19157            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19158        } else if (umInternal.isUserRunning(userId)) {
19159            flags = StorageManager.FLAG_STORAGE_DE;
19160        } else {
19161            flags = 0;
19162        }
19163        prepareAppDataContentsLIF(pkg, userId, flags);
19164
19165        return true;
19166    }
19167
19168    /**
19169     * Reverts user permission state changes (permissions and flags) in
19170     * all packages for a given user.
19171     *
19172     * @param userId The device user for which to do a reset.
19173     */
19174    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19175        final int packageCount = mPackages.size();
19176        for (int i = 0; i < packageCount; i++) {
19177            PackageParser.Package pkg = mPackages.valueAt(i);
19178            PackageSetting ps = (PackageSetting) pkg.mExtras;
19179            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19180        }
19181    }
19182
19183    private void resetNetworkPolicies(int userId) {
19184        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19185    }
19186
19187    /**
19188     * Reverts user permission state changes (permissions and flags).
19189     *
19190     * @param ps The package for which to reset.
19191     * @param userId The device user for which to do a reset.
19192     */
19193    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19194            final PackageSetting ps, final int userId) {
19195        if (ps.pkg == null) {
19196            return;
19197        }
19198
19199        // These are flags that can change base on user actions.
19200        final int userSettableMask = FLAG_PERMISSION_USER_SET
19201                | FLAG_PERMISSION_USER_FIXED
19202                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19203                | FLAG_PERMISSION_REVIEW_REQUIRED;
19204
19205        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19206                | FLAG_PERMISSION_POLICY_FIXED;
19207
19208        boolean writeInstallPermissions = false;
19209        boolean writeRuntimePermissions = false;
19210
19211        final int permissionCount = ps.pkg.requestedPermissions.size();
19212        for (int i = 0; i < permissionCount; i++) {
19213            final String permName = ps.pkg.requestedPermissions.get(i);
19214            final BasePermission bp =
19215                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19216            if (bp == null) {
19217                continue;
19218            }
19219
19220            // If shared user we just reset the state to which only this app contributed.
19221            if (ps.sharedUser != null) {
19222                boolean used = false;
19223                final int packageCount = ps.sharedUser.packages.size();
19224                for (int j = 0; j < packageCount; j++) {
19225                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19226                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19227                            && pkg.pkg.requestedPermissions.contains(permName)) {
19228                        used = true;
19229                        break;
19230                    }
19231                }
19232                if (used) {
19233                    continue;
19234                }
19235            }
19236
19237            final PermissionsState permissionsState = ps.getPermissionsState();
19238
19239            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19240
19241            // Always clear the user settable flags.
19242            final boolean hasInstallState =
19243                    permissionsState.getInstallPermissionState(permName) != null;
19244            // If permission review is enabled and this is a legacy app, mark the
19245            // permission as requiring a review as this is the initial state.
19246            int flags = 0;
19247            if (mSettings.mPermissions.mPermissionReviewRequired
19248                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19249                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19250            }
19251            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19252                if (hasInstallState) {
19253                    writeInstallPermissions = true;
19254                } else {
19255                    writeRuntimePermissions = true;
19256                }
19257            }
19258
19259            // Below is only runtime permission handling.
19260            if (!bp.isRuntime()) {
19261                continue;
19262            }
19263
19264            // Never clobber system or policy.
19265            if ((oldFlags & policyOrSystemFlags) != 0) {
19266                continue;
19267            }
19268
19269            // If this permission was granted by default, make sure it is.
19270            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19271                if (permissionsState.grantRuntimePermission(bp, userId)
19272                        != PERMISSION_OPERATION_FAILURE) {
19273                    writeRuntimePermissions = true;
19274                }
19275            // If permission review is enabled the permissions for a legacy apps
19276            // are represented as constantly granted runtime ones, so don't revoke.
19277            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19278                // Otherwise, reset the permission.
19279                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19280                switch (revokeResult) {
19281                    case PERMISSION_OPERATION_SUCCESS:
19282                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19283                        writeRuntimePermissions = true;
19284                        final int appId = ps.appId;
19285                        mHandler.post(new Runnable() {
19286                            @Override
19287                            public void run() {
19288                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19289                            }
19290                        });
19291                    } break;
19292                }
19293            }
19294        }
19295
19296        // Synchronously write as we are taking permissions away.
19297        if (writeRuntimePermissions) {
19298            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19299        }
19300
19301        // Synchronously write as we are taking permissions away.
19302        if (writeInstallPermissions) {
19303            mSettings.writeLPr();
19304        }
19305    }
19306
19307    /**
19308     * Remove entries from the keystore daemon. Will only remove it if the
19309     * {@code appId} is valid.
19310     */
19311    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19312        if (appId < 0) {
19313            return;
19314        }
19315
19316        final KeyStore keyStore = KeyStore.getInstance();
19317        if (keyStore != null) {
19318            if (userId == UserHandle.USER_ALL) {
19319                for (final int individual : sUserManager.getUserIds()) {
19320                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19321                }
19322            } else {
19323                keyStore.clearUid(UserHandle.getUid(userId, appId));
19324            }
19325        } else {
19326            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19327        }
19328    }
19329
19330    @Override
19331    public void deleteApplicationCacheFiles(final String packageName,
19332            final IPackageDataObserver observer) {
19333        final int userId = UserHandle.getCallingUserId();
19334        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19335    }
19336
19337    @Override
19338    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19339            final IPackageDataObserver observer) {
19340        final int callingUid = Binder.getCallingUid();
19341        if (mContext.checkCallingOrSelfPermission(
19342                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19343                != PackageManager.PERMISSION_GRANTED) {
19344            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19345            if (mContext.checkCallingOrSelfPermission(
19346                    android.Manifest.permission.DELETE_CACHE_FILES)
19347                    == PackageManager.PERMISSION_GRANTED) {
19348                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19349                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19350                        ", silently ignoring");
19351                return;
19352            }
19353            mContext.enforceCallingOrSelfPermission(
19354                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19355        }
19356        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19357                /* requireFullPermission= */ true, /* checkShell= */ false,
19358                "delete application cache files");
19359        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19360                android.Manifest.permission.ACCESS_INSTANT_APPS);
19361
19362        final PackageParser.Package pkg;
19363        synchronized (mPackages) {
19364            pkg = mPackages.get(packageName);
19365        }
19366
19367        // Queue up an async operation since the package deletion may take a little while.
19368        mHandler.post(new Runnable() {
19369            public void run() {
19370                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19371                boolean doClearData = true;
19372                if (ps != null) {
19373                    final boolean targetIsInstantApp =
19374                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19375                    doClearData = !targetIsInstantApp
19376                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19377                }
19378                if (doClearData) {
19379                    synchronized (mInstallLock) {
19380                        final int flags = StorageManager.FLAG_STORAGE_DE
19381                                | StorageManager.FLAG_STORAGE_CE;
19382                        // We're only clearing cache files, so we don't care if the
19383                        // app is unfrozen and still able to run
19384                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19385                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19386                    }
19387                    clearExternalStorageDataSync(packageName, userId, false);
19388                }
19389                if (observer != null) {
19390                    try {
19391                        observer.onRemoveCompleted(packageName, true);
19392                    } catch (RemoteException e) {
19393                        Log.i(TAG, "Observer no longer exists.");
19394                    }
19395                }
19396            }
19397        });
19398    }
19399
19400    @Override
19401    public void getPackageSizeInfo(final String packageName, int userHandle,
19402            final IPackageStatsObserver observer) {
19403        throw new UnsupportedOperationException(
19404                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19405    }
19406
19407    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19408        final PackageSetting ps;
19409        synchronized (mPackages) {
19410            ps = mSettings.mPackages.get(packageName);
19411            if (ps == null) {
19412                Slog.w(TAG, "Failed to find settings for " + packageName);
19413                return false;
19414            }
19415        }
19416
19417        final String[] packageNames = { packageName };
19418        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19419        final String[] codePaths = { ps.codePathString };
19420
19421        try {
19422            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19423                    ps.appId, ceDataInodes, codePaths, stats);
19424
19425            // For now, ignore code size of packages on system partition
19426            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19427                stats.codeSize = 0;
19428            }
19429
19430            // External clients expect these to be tracked separately
19431            stats.dataSize -= stats.cacheSize;
19432
19433        } catch (InstallerException e) {
19434            Slog.w(TAG, String.valueOf(e));
19435            return false;
19436        }
19437
19438        return true;
19439    }
19440
19441    private int getUidTargetSdkVersionLockedLPr(int uid) {
19442        Object obj = mSettings.getUserIdLPr(uid);
19443        if (obj instanceof SharedUserSetting) {
19444            final SharedUserSetting sus = (SharedUserSetting) obj;
19445            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19446            final Iterator<PackageSetting> it = sus.packages.iterator();
19447            while (it.hasNext()) {
19448                final PackageSetting ps = it.next();
19449                if (ps.pkg != null) {
19450                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19451                    if (v < vers) vers = v;
19452                }
19453            }
19454            return vers;
19455        } else if (obj instanceof PackageSetting) {
19456            final PackageSetting ps = (PackageSetting) obj;
19457            if (ps.pkg != null) {
19458                return ps.pkg.applicationInfo.targetSdkVersion;
19459            }
19460        }
19461        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19462    }
19463
19464    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19465        final PackageParser.Package p = mPackages.get(packageName);
19466        if (p != null) {
19467            return p.applicationInfo.targetSdkVersion;
19468        }
19469        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19470    }
19471
19472    @Override
19473    public void addPreferredActivity(IntentFilter filter, int match,
19474            ComponentName[] set, ComponentName activity, int userId) {
19475        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19476                "Adding preferred");
19477    }
19478
19479    private void addPreferredActivityInternal(IntentFilter filter, int match,
19480            ComponentName[] set, ComponentName activity, boolean always, int userId,
19481            String opname) {
19482        // writer
19483        int callingUid = Binder.getCallingUid();
19484        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19485                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19486        if (filter.countActions() == 0) {
19487            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19488            return;
19489        }
19490        synchronized (mPackages) {
19491            if (mContext.checkCallingOrSelfPermission(
19492                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19493                    != PackageManager.PERMISSION_GRANTED) {
19494                if (getUidTargetSdkVersionLockedLPr(callingUid)
19495                        < Build.VERSION_CODES.FROYO) {
19496                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19497                            + callingUid);
19498                    return;
19499                }
19500                mContext.enforceCallingOrSelfPermission(
19501                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19502            }
19503
19504            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19505            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19506                    + userId + ":");
19507            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19508            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19509            scheduleWritePackageRestrictionsLocked(userId);
19510            postPreferredActivityChangedBroadcast(userId);
19511        }
19512    }
19513
19514    private void postPreferredActivityChangedBroadcast(int userId) {
19515        mHandler.post(() -> {
19516            final IActivityManager am = ActivityManager.getService();
19517            if (am == null) {
19518                return;
19519            }
19520
19521            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19522            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19523            try {
19524                am.broadcastIntent(null, intent, null, null,
19525                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19526                        null, false, false, userId);
19527            } catch (RemoteException e) {
19528            }
19529        });
19530    }
19531
19532    @Override
19533    public void replacePreferredActivity(IntentFilter filter, int match,
19534            ComponentName[] set, ComponentName activity, int userId) {
19535        if (filter.countActions() != 1) {
19536            throw new IllegalArgumentException(
19537                    "replacePreferredActivity expects filter to have only 1 action.");
19538        }
19539        if (filter.countDataAuthorities() != 0
19540                || filter.countDataPaths() != 0
19541                || filter.countDataSchemes() > 1
19542                || filter.countDataTypes() != 0) {
19543            throw new IllegalArgumentException(
19544                    "replacePreferredActivity expects filter to have no data authorities, " +
19545                    "paths, or types; and at most one scheme.");
19546        }
19547
19548        final int callingUid = Binder.getCallingUid();
19549        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19550                true /* requireFullPermission */, false /* checkShell */,
19551                "replace preferred activity");
19552        synchronized (mPackages) {
19553            if (mContext.checkCallingOrSelfPermission(
19554                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19555                    != PackageManager.PERMISSION_GRANTED) {
19556                if (getUidTargetSdkVersionLockedLPr(callingUid)
19557                        < Build.VERSION_CODES.FROYO) {
19558                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19559                            + Binder.getCallingUid());
19560                    return;
19561                }
19562                mContext.enforceCallingOrSelfPermission(
19563                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19564            }
19565
19566            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19567            if (pir != null) {
19568                // Get all of the existing entries that exactly match this filter.
19569                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19570                if (existing != null && existing.size() == 1) {
19571                    PreferredActivity cur = existing.get(0);
19572                    if (DEBUG_PREFERRED) {
19573                        Slog.i(TAG, "Checking replace of preferred:");
19574                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19575                        if (!cur.mPref.mAlways) {
19576                            Slog.i(TAG, "  -- CUR; not mAlways!");
19577                        } else {
19578                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19579                            Slog.i(TAG, "  -- CUR: mSet="
19580                                    + Arrays.toString(cur.mPref.mSetComponents));
19581                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19582                            Slog.i(TAG, "  -- NEW: mMatch="
19583                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19584                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19585                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19586                        }
19587                    }
19588                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19589                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19590                            && cur.mPref.sameSet(set)) {
19591                        // Setting the preferred activity to what it happens to be already
19592                        if (DEBUG_PREFERRED) {
19593                            Slog.i(TAG, "Replacing with same preferred activity "
19594                                    + cur.mPref.mShortComponent + " for user "
19595                                    + userId + ":");
19596                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19597                        }
19598                        return;
19599                    }
19600                }
19601
19602                if (existing != null) {
19603                    if (DEBUG_PREFERRED) {
19604                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19605                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19606                    }
19607                    for (int i = 0; i < existing.size(); i++) {
19608                        PreferredActivity pa = existing.get(i);
19609                        if (DEBUG_PREFERRED) {
19610                            Slog.i(TAG, "Removing existing preferred activity "
19611                                    + pa.mPref.mComponent + ":");
19612                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19613                        }
19614                        pir.removeFilter(pa);
19615                    }
19616                }
19617            }
19618            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19619                    "Replacing preferred");
19620        }
19621    }
19622
19623    @Override
19624    public void clearPackagePreferredActivities(String packageName) {
19625        final int callingUid = Binder.getCallingUid();
19626        if (getInstantAppPackageName(callingUid) != null) {
19627            return;
19628        }
19629        // writer
19630        synchronized (mPackages) {
19631            PackageParser.Package pkg = mPackages.get(packageName);
19632            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19633                if (mContext.checkCallingOrSelfPermission(
19634                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19635                        != PackageManager.PERMISSION_GRANTED) {
19636                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19637                            < Build.VERSION_CODES.FROYO) {
19638                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19639                                + callingUid);
19640                        return;
19641                    }
19642                    mContext.enforceCallingOrSelfPermission(
19643                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19644                }
19645            }
19646            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19647            if (ps != null
19648                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19649                return;
19650            }
19651            int user = UserHandle.getCallingUserId();
19652            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19653                scheduleWritePackageRestrictionsLocked(user);
19654            }
19655        }
19656    }
19657
19658    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19659    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19660        ArrayList<PreferredActivity> removed = null;
19661        boolean changed = false;
19662        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19663            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19664            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19665            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19666                continue;
19667            }
19668            Iterator<PreferredActivity> it = pir.filterIterator();
19669            while (it.hasNext()) {
19670                PreferredActivity pa = it.next();
19671                // Mark entry for removal only if it matches the package name
19672                // and the entry is of type "always".
19673                if (packageName == null ||
19674                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19675                                && pa.mPref.mAlways)) {
19676                    if (removed == null) {
19677                        removed = new ArrayList<PreferredActivity>();
19678                    }
19679                    removed.add(pa);
19680                }
19681            }
19682            if (removed != null) {
19683                for (int j=0; j<removed.size(); j++) {
19684                    PreferredActivity pa = removed.get(j);
19685                    pir.removeFilter(pa);
19686                }
19687                changed = true;
19688            }
19689        }
19690        if (changed) {
19691            postPreferredActivityChangedBroadcast(userId);
19692        }
19693        return changed;
19694    }
19695
19696    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19697    private void clearIntentFilterVerificationsLPw(int userId) {
19698        final int packageCount = mPackages.size();
19699        for (int i = 0; i < packageCount; i++) {
19700            PackageParser.Package pkg = mPackages.valueAt(i);
19701            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19702        }
19703    }
19704
19705    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19706    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19707        if (userId == UserHandle.USER_ALL) {
19708            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19709                    sUserManager.getUserIds())) {
19710                for (int oneUserId : sUserManager.getUserIds()) {
19711                    scheduleWritePackageRestrictionsLocked(oneUserId);
19712                }
19713            }
19714        } else {
19715            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19716                scheduleWritePackageRestrictionsLocked(userId);
19717            }
19718        }
19719    }
19720
19721    /** Clears state for all users, and touches intent filter verification policy */
19722    void clearDefaultBrowserIfNeeded(String packageName) {
19723        for (int oneUserId : sUserManager.getUserIds()) {
19724            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19725        }
19726    }
19727
19728    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19729        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19730        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19731            if (packageName.equals(defaultBrowserPackageName)) {
19732                setDefaultBrowserPackageName(null, userId);
19733            }
19734        }
19735    }
19736
19737    @Override
19738    public void resetApplicationPreferences(int userId) {
19739        mContext.enforceCallingOrSelfPermission(
19740                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19741        final long identity = Binder.clearCallingIdentity();
19742        // writer
19743        try {
19744            synchronized (mPackages) {
19745                clearPackagePreferredActivitiesLPw(null, userId);
19746                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19747                // TODO: We have to reset the default SMS and Phone. This requires
19748                // significant refactoring to keep all default apps in the package
19749                // manager (cleaner but more work) or have the services provide
19750                // callbacks to the package manager to request a default app reset.
19751                applyFactoryDefaultBrowserLPw(userId);
19752                clearIntentFilterVerificationsLPw(userId);
19753                primeDomainVerificationsLPw(userId);
19754                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19755                scheduleWritePackageRestrictionsLocked(userId);
19756            }
19757            resetNetworkPolicies(userId);
19758        } finally {
19759            Binder.restoreCallingIdentity(identity);
19760        }
19761    }
19762
19763    @Override
19764    public int getPreferredActivities(List<IntentFilter> outFilters,
19765            List<ComponentName> outActivities, String packageName) {
19766        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19767            return 0;
19768        }
19769        int num = 0;
19770        final int userId = UserHandle.getCallingUserId();
19771        // reader
19772        synchronized (mPackages) {
19773            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19774            if (pir != null) {
19775                final Iterator<PreferredActivity> it = pir.filterIterator();
19776                while (it.hasNext()) {
19777                    final PreferredActivity pa = it.next();
19778                    if (packageName == null
19779                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19780                                    && pa.mPref.mAlways)) {
19781                        if (outFilters != null) {
19782                            outFilters.add(new IntentFilter(pa));
19783                        }
19784                        if (outActivities != null) {
19785                            outActivities.add(pa.mPref.mComponent);
19786                        }
19787                    }
19788                }
19789            }
19790        }
19791
19792        return num;
19793    }
19794
19795    @Override
19796    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19797            int userId) {
19798        int callingUid = Binder.getCallingUid();
19799        if (callingUid != Process.SYSTEM_UID) {
19800            throw new SecurityException(
19801                    "addPersistentPreferredActivity can only be run by the system");
19802        }
19803        if (filter.countActions() == 0) {
19804            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19805            return;
19806        }
19807        synchronized (mPackages) {
19808            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19809                    ":");
19810            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19811            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19812                    new PersistentPreferredActivity(filter, activity));
19813            scheduleWritePackageRestrictionsLocked(userId);
19814            postPreferredActivityChangedBroadcast(userId);
19815        }
19816    }
19817
19818    @Override
19819    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19820        int callingUid = Binder.getCallingUid();
19821        if (callingUid != Process.SYSTEM_UID) {
19822            throw new SecurityException(
19823                    "clearPackagePersistentPreferredActivities can only be run by the system");
19824        }
19825        ArrayList<PersistentPreferredActivity> removed = null;
19826        boolean changed = false;
19827        synchronized (mPackages) {
19828            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19829                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19830                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19831                        .valueAt(i);
19832                if (userId != thisUserId) {
19833                    continue;
19834                }
19835                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19836                while (it.hasNext()) {
19837                    PersistentPreferredActivity ppa = it.next();
19838                    // Mark entry for removal only if it matches the package name.
19839                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19840                        if (removed == null) {
19841                            removed = new ArrayList<PersistentPreferredActivity>();
19842                        }
19843                        removed.add(ppa);
19844                    }
19845                }
19846                if (removed != null) {
19847                    for (int j=0; j<removed.size(); j++) {
19848                        PersistentPreferredActivity ppa = removed.get(j);
19849                        ppir.removeFilter(ppa);
19850                    }
19851                    changed = true;
19852                }
19853            }
19854
19855            if (changed) {
19856                scheduleWritePackageRestrictionsLocked(userId);
19857                postPreferredActivityChangedBroadcast(userId);
19858            }
19859        }
19860    }
19861
19862    /**
19863     * Common machinery for picking apart a restored XML blob and passing
19864     * it to a caller-supplied functor to be applied to the running system.
19865     */
19866    private void restoreFromXml(XmlPullParser parser, int userId,
19867            String expectedStartTag, BlobXmlRestorer functor)
19868            throws IOException, XmlPullParserException {
19869        int type;
19870        while ((type = parser.next()) != XmlPullParser.START_TAG
19871                && type != XmlPullParser.END_DOCUMENT) {
19872        }
19873        if (type != XmlPullParser.START_TAG) {
19874            // oops didn't find a start tag?!
19875            if (DEBUG_BACKUP) {
19876                Slog.e(TAG, "Didn't find start tag during restore");
19877            }
19878            return;
19879        }
19880Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19881        // this is supposed to be TAG_PREFERRED_BACKUP
19882        if (!expectedStartTag.equals(parser.getName())) {
19883            if (DEBUG_BACKUP) {
19884                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19885            }
19886            return;
19887        }
19888
19889        // skip interfering stuff, then we're aligned with the backing implementation
19890        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19891Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19892        functor.apply(parser, userId);
19893    }
19894
19895    private interface BlobXmlRestorer {
19896        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19897    }
19898
19899    /**
19900     * Non-Binder method, support for the backup/restore mechanism: write the
19901     * full set of preferred activities in its canonical XML format.  Returns the
19902     * XML output as a byte array, or null if there is none.
19903     */
19904    @Override
19905    public byte[] getPreferredActivityBackup(int userId) {
19906        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19907            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19908        }
19909
19910        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19911        try {
19912            final XmlSerializer serializer = new FastXmlSerializer();
19913            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19914            serializer.startDocument(null, true);
19915            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19916
19917            synchronized (mPackages) {
19918                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19919            }
19920
19921            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19922            serializer.endDocument();
19923            serializer.flush();
19924        } catch (Exception e) {
19925            if (DEBUG_BACKUP) {
19926                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19927            }
19928            return null;
19929        }
19930
19931        return dataStream.toByteArray();
19932    }
19933
19934    @Override
19935    public void restorePreferredActivities(byte[] backup, int userId) {
19936        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19937            throw new SecurityException("Only the system may call restorePreferredActivities()");
19938        }
19939
19940        try {
19941            final XmlPullParser parser = Xml.newPullParser();
19942            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19943            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19944                    new BlobXmlRestorer() {
19945                        @Override
19946                        public void apply(XmlPullParser parser, int userId)
19947                                throws XmlPullParserException, IOException {
19948                            synchronized (mPackages) {
19949                                mSettings.readPreferredActivitiesLPw(parser, userId);
19950                            }
19951                        }
19952                    } );
19953        } catch (Exception e) {
19954            if (DEBUG_BACKUP) {
19955                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19956            }
19957        }
19958    }
19959
19960    /**
19961     * Non-Binder method, support for the backup/restore mechanism: write the
19962     * default browser (etc) settings in its canonical XML format.  Returns the default
19963     * browser XML representation as a byte array, or null if there is none.
19964     */
19965    @Override
19966    public byte[] getDefaultAppsBackup(int userId) {
19967        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19968            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19969        }
19970
19971        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19972        try {
19973            final XmlSerializer serializer = new FastXmlSerializer();
19974            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19975            serializer.startDocument(null, true);
19976            serializer.startTag(null, TAG_DEFAULT_APPS);
19977
19978            synchronized (mPackages) {
19979                mSettings.writeDefaultAppsLPr(serializer, userId);
19980            }
19981
19982            serializer.endTag(null, TAG_DEFAULT_APPS);
19983            serializer.endDocument();
19984            serializer.flush();
19985        } catch (Exception e) {
19986            if (DEBUG_BACKUP) {
19987                Slog.e(TAG, "Unable to write default apps for backup", e);
19988            }
19989            return null;
19990        }
19991
19992        return dataStream.toByteArray();
19993    }
19994
19995    @Override
19996    public void restoreDefaultApps(byte[] backup, int userId) {
19997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19998            throw new SecurityException("Only the system may call restoreDefaultApps()");
19999        }
20000
20001        try {
20002            final XmlPullParser parser = Xml.newPullParser();
20003            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20004            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20005                    new BlobXmlRestorer() {
20006                        @Override
20007                        public void apply(XmlPullParser parser, int userId)
20008                                throws XmlPullParserException, IOException {
20009                            synchronized (mPackages) {
20010                                mSettings.readDefaultAppsLPw(parser, userId);
20011                            }
20012                        }
20013                    } );
20014        } catch (Exception e) {
20015            if (DEBUG_BACKUP) {
20016                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20017            }
20018        }
20019    }
20020
20021    @Override
20022    public byte[] getIntentFilterVerificationBackup(int userId) {
20023        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20024            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20025        }
20026
20027        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20028        try {
20029            final XmlSerializer serializer = new FastXmlSerializer();
20030            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20031            serializer.startDocument(null, true);
20032            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20033
20034            synchronized (mPackages) {
20035                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20036            }
20037
20038            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20039            serializer.endDocument();
20040            serializer.flush();
20041        } catch (Exception e) {
20042            if (DEBUG_BACKUP) {
20043                Slog.e(TAG, "Unable to write default apps for backup", e);
20044            }
20045            return null;
20046        }
20047
20048        return dataStream.toByteArray();
20049    }
20050
20051    @Override
20052    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20053        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20054            throw new SecurityException("Only the system may call restorePreferredActivities()");
20055        }
20056
20057        try {
20058            final XmlPullParser parser = Xml.newPullParser();
20059            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20060            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20061                    new BlobXmlRestorer() {
20062                        @Override
20063                        public void apply(XmlPullParser parser, int userId)
20064                                throws XmlPullParserException, IOException {
20065                            synchronized (mPackages) {
20066                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20067                                mSettings.writeLPr();
20068                            }
20069                        }
20070                    } );
20071        } catch (Exception e) {
20072            if (DEBUG_BACKUP) {
20073                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20074            }
20075        }
20076    }
20077
20078    @Override
20079    public byte[] getPermissionGrantBackup(int userId) {
20080        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20081            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20082        }
20083
20084        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20085        try {
20086            final XmlSerializer serializer = new FastXmlSerializer();
20087            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20088            serializer.startDocument(null, true);
20089            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20090
20091            synchronized (mPackages) {
20092                serializeRuntimePermissionGrantsLPr(serializer, userId);
20093            }
20094
20095            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20096            serializer.endDocument();
20097            serializer.flush();
20098        } catch (Exception e) {
20099            if (DEBUG_BACKUP) {
20100                Slog.e(TAG, "Unable to write default apps for backup", e);
20101            }
20102            return null;
20103        }
20104
20105        return dataStream.toByteArray();
20106    }
20107
20108    @Override
20109    public void restorePermissionGrants(byte[] backup, int userId) {
20110        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20111            throw new SecurityException("Only the system may call restorePermissionGrants()");
20112        }
20113
20114        try {
20115            final XmlPullParser parser = Xml.newPullParser();
20116            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20117            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20118                    new BlobXmlRestorer() {
20119                        @Override
20120                        public void apply(XmlPullParser parser, int userId)
20121                                throws XmlPullParserException, IOException {
20122                            synchronized (mPackages) {
20123                                processRestoredPermissionGrantsLPr(parser, userId);
20124                            }
20125                        }
20126                    } );
20127        } catch (Exception e) {
20128            if (DEBUG_BACKUP) {
20129                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20130            }
20131        }
20132    }
20133
20134    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20135            throws IOException {
20136        serializer.startTag(null, TAG_ALL_GRANTS);
20137
20138        final int N = mSettings.mPackages.size();
20139        for (int i = 0; i < N; i++) {
20140            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20141            boolean pkgGrantsKnown = false;
20142
20143            PermissionsState packagePerms = ps.getPermissionsState();
20144
20145            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20146                final int grantFlags = state.getFlags();
20147                // only look at grants that are not system/policy fixed
20148                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20149                    final boolean isGranted = state.isGranted();
20150                    // And only back up the user-twiddled state bits
20151                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20152                        final String packageName = mSettings.mPackages.keyAt(i);
20153                        if (!pkgGrantsKnown) {
20154                            serializer.startTag(null, TAG_GRANT);
20155                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20156                            pkgGrantsKnown = true;
20157                        }
20158
20159                        final boolean userSet =
20160                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20161                        final boolean userFixed =
20162                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20163                        final boolean revoke =
20164                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20165
20166                        serializer.startTag(null, TAG_PERMISSION);
20167                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20168                        if (isGranted) {
20169                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20170                        }
20171                        if (userSet) {
20172                            serializer.attribute(null, ATTR_USER_SET, "true");
20173                        }
20174                        if (userFixed) {
20175                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20176                        }
20177                        if (revoke) {
20178                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20179                        }
20180                        serializer.endTag(null, TAG_PERMISSION);
20181                    }
20182                }
20183            }
20184
20185            if (pkgGrantsKnown) {
20186                serializer.endTag(null, TAG_GRANT);
20187            }
20188        }
20189
20190        serializer.endTag(null, TAG_ALL_GRANTS);
20191    }
20192
20193    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20194            throws XmlPullParserException, IOException {
20195        String pkgName = null;
20196        int outerDepth = parser.getDepth();
20197        int type;
20198        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20199                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20200            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20201                continue;
20202            }
20203
20204            final String tagName = parser.getName();
20205            if (tagName.equals(TAG_GRANT)) {
20206                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20207                if (DEBUG_BACKUP) {
20208                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20209                }
20210            } else if (tagName.equals(TAG_PERMISSION)) {
20211
20212                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20213                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20214
20215                int newFlagSet = 0;
20216                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20217                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20218                }
20219                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20220                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20221                }
20222                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20223                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20224                }
20225                if (DEBUG_BACKUP) {
20226                    Slog.v(TAG, "  + Restoring grant:"
20227                            + " pkg=" + pkgName
20228                            + " perm=" + permName
20229                            + " granted=" + isGranted
20230                            + " bits=0x" + Integer.toHexString(newFlagSet));
20231                }
20232                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20233                if (ps != null) {
20234                    // Already installed so we apply the grant immediately
20235                    if (DEBUG_BACKUP) {
20236                        Slog.v(TAG, "        + already installed; applying");
20237                    }
20238                    PermissionsState perms = ps.getPermissionsState();
20239                    BasePermission bp =
20240                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20241                    if (bp != null) {
20242                        if (isGranted) {
20243                            perms.grantRuntimePermission(bp, userId);
20244                        }
20245                        if (newFlagSet != 0) {
20246                            perms.updatePermissionFlags(
20247                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20248                        }
20249                    }
20250                } else {
20251                    // Need to wait for post-restore install to apply the grant
20252                    if (DEBUG_BACKUP) {
20253                        Slog.v(TAG, "        - not yet installed; saving for later");
20254                    }
20255                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20256                            isGranted, newFlagSet, userId);
20257                }
20258            } else {
20259                PackageManagerService.reportSettingsProblem(Log.WARN,
20260                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20261                XmlUtils.skipCurrentTag(parser);
20262            }
20263        }
20264
20265        scheduleWriteSettingsLocked();
20266        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20267    }
20268
20269    @Override
20270    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20271            int sourceUserId, int targetUserId, int flags) {
20272        mContext.enforceCallingOrSelfPermission(
20273                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20274        int callingUid = Binder.getCallingUid();
20275        enforceOwnerRights(ownerPackage, callingUid);
20276        PackageManagerServiceUtils.enforceShellRestriction(
20277                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20278        if (intentFilter.countActions() == 0) {
20279            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20280            return;
20281        }
20282        synchronized (mPackages) {
20283            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20284                    ownerPackage, targetUserId, flags);
20285            CrossProfileIntentResolver resolver =
20286                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20287            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20288            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20289            if (existing != null) {
20290                int size = existing.size();
20291                for (int i = 0; i < size; i++) {
20292                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20293                        return;
20294                    }
20295                }
20296            }
20297            resolver.addFilter(newFilter);
20298            scheduleWritePackageRestrictionsLocked(sourceUserId);
20299        }
20300    }
20301
20302    @Override
20303    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20304        mContext.enforceCallingOrSelfPermission(
20305                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20306        final int callingUid = Binder.getCallingUid();
20307        enforceOwnerRights(ownerPackage, callingUid);
20308        PackageManagerServiceUtils.enforceShellRestriction(
20309                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20310        synchronized (mPackages) {
20311            CrossProfileIntentResolver resolver =
20312                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20313            ArraySet<CrossProfileIntentFilter> set =
20314                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20315            for (CrossProfileIntentFilter filter : set) {
20316                if (filter.getOwnerPackage().equals(ownerPackage)) {
20317                    resolver.removeFilter(filter);
20318                }
20319            }
20320            scheduleWritePackageRestrictionsLocked(sourceUserId);
20321        }
20322    }
20323
20324    // Enforcing that callingUid is owning pkg on userId
20325    private void enforceOwnerRights(String pkg, int callingUid) {
20326        // The system owns everything.
20327        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20328            return;
20329        }
20330        final int callingUserId = UserHandle.getUserId(callingUid);
20331        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20332        if (pi == null) {
20333            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20334                    + callingUserId);
20335        }
20336        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20337            throw new SecurityException("Calling uid " + callingUid
20338                    + " does not own package " + pkg);
20339        }
20340    }
20341
20342    @Override
20343    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20344        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20345            return null;
20346        }
20347        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20348    }
20349
20350    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20351        UserManagerService ums = UserManagerService.getInstance();
20352        if (ums != null) {
20353            final UserInfo parent = ums.getProfileParent(userId);
20354            final int launcherUid = (parent != null) ? parent.id : userId;
20355            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20356            if (launcherComponent != null) {
20357                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20358                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20359                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20360                        .setPackage(launcherComponent.getPackageName());
20361                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20362            }
20363        }
20364    }
20365
20366    /**
20367     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20368     * then reports the most likely home activity or null if there are more than one.
20369     */
20370    private ComponentName getDefaultHomeActivity(int userId) {
20371        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20372        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20373        if (cn != null) {
20374            return cn;
20375        }
20376
20377        // Find the launcher with the highest priority and return that component if there are no
20378        // other home activity with the same priority.
20379        int lastPriority = Integer.MIN_VALUE;
20380        ComponentName lastComponent = null;
20381        final int size = allHomeCandidates.size();
20382        for (int i = 0; i < size; i++) {
20383            final ResolveInfo ri = allHomeCandidates.get(i);
20384            if (ri.priority > lastPriority) {
20385                lastComponent = ri.activityInfo.getComponentName();
20386                lastPriority = ri.priority;
20387            } else if (ri.priority == lastPriority) {
20388                // Two components found with same priority.
20389                lastComponent = null;
20390            }
20391        }
20392        return lastComponent;
20393    }
20394
20395    private Intent getHomeIntent() {
20396        Intent intent = new Intent(Intent.ACTION_MAIN);
20397        intent.addCategory(Intent.CATEGORY_HOME);
20398        intent.addCategory(Intent.CATEGORY_DEFAULT);
20399        return intent;
20400    }
20401
20402    private IntentFilter getHomeFilter() {
20403        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20404        filter.addCategory(Intent.CATEGORY_HOME);
20405        filter.addCategory(Intent.CATEGORY_DEFAULT);
20406        return filter;
20407    }
20408
20409    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20410            int userId) {
20411        Intent intent  = getHomeIntent();
20412        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20413                PackageManager.GET_META_DATA, userId);
20414        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20415                true, false, false, userId);
20416
20417        allHomeCandidates.clear();
20418        if (list != null) {
20419            for (ResolveInfo ri : list) {
20420                allHomeCandidates.add(ri);
20421            }
20422        }
20423        return (preferred == null || preferred.activityInfo == null)
20424                ? null
20425                : new ComponentName(preferred.activityInfo.packageName,
20426                        preferred.activityInfo.name);
20427    }
20428
20429    @Override
20430    public void setHomeActivity(ComponentName comp, int userId) {
20431        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20432            return;
20433        }
20434        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20435        getHomeActivitiesAsUser(homeActivities, userId);
20436
20437        boolean found = false;
20438
20439        final int size = homeActivities.size();
20440        final ComponentName[] set = new ComponentName[size];
20441        for (int i = 0; i < size; i++) {
20442            final ResolveInfo candidate = homeActivities.get(i);
20443            final ActivityInfo info = candidate.activityInfo;
20444            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20445            set[i] = activityName;
20446            if (!found && activityName.equals(comp)) {
20447                found = true;
20448            }
20449        }
20450        if (!found) {
20451            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20452                    + userId);
20453        }
20454        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20455                set, comp, userId);
20456    }
20457
20458    private @Nullable String getSetupWizardPackageName() {
20459        final Intent intent = new Intent(Intent.ACTION_MAIN);
20460        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20461
20462        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20463                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20464                        | MATCH_DISABLED_COMPONENTS,
20465                UserHandle.myUserId());
20466        if (matches.size() == 1) {
20467            return matches.get(0).getComponentInfo().packageName;
20468        } else {
20469            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20470                    + ": matches=" + matches);
20471            return null;
20472        }
20473    }
20474
20475    private @Nullable String getStorageManagerPackageName() {
20476        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20477
20478        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20479                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20480                        | MATCH_DISABLED_COMPONENTS,
20481                UserHandle.myUserId());
20482        if (matches.size() == 1) {
20483            return matches.get(0).getComponentInfo().packageName;
20484        } else {
20485            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20486                    + matches.size() + ": matches=" + matches);
20487            return null;
20488        }
20489    }
20490
20491    @Override
20492    public String getSystemTextClassifierPackageName() {
20493        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20494    }
20495
20496    @Override
20497    public void setApplicationEnabledSetting(String appPackageName,
20498            int newState, int flags, int userId, String callingPackage) {
20499        if (!sUserManager.exists(userId)) return;
20500        if (callingPackage == null) {
20501            callingPackage = Integer.toString(Binder.getCallingUid());
20502        }
20503        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20504    }
20505
20506    @Override
20507    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20508        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20509        synchronized (mPackages) {
20510            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20511            if (pkgSetting != null) {
20512                pkgSetting.setUpdateAvailable(updateAvailable);
20513            }
20514        }
20515    }
20516
20517    @Override
20518    public void setComponentEnabledSetting(ComponentName componentName,
20519            int newState, int flags, int userId) {
20520        if (!sUserManager.exists(userId)) return;
20521        setEnabledSetting(componentName.getPackageName(),
20522                componentName.getClassName(), newState, flags, userId, null);
20523    }
20524
20525    private void setEnabledSetting(final String packageName, String className, int newState,
20526            final int flags, int userId, String callingPackage) {
20527        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20528              || newState == COMPONENT_ENABLED_STATE_ENABLED
20529              || newState == COMPONENT_ENABLED_STATE_DISABLED
20530              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20531              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20532            throw new IllegalArgumentException("Invalid new component state: "
20533                    + newState);
20534        }
20535        PackageSetting pkgSetting;
20536        final int callingUid = Binder.getCallingUid();
20537        final int permission;
20538        if (callingUid == Process.SYSTEM_UID) {
20539            permission = PackageManager.PERMISSION_GRANTED;
20540        } else {
20541            permission = mContext.checkCallingOrSelfPermission(
20542                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20543        }
20544        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20545                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20546        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20547        boolean sendNow = false;
20548        boolean isApp = (className == null);
20549        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20550        String componentName = isApp ? packageName : className;
20551        int packageUid = -1;
20552        ArrayList<String> components;
20553
20554        // reader
20555        synchronized (mPackages) {
20556            pkgSetting = mSettings.mPackages.get(packageName);
20557            if (pkgSetting == null) {
20558                if (!isCallerInstantApp) {
20559                    if (className == null) {
20560                        throw new IllegalArgumentException("Unknown package: " + packageName);
20561                    }
20562                    throw new IllegalArgumentException(
20563                            "Unknown component: " + packageName + "/" + className);
20564                } else {
20565                    // throw SecurityException to prevent leaking package information
20566                    throw new SecurityException(
20567                            "Attempt to change component state; "
20568                            + "pid=" + Binder.getCallingPid()
20569                            + ", uid=" + callingUid
20570                            + (className == null
20571                                    ? ", package=" + packageName
20572                                    : ", component=" + packageName + "/" + className));
20573                }
20574            }
20575        }
20576
20577        // Limit who can change which apps
20578        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20579            // Don't allow apps that don't have permission to modify other apps
20580            if (!allowedByPermission
20581                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20582                throw new SecurityException(
20583                        "Attempt to change component state; "
20584                        + "pid=" + Binder.getCallingPid()
20585                        + ", uid=" + callingUid
20586                        + (className == null
20587                                ? ", package=" + packageName
20588                                : ", component=" + packageName + "/" + className));
20589            }
20590            // Don't allow changing protected packages.
20591            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20592                throw new SecurityException("Cannot disable a protected package: " + packageName);
20593            }
20594        }
20595
20596        synchronized (mPackages) {
20597            if (callingUid == Process.SHELL_UID
20598                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20599                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20600                // unless it is a test package.
20601                int oldState = pkgSetting.getEnabled(userId);
20602                if (className == null
20603                        &&
20604                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20605                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20606                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20607                        &&
20608                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20609                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20610                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20611                    // ok
20612                } else {
20613                    throw new SecurityException(
20614                            "Shell cannot change component state for " + packageName + "/"
20615                                    + className + " to " + newState);
20616                }
20617            }
20618        }
20619        if (className == null) {
20620            // We're dealing with an application/package level state change
20621            synchronized (mPackages) {
20622                if (pkgSetting.getEnabled(userId) == newState) {
20623                    // Nothing to do
20624                    return;
20625                }
20626            }
20627            // If we're enabling a system stub, there's a little more work to do.
20628            // Prior to enabling the package, we need to decompress the APK(s) to the
20629            // data partition and then replace the version on the system partition.
20630            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20631            final boolean isSystemStub = deletedPkg.isStub
20632                    && deletedPkg.isSystem();
20633            if (isSystemStub
20634                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20635                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20636                final File codePath = decompressPackage(deletedPkg);
20637                if (codePath == null) {
20638                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20639                    return;
20640                }
20641                // TODO remove direct parsing of the package object during internal cleanup
20642                // of scan package
20643                // We need to call parse directly here for no other reason than we need
20644                // the new package in order to disable the old one [we use the information
20645                // for some internal optimization to optionally create a new package setting
20646                // object on replace]. However, we can't get the package from the scan
20647                // because the scan modifies live structures and we need to remove the
20648                // old [system] package from the system before a scan can be attempted.
20649                // Once scan is indempotent we can remove this parse and use the package
20650                // object we scanned, prior to adding it to package settings.
20651                final PackageParser pp = new PackageParser();
20652                pp.setSeparateProcesses(mSeparateProcesses);
20653                pp.setDisplayMetrics(mMetrics);
20654                pp.setCallback(mPackageParserCallback);
20655                final PackageParser.Package tmpPkg;
20656                try {
20657                    final @ParseFlags int parseFlags = mDefParseFlags
20658                            | PackageParser.PARSE_MUST_BE_APK
20659                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20660                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20661                } catch (PackageParserException e) {
20662                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20663                    return;
20664                }
20665                synchronized (mInstallLock) {
20666                    // Disable the stub and remove any package entries
20667                    removePackageLI(deletedPkg, true);
20668                    synchronized (mPackages) {
20669                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20670                    }
20671                    final PackageParser.Package pkg;
20672                    try (PackageFreezer freezer =
20673                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20674                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20675                                | PackageParser.PARSE_ENFORCE_CODE;
20676                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20677                                0 /*currentTime*/, null /*user*/);
20678                        prepareAppDataAfterInstallLIF(pkg);
20679                        synchronized (mPackages) {
20680                            try {
20681                                updateSharedLibrariesLPr(pkg, null);
20682                            } catch (PackageManagerException e) {
20683                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20684                            }
20685                            mPermissionManager.updatePermissions(
20686                                    pkg.packageName, pkg, true, mPackages.values(),
20687                                    mPermissionCallback);
20688                            mSettings.writeLPr();
20689                        }
20690                    } catch (PackageManagerException e) {
20691                        // Whoops! Something went wrong; try to roll back to the stub
20692                        Slog.w(TAG, "Failed to install compressed system package:"
20693                                + pkgSetting.name, e);
20694                        // Remove the failed install
20695                        removeCodePathLI(codePath);
20696
20697                        // Install the system package
20698                        try (PackageFreezer freezer =
20699                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20700                            synchronized (mPackages) {
20701                                // NOTE: The system package always needs to be enabled; even
20702                                // if it's for a compressed stub. If we don't, installing the
20703                                // system package fails during scan [scanning checks the disabled
20704                                // packages]. We will reverse this later, after we've "installed"
20705                                // the stub.
20706                                // This leaves us in a fragile state; the stub should never be
20707                                // enabled, so, cross your fingers and hope nothing goes wrong
20708                                // until we can disable the package later.
20709                                enableSystemPackageLPw(deletedPkg);
20710                            }
20711                            installPackageFromSystemLIF(deletedPkg.codePath,
20712                                    false /*isPrivileged*/, null /*allUserHandles*/,
20713                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20714                                    true /*writeSettings*/);
20715                        } catch (PackageManagerException pme) {
20716                            Slog.w(TAG, "Failed to restore system package:"
20717                                    + deletedPkg.packageName, pme);
20718                        } finally {
20719                            synchronized (mPackages) {
20720                                mSettings.disableSystemPackageLPw(
20721                                        deletedPkg.packageName, true /*replaced*/);
20722                                mSettings.writeLPr();
20723                            }
20724                        }
20725                        return;
20726                    }
20727                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20728                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20729                    mDexManager.notifyPackageUpdated(pkg.packageName,
20730                            pkg.baseCodePath, pkg.splitCodePaths);
20731                }
20732            }
20733            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20734                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20735                // Don't care about who enables an app.
20736                callingPackage = null;
20737            }
20738            synchronized (mPackages) {
20739                pkgSetting.setEnabled(newState, userId, callingPackage);
20740            }
20741        } else {
20742            synchronized (mPackages) {
20743                // We're dealing with a component level state change
20744                // First, verify that this is a valid class name.
20745                PackageParser.Package pkg = pkgSetting.pkg;
20746                if (pkg == null || !pkg.hasComponentClassName(className)) {
20747                    if (pkg != null &&
20748                            pkg.applicationInfo.targetSdkVersion >=
20749                                    Build.VERSION_CODES.JELLY_BEAN) {
20750                        throw new IllegalArgumentException("Component class " + className
20751                                + " does not exist in " + packageName);
20752                    } else {
20753                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20754                                + className + " does not exist in " + packageName);
20755                    }
20756                }
20757                switch (newState) {
20758                    case COMPONENT_ENABLED_STATE_ENABLED:
20759                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20760                            return;
20761                        }
20762                        break;
20763                    case COMPONENT_ENABLED_STATE_DISABLED:
20764                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20765                            return;
20766                        }
20767                        break;
20768                    case COMPONENT_ENABLED_STATE_DEFAULT:
20769                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20770                            return;
20771                        }
20772                        break;
20773                    default:
20774                        Slog.e(TAG, "Invalid new component state: " + newState);
20775                        return;
20776                }
20777            }
20778        }
20779        synchronized (mPackages) {
20780            scheduleWritePackageRestrictionsLocked(userId);
20781            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20782            final long callingId = Binder.clearCallingIdentity();
20783            try {
20784                updateInstantAppInstallerLocked(packageName);
20785            } finally {
20786                Binder.restoreCallingIdentity(callingId);
20787            }
20788            components = mPendingBroadcasts.get(userId, packageName);
20789            final boolean newPackage = components == null;
20790            if (newPackage) {
20791                components = new ArrayList<String>();
20792            }
20793            if (!components.contains(componentName)) {
20794                components.add(componentName);
20795            }
20796            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20797                sendNow = true;
20798                // Purge entry from pending broadcast list if another one exists already
20799                // since we are sending one right away.
20800                mPendingBroadcasts.remove(userId, packageName);
20801            } else {
20802                if (newPackage) {
20803                    mPendingBroadcasts.put(userId, packageName, components);
20804                }
20805                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20806                    // Schedule a message
20807                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20808                }
20809            }
20810        }
20811
20812        long callingId = Binder.clearCallingIdentity();
20813        try {
20814            if (sendNow) {
20815                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20816                sendPackageChangedBroadcast(packageName,
20817                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20818            }
20819        } finally {
20820            Binder.restoreCallingIdentity(callingId);
20821        }
20822    }
20823
20824    @Override
20825    public void flushPackageRestrictionsAsUser(int userId) {
20826        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20827            return;
20828        }
20829        if (!sUserManager.exists(userId)) {
20830            return;
20831        }
20832        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20833                false /* checkShell */, "flushPackageRestrictions");
20834        synchronized (mPackages) {
20835            mSettings.writePackageRestrictionsLPr(userId);
20836            mDirtyUsers.remove(userId);
20837            if (mDirtyUsers.isEmpty()) {
20838                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20839            }
20840        }
20841    }
20842
20843    private void sendPackageChangedBroadcast(String packageName,
20844            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20845        if (DEBUG_INSTALL)
20846            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20847                    + componentNames);
20848        Bundle extras = new Bundle(4);
20849        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20850        String nameList[] = new String[componentNames.size()];
20851        componentNames.toArray(nameList);
20852        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20853        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20854        extras.putInt(Intent.EXTRA_UID, packageUid);
20855        // If this is not reporting a change of the overall package, then only send it
20856        // to registered receivers.  We don't want to launch a swath of apps for every
20857        // little component state change.
20858        final int flags = !componentNames.contains(packageName)
20859                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20860        final int userId = UserHandle.getUserId(packageUid);
20861        final boolean isInstantApp = isInstantApp(packageName, userId);
20862        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20863        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20864        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20865                userIds, instantUserIds);
20866    }
20867
20868    @Override
20869    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20870        if (!sUserManager.exists(userId)) return;
20871        final int callingUid = Binder.getCallingUid();
20872        if (getInstantAppPackageName(callingUid) != null) {
20873            return;
20874        }
20875        final int permission = mContext.checkCallingOrSelfPermission(
20876                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20877        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20878        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20879                true /* requireFullPermission */, true /* checkShell */, "stop package");
20880        // writer
20881        synchronized (mPackages) {
20882            final PackageSetting ps = mSettings.mPackages.get(packageName);
20883            if (!filterAppAccessLPr(ps, callingUid, userId)
20884                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20885                            allowedByPermission, callingUid, userId)) {
20886                scheduleWritePackageRestrictionsLocked(userId);
20887            }
20888        }
20889    }
20890
20891    @Override
20892    public String getInstallerPackageName(String packageName) {
20893        final int callingUid = Binder.getCallingUid();
20894        synchronized (mPackages) {
20895            final PackageSetting ps = mSettings.mPackages.get(packageName);
20896            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20897                return null;
20898            }
20899            return mSettings.getInstallerPackageNameLPr(packageName);
20900        }
20901    }
20902
20903    public boolean isOrphaned(String packageName) {
20904        // reader
20905        synchronized (mPackages) {
20906            return mSettings.isOrphaned(packageName);
20907        }
20908    }
20909
20910    @Override
20911    public int getApplicationEnabledSetting(String packageName, int userId) {
20912        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20913        int callingUid = Binder.getCallingUid();
20914        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20915                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20916        // reader
20917        synchronized (mPackages) {
20918            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20919                return COMPONENT_ENABLED_STATE_DISABLED;
20920            }
20921            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20922        }
20923    }
20924
20925    @Override
20926    public int getComponentEnabledSetting(ComponentName component, int userId) {
20927        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20928        int callingUid = Binder.getCallingUid();
20929        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20930                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20931        synchronized (mPackages) {
20932            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20933                    component, TYPE_UNKNOWN, userId)) {
20934                return COMPONENT_ENABLED_STATE_DISABLED;
20935            }
20936            return mSettings.getComponentEnabledSettingLPr(component, userId);
20937        }
20938    }
20939
20940    @Override
20941    public void enterSafeMode() {
20942        enforceSystemOrRoot("Only the system can request entering safe mode");
20943
20944        if (!mSystemReady) {
20945            mSafeMode = true;
20946        }
20947    }
20948
20949    @Override
20950    public void systemReady() {
20951        enforceSystemOrRoot("Only the system can claim the system is ready");
20952
20953        mSystemReady = true;
20954        final ContentResolver resolver = mContext.getContentResolver();
20955        ContentObserver co = new ContentObserver(mHandler) {
20956            @Override
20957            public void onChange(boolean selfChange) {
20958                mWebInstantAppsDisabled =
20959                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20960                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20961            }
20962        };
20963        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20964                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20965                false, co, UserHandle.USER_SYSTEM);
20966        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20967                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20968        co.onChange(true);
20969
20970        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20971        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20972        // it is done.
20973        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20974            @Override
20975            public void onChange(boolean selfChange) {
20976                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20977                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20978                        oobEnabled == 1 ? "true" : "false");
20979            }
20980        };
20981        mContext.getContentResolver().registerContentObserver(
20982                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20983                UserHandle.USER_SYSTEM);
20984        // At boot, restore the value from the setting, which persists across reboot.
20985        privAppOobObserver.onChange(true);
20986
20987        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20988        // disabled after already being started.
20989        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20990                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20991
20992        // Read the compatibilty setting when the system is ready.
20993        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20994                mContext.getContentResolver(),
20995                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20996        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20997        if (DEBUG_SETTINGS) {
20998            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20999        }
21000
21001        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21002
21003        synchronized (mPackages) {
21004            // Verify that all of the preferred activity components actually
21005            // exist.  It is possible for applications to be updated and at
21006            // that point remove a previously declared activity component that
21007            // had been set as a preferred activity.  We try to clean this up
21008            // the next time we encounter that preferred activity, but it is
21009            // possible for the user flow to never be able to return to that
21010            // situation so here we do a sanity check to make sure we haven't
21011            // left any junk around.
21012            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21013            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21014                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21015                removed.clear();
21016                for (PreferredActivity pa : pir.filterSet()) {
21017                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21018                        removed.add(pa);
21019                    }
21020                }
21021                if (removed.size() > 0) {
21022                    for (int r=0; r<removed.size(); r++) {
21023                        PreferredActivity pa = removed.get(r);
21024                        Slog.w(TAG, "Removing dangling preferred activity: "
21025                                + pa.mPref.mComponent);
21026                        pir.removeFilter(pa);
21027                    }
21028                    mSettings.writePackageRestrictionsLPr(
21029                            mSettings.mPreferredActivities.keyAt(i));
21030                }
21031            }
21032
21033            for (int userId : UserManagerService.getInstance().getUserIds()) {
21034                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21035                    grantPermissionsUserIds = ArrayUtils.appendInt(
21036                            grantPermissionsUserIds, userId);
21037                }
21038            }
21039        }
21040        sUserManager.systemReady();
21041        // If we upgraded grant all default permissions before kicking off.
21042        for (int userId : grantPermissionsUserIds) {
21043            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21044        }
21045
21046        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21047            // If we did not grant default permissions, we preload from this the
21048            // default permission exceptions lazily to ensure we don't hit the
21049            // disk on a new user creation.
21050            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21051        }
21052
21053        // Now that we've scanned all packages, and granted any default
21054        // permissions, ensure permissions are updated. Beware of dragons if you
21055        // try optimizing this.
21056        synchronized (mPackages) {
21057            mPermissionManager.updateAllPermissions(
21058                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21059                    mPermissionCallback);
21060        }
21061
21062        // Kick off any messages waiting for system ready
21063        if (mPostSystemReadyMessages != null) {
21064            for (Message msg : mPostSystemReadyMessages) {
21065                msg.sendToTarget();
21066            }
21067            mPostSystemReadyMessages = null;
21068        }
21069
21070        // Watch for external volumes that come and go over time
21071        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21072        storage.registerListener(mStorageListener);
21073
21074        mInstallerService.systemReady();
21075        mPackageDexOptimizer.systemReady();
21076
21077        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21078                StorageManagerInternal.class);
21079        StorageManagerInternal.addExternalStoragePolicy(
21080                new StorageManagerInternal.ExternalStorageMountPolicy() {
21081            @Override
21082            public int getMountMode(int uid, String packageName) {
21083                if (Process.isIsolated(uid)) {
21084                    return Zygote.MOUNT_EXTERNAL_NONE;
21085                }
21086                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21087                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21088                }
21089                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21090                    return Zygote.MOUNT_EXTERNAL_READ;
21091                }
21092                return Zygote.MOUNT_EXTERNAL_WRITE;
21093            }
21094
21095            @Override
21096            public boolean hasExternalStorage(int uid, String packageName) {
21097                return true;
21098            }
21099        });
21100
21101        // Now that we're mostly running, clean up stale users and apps
21102        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21103        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21104
21105        mPermissionManager.systemReady();
21106
21107        if (mInstantAppResolverConnection != null) {
21108            mContext.registerReceiver(new BroadcastReceiver() {
21109                @Override
21110                public void onReceive(Context context, Intent intent) {
21111                    mInstantAppResolverConnection.optimisticBind();
21112                    mContext.unregisterReceiver(this);
21113                }
21114            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21115        }
21116    }
21117
21118    public void waitForAppDataPrepared() {
21119        if (mPrepareAppDataFuture == null) {
21120            return;
21121        }
21122        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21123        mPrepareAppDataFuture = null;
21124    }
21125
21126    @Override
21127    public boolean isSafeMode() {
21128        // allow instant applications
21129        return mSafeMode;
21130    }
21131
21132    @Override
21133    public boolean hasSystemUidErrors() {
21134        // allow instant applications
21135        return mHasSystemUidErrors;
21136    }
21137
21138    static String arrayToString(int[] array) {
21139        StringBuffer buf = new StringBuffer(128);
21140        buf.append('[');
21141        if (array != null) {
21142            for (int i=0; i<array.length; i++) {
21143                if (i > 0) buf.append(", ");
21144                buf.append(array[i]);
21145            }
21146        }
21147        buf.append(']');
21148        return buf.toString();
21149    }
21150
21151    @Override
21152    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21153            FileDescriptor err, String[] args, ShellCallback callback,
21154            ResultReceiver resultReceiver) {
21155        (new PackageManagerShellCommand(this)).exec(
21156                this, in, out, err, args, callback, resultReceiver);
21157    }
21158
21159    @Override
21160    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21161        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21162
21163        DumpState dumpState = new DumpState();
21164        boolean fullPreferred = false;
21165        boolean checkin = false;
21166
21167        String packageName = null;
21168        ArraySet<String> permissionNames = null;
21169
21170        int opti = 0;
21171        while (opti < args.length) {
21172            String opt = args[opti];
21173            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21174                break;
21175            }
21176            opti++;
21177
21178            if ("-a".equals(opt)) {
21179                // Right now we only know how to print all.
21180            } else if ("-h".equals(opt)) {
21181                pw.println("Package manager dump options:");
21182                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21183                pw.println("    --checkin: dump for a checkin");
21184                pw.println("    -f: print details of intent filters");
21185                pw.println("    -h: print this help");
21186                pw.println("  cmd may be one of:");
21187                pw.println("    l[ibraries]: list known shared libraries");
21188                pw.println("    f[eatures]: list device features");
21189                pw.println("    k[eysets]: print known keysets");
21190                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21191                pw.println("    perm[issions]: dump permissions");
21192                pw.println("    permission [name ...]: dump declaration and use of given permission");
21193                pw.println("    pref[erred]: print preferred package settings");
21194                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21195                pw.println("    prov[iders]: dump content providers");
21196                pw.println("    p[ackages]: dump installed packages");
21197                pw.println("    s[hared-users]: dump shared user IDs");
21198                pw.println("    m[essages]: print collected runtime messages");
21199                pw.println("    v[erifiers]: print package verifier info");
21200                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21201                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21202                pw.println("    version: print database version info");
21203                pw.println("    write: write current settings now");
21204                pw.println("    installs: details about install sessions");
21205                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21206                pw.println("    dexopt: dump dexopt state");
21207                pw.println("    compiler-stats: dump compiler statistics");
21208                pw.println("    service-permissions: dump permissions required by services");
21209                pw.println("    <package.name>: info about given package");
21210                return;
21211            } else if ("--checkin".equals(opt)) {
21212                checkin = true;
21213            } else if ("-f".equals(opt)) {
21214                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21215            } else if ("--proto".equals(opt)) {
21216                dumpProto(fd);
21217                return;
21218            } else {
21219                pw.println("Unknown argument: " + opt + "; use -h for help");
21220            }
21221        }
21222
21223        // Is the caller requesting to dump a particular piece of data?
21224        if (opti < args.length) {
21225            String cmd = args[opti];
21226            opti++;
21227            // Is this a package name?
21228            if ("android".equals(cmd) || cmd.contains(".")) {
21229                packageName = cmd;
21230                // When dumping a single package, we always dump all of its
21231                // filter information since the amount of data will be reasonable.
21232                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21233            } else if ("check-permission".equals(cmd)) {
21234                if (opti >= args.length) {
21235                    pw.println("Error: check-permission missing permission argument");
21236                    return;
21237                }
21238                String perm = args[opti];
21239                opti++;
21240                if (opti >= args.length) {
21241                    pw.println("Error: check-permission missing package argument");
21242                    return;
21243                }
21244
21245                String pkg = args[opti];
21246                opti++;
21247                int user = UserHandle.getUserId(Binder.getCallingUid());
21248                if (opti < args.length) {
21249                    try {
21250                        user = Integer.parseInt(args[opti]);
21251                    } catch (NumberFormatException e) {
21252                        pw.println("Error: check-permission user argument is not a number: "
21253                                + args[opti]);
21254                        return;
21255                    }
21256                }
21257
21258                // Normalize package name to handle renamed packages and static libs
21259                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21260
21261                pw.println(checkPermission(perm, pkg, user));
21262                return;
21263            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21264                dumpState.setDump(DumpState.DUMP_LIBS);
21265            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21266                dumpState.setDump(DumpState.DUMP_FEATURES);
21267            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21268                if (opti >= args.length) {
21269                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21270                            | DumpState.DUMP_SERVICE_RESOLVERS
21271                            | DumpState.DUMP_RECEIVER_RESOLVERS
21272                            | DumpState.DUMP_CONTENT_RESOLVERS);
21273                } else {
21274                    while (opti < args.length) {
21275                        String name = args[opti];
21276                        if ("a".equals(name) || "activity".equals(name)) {
21277                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21278                        } else if ("s".equals(name) || "service".equals(name)) {
21279                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21280                        } else if ("r".equals(name) || "receiver".equals(name)) {
21281                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21282                        } else if ("c".equals(name) || "content".equals(name)) {
21283                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21284                        } else {
21285                            pw.println("Error: unknown resolver table type: " + name);
21286                            return;
21287                        }
21288                        opti++;
21289                    }
21290                }
21291            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21292                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21293            } else if ("permission".equals(cmd)) {
21294                if (opti >= args.length) {
21295                    pw.println("Error: permission requires permission name");
21296                    return;
21297                }
21298                permissionNames = new ArraySet<>();
21299                while (opti < args.length) {
21300                    permissionNames.add(args[opti]);
21301                    opti++;
21302                }
21303                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21304                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21305            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21306                dumpState.setDump(DumpState.DUMP_PREFERRED);
21307            } else if ("preferred-xml".equals(cmd)) {
21308                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21309                if (opti < args.length && "--full".equals(args[opti])) {
21310                    fullPreferred = true;
21311                    opti++;
21312                }
21313            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21314                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21315            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21316                dumpState.setDump(DumpState.DUMP_PACKAGES);
21317            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21318                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21319            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21320                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21321            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21322                dumpState.setDump(DumpState.DUMP_MESSAGES);
21323            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21324                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21325            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21326                    || "intent-filter-verifiers".equals(cmd)) {
21327                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21328            } else if ("version".equals(cmd)) {
21329                dumpState.setDump(DumpState.DUMP_VERSION);
21330            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21331                dumpState.setDump(DumpState.DUMP_KEYSETS);
21332            } else if ("installs".equals(cmd)) {
21333                dumpState.setDump(DumpState.DUMP_INSTALLS);
21334            } else if ("frozen".equals(cmd)) {
21335                dumpState.setDump(DumpState.DUMP_FROZEN);
21336            } else if ("volumes".equals(cmd)) {
21337                dumpState.setDump(DumpState.DUMP_VOLUMES);
21338            } else if ("dexopt".equals(cmd)) {
21339                dumpState.setDump(DumpState.DUMP_DEXOPT);
21340            } else if ("compiler-stats".equals(cmd)) {
21341                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21342            } else if ("changes".equals(cmd)) {
21343                dumpState.setDump(DumpState.DUMP_CHANGES);
21344            } else if ("service-permissions".equals(cmd)) {
21345                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21346            } else if ("write".equals(cmd)) {
21347                synchronized (mPackages) {
21348                    mSettings.writeLPr();
21349                    pw.println("Settings written.");
21350                    return;
21351                }
21352            }
21353        }
21354
21355        if (checkin) {
21356            pw.println("vers,1");
21357        }
21358
21359        // reader
21360        synchronized (mPackages) {
21361            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21362                if (!checkin) {
21363                    if (dumpState.onTitlePrinted())
21364                        pw.println();
21365                    pw.println("Database versions:");
21366                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21367                }
21368            }
21369
21370            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21371                if (!checkin) {
21372                    if (dumpState.onTitlePrinted())
21373                        pw.println();
21374                    pw.println("Verifiers:");
21375                    pw.print("  Required: ");
21376                    pw.print(mRequiredVerifierPackage);
21377                    pw.print(" (uid=");
21378                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21379                            UserHandle.USER_SYSTEM));
21380                    pw.println(")");
21381                } else if (mRequiredVerifierPackage != null) {
21382                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21383                    pw.print(",");
21384                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21385                            UserHandle.USER_SYSTEM));
21386                }
21387            }
21388
21389            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21390                    packageName == null) {
21391                if (mIntentFilterVerifierComponent != null) {
21392                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21393                    if (!checkin) {
21394                        if (dumpState.onTitlePrinted())
21395                            pw.println();
21396                        pw.println("Intent Filter Verifier:");
21397                        pw.print("  Using: ");
21398                        pw.print(verifierPackageName);
21399                        pw.print(" (uid=");
21400                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21401                                UserHandle.USER_SYSTEM));
21402                        pw.println(")");
21403                    } else if (verifierPackageName != null) {
21404                        pw.print("ifv,"); pw.print(verifierPackageName);
21405                        pw.print(",");
21406                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21407                                UserHandle.USER_SYSTEM));
21408                    }
21409                } else {
21410                    pw.println();
21411                    pw.println("No Intent Filter Verifier available!");
21412                }
21413            }
21414
21415            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21416                boolean printedHeader = false;
21417                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21418                while (it.hasNext()) {
21419                    String libName = it.next();
21420                    LongSparseArray<SharedLibraryEntry> versionedLib
21421                            = mSharedLibraries.get(libName);
21422                    if (versionedLib == null) {
21423                        continue;
21424                    }
21425                    final int versionCount = versionedLib.size();
21426                    for (int i = 0; i < versionCount; i++) {
21427                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21428                        if (!checkin) {
21429                            if (!printedHeader) {
21430                                if (dumpState.onTitlePrinted())
21431                                    pw.println();
21432                                pw.println("Libraries:");
21433                                printedHeader = true;
21434                            }
21435                            pw.print("  ");
21436                        } else {
21437                            pw.print("lib,");
21438                        }
21439                        pw.print(libEntry.info.getName());
21440                        if (libEntry.info.isStatic()) {
21441                            pw.print(" version=" + libEntry.info.getLongVersion());
21442                        }
21443                        if (!checkin) {
21444                            pw.print(" -> ");
21445                        }
21446                        if (libEntry.path != null) {
21447                            pw.print(" (jar) ");
21448                            pw.print(libEntry.path);
21449                        } else {
21450                            pw.print(" (apk) ");
21451                            pw.print(libEntry.apk);
21452                        }
21453                        pw.println();
21454                    }
21455                }
21456            }
21457
21458            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21459                if (dumpState.onTitlePrinted())
21460                    pw.println();
21461                if (!checkin) {
21462                    pw.println("Features:");
21463                }
21464
21465                synchronized (mAvailableFeatures) {
21466                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21467                        if (checkin) {
21468                            pw.print("feat,");
21469                            pw.print(feat.name);
21470                            pw.print(",");
21471                            pw.println(feat.version);
21472                        } else {
21473                            pw.print("  ");
21474                            pw.print(feat.name);
21475                            if (feat.version > 0) {
21476                                pw.print(" version=");
21477                                pw.print(feat.version);
21478                            }
21479                            pw.println();
21480                        }
21481                    }
21482                }
21483            }
21484
21485            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21486                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21487                        : "Activity Resolver Table:", "  ", packageName,
21488                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21489                    dumpState.setTitlePrinted(true);
21490                }
21491            }
21492            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21493                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21494                        : "Receiver Resolver Table:", "  ", packageName,
21495                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21496                    dumpState.setTitlePrinted(true);
21497                }
21498            }
21499            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21500                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21501                        : "Service Resolver Table:", "  ", packageName,
21502                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21503                    dumpState.setTitlePrinted(true);
21504                }
21505            }
21506            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21507                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21508                        : "Provider Resolver Table:", "  ", packageName,
21509                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21510                    dumpState.setTitlePrinted(true);
21511                }
21512            }
21513
21514            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21515                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21516                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21517                    int user = mSettings.mPreferredActivities.keyAt(i);
21518                    if (pir.dump(pw,
21519                            dumpState.getTitlePrinted()
21520                                ? "\nPreferred Activities User " + user + ":"
21521                                : "Preferred Activities User " + user + ":", "  ",
21522                            packageName, true, false)) {
21523                        dumpState.setTitlePrinted(true);
21524                    }
21525                }
21526            }
21527
21528            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21529                pw.flush();
21530                FileOutputStream fout = new FileOutputStream(fd);
21531                BufferedOutputStream str = new BufferedOutputStream(fout);
21532                XmlSerializer serializer = new FastXmlSerializer();
21533                try {
21534                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21535                    serializer.startDocument(null, true);
21536                    serializer.setFeature(
21537                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21538                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21539                    serializer.endDocument();
21540                    serializer.flush();
21541                } catch (IllegalArgumentException e) {
21542                    pw.println("Failed writing: " + e);
21543                } catch (IllegalStateException e) {
21544                    pw.println("Failed writing: " + e);
21545                } catch (IOException e) {
21546                    pw.println("Failed writing: " + e);
21547                }
21548            }
21549
21550            if (!checkin
21551                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21552                    && packageName == null) {
21553                pw.println();
21554                int count = mSettings.mPackages.size();
21555                if (count == 0) {
21556                    pw.println("No applications!");
21557                    pw.println();
21558                } else {
21559                    final String prefix = "  ";
21560                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21561                    if (allPackageSettings.size() == 0) {
21562                        pw.println("No domain preferred apps!");
21563                        pw.println();
21564                    } else {
21565                        pw.println("App verification status:");
21566                        pw.println();
21567                        count = 0;
21568                        for (PackageSetting ps : allPackageSettings) {
21569                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21570                            if (ivi == null || ivi.getPackageName() == null) continue;
21571                            pw.println(prefix + "Package: " + ivi.getPackageName());
21572                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21573                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21574                            pw.println();
21575                            count++;
21576                        }
21577                        if (count == 0) {
21578                            pw.println(prefix + "No app verification established.");
21579                            pw.println();
21580                        }
21581                        for (int userId : sUserManager.getUserIds()) {
21582                            pw.println("App linkages for user " + userId + ":");
21583                            pw.println();
21584                            count = 0;
21585                            for (PackageSetting ps : allPackageSettings) {
21586                                final long status = ps.getDomainVerificationStatusForUser(userId);
21587                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21588                                        && !DEBUG_DOMAIN_VERIFICATION) {
21589                                    continue;
21590                                }
21591                                pw.println(prefix + "Package: " + ps.name);
21592                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21593                                String statusStr = IntentFilterVerificationInfo.
21594                                        getStatusStringFromValue(status);
21595                                pw.println(prefix + "Status:  " + statusStr);
21596                                pw.println();
21597                                count++;
21598                            }
21599                            if (count == 0) {
21600                                pw.println(prefix + "No configured app linkages.");
21601                                pw.println();
21602                            }
21603                        }
21604                    }
21605                }
21606            }
21607
21608            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21609                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21610            }
21611
21612            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21613                boolean printedSomething = false;
21614                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21615                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21616                        continue;
21617                    }
21618                    if (!printedSomething) {
21619                        if (dumpState.onTitlePrinted())
21620                            pw.println();
21621                        pw.println("Registered ContentProviders:");
21622                        printedSomething = true;
21623                    }
21624                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21625                    pw.print("    "); pw.println(p.toString());
21626                }
21627                printedSomething = false;
21628                for (Map.Entry<String, PackageParser.Provider> entry :
21629                        mProvidersByAuthority.entrySet()) {
21630                    PackageParser.Provider p = entry.getValue();
21631                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21632                        continue;
21633                    }
21634                    if (!printedSomething) {
21635                        if (dumpState.onTitlePrinted())
21636                            pw.println();
21637                        pw.println("ContentProvider Authorities:");
21638                        printedSomething = true;
21639                    }
21640                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21641                    pw.print("    "); pw.println(p.toString());
21642                    if (p.info != null && p.info.applicationInfo != null) {
21643                        final String appInfo = p.info.applicationInfo.toString();
21644                        pw.print("      applicationInfo="); pw.println(appInfo);
21645                    }
21646                }
21647            }
21648
21649            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21650                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21651            }
21652
21653            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21654                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21655            }
21656
21657            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21658                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21659            }
21660
21661            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21662                if (dumpState.onTitlePrinted()) pw.println();
21663                pw.println("Package Changes:");
21664                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21665                final int K = mChangedPackages.size();
21666                for (int i = 0; i < K; i++) {
21667                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21668                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21669                    final int N = changes.size();
21670                    if (N == 0) {
21671                        pw.print("    "); pw.println("No packages changed");
21672                    } else {
21673                        for (int j = 0; j < N; j++) {
21674                            final String pkgName = changes.valueAt(j);
21675                            final int sequenceNumber = changes.keyAt(j);
21676                            pw.print("    ");
21677                            pw.print("seq=");
21678                            pw.print(sequenceNumber);
21679                            pw.print(", package=");
21680                            pw.println(pkgName);
21681                        }
21682                    }
21683                }
21684            }
21685
21686            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21687                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21688            }
21689
21690            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21691                // XXX should handle packageName != null by dumping only install data that
21692                // the given package is involved with.
21693                if (dumpState.onTitlePrinted()) pw.println();
21694
21695                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21696                ipw.println();
21697                ipw.println("Frozen packages:");
21698                ipw.increaseIndent();
21699                if (mFrozenPackages.size() == 0) {
21700                    ipw.println("(none)");
21701                } else {
21702                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21703                        ipw.println(mFrozenPackages.valueAt(i));
21704                    }
21705                }
21706                ipw.decreaseIndent();
21707            }
21708
21709            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21710                if (dumpState.onTitlePrinted()) pw.println();
21711
21712                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21713                ipw.println();
21714                ipw.println("Loaded volumes:");
21715                ipw.increaseIndent();
21716                if (mLoadedVolumes.size() == 0) {
21717                    ipw.println("(none)");
21718                } else {
21719                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21720                        ipw.println(mLoadedVolumes.valueAt(i));
21721                    }
21722                }
21723                ipw.decreaseIndent();
21724            }
21725
21726            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21727                    && packageName == null) {
21728                if (dumpState.onTitlePrinted()) pw.println();
21729                pw.println("Service permissions:");
21730
21731                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21732                while (filterIterator.hasNext()) {
21733                    final ServiceIntentInfo info = filterIterator.next();
21734                    final ServiceInfo serviceInfo = info.service.info;
21735                    final String permission = serviceInfo.permission;
21736                    if (permission != null) {
21737                        pw.print("    ");
21738                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21739                        pw.print(": ");
21740                        pw.println(permission);
21741                    }
21742                }
21743            }
21744
21745            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21746                if (dumpState.onTitlePrinted()) pw.println();
21747                dumpDexoptStateLPr(pw, packageName);
21748            }
21749
21750            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21751                if (dumpState.onTitlePrinted()) pw.println();
21752                dumpCompilerStatsLPr(pw, packageName);
21753            }
21754
21755            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21756                if (dumpState.onTitlePrinted()) pw.println();
21757                mSettings.dumpReadMessagesLPr(pw, dumpState);
21758
21759                pw.println();
21760                pw.println("Package warning messages:");
21761                dumpCriticalInfo(pw, null);
21762            }
21763
21764            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21765                dumpCriticalInfo(pw, "msg,");
21766            }
21767        }
21768
21769        // PackageInstaller should be called outside of mPackages lock
21770        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21771            // XXX should handle packageName != null by dumping only install data that
21772            // the given package is involved with.
21773            if (dumpState.onTitlePrinted()) pw.println();
21774            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21775        }
21776    }
21777
21778    private void dumpProto(FileDescriptor fd) {
21779        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21780
21781        synchronized (mPackages) {
21782            final long requiredVerifierPackageToken =
21783                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21784            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21785            proto.write(
21786                    PackageServiceDumpProto.PackageShortProto.UID,
21787                    getPackageUid(
21788                            mRequiredVerifierPackage,
21789                            MATCH_DEBUG_TRIAGED_MISSING,
21790                            UserHandle.USER_SYSTEM));
21791            proto.end(requiredVerifierPackageToken);
21792
21793            if (mIntentFilterVerifierComponent != null) {
21794                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21795                final long verifierPackageToken =
21796                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21797                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21798                proto.write(
21799                        PackageServiceDumpProto.PackageShortProto.UID,
21800                        getPackageUid(
21801                                verifierPackageName,
21802                                MATCH_DEBUG_TRIAGED_MISSING,
21803                                UserHandle.USER_SYSTEM));
21804                proto.end(verifierPackageToken);
21805            }
21806
21807            dumpSharedLibrariesProto(proto);
21808            dumpFeaturesProto(proto);
21809            mSettings.dumpPackagesProto(proto);
21810            mSettings.dumpSharedUsersProto(proto);
21811            dumpCriticalInfo(proto);
21812        }
21813        proto.flush();
21814    }
21815
21816    private void dumpFeaturesProto(ProtoOutputStream proto) {
21817        synchronized (mAvailableFeatures) {
21818            final int count = mAvailableFeatures.size();
21819            for (int i = 0; i < count; i++) {
21820                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21821            }
21822        }
21823    }
21824
21825    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21826        final int count = mSharedLibraries.size();
21827        for (int i = 0; i < count; i++) {
21828            final String libName = mSharedLibraries.keyAt(i);
21829            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21830            if (versionedLib == null) {
21831                continue;
21832            }
21833            final int versionCount = versionedLib.size();
21834            for (int j = 0; j < versionCount; j++) {
21835                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21836                final long sharedLibraryToken =
21837                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21838                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21839                final boolean isJar = (libEntry.path != null);
21840                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21841                if (isJar) {
21842                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21843                } else {
21844                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21845                }
21846                proto.end(sharedLibraryToken);
21847            }
21848        }
21849    }
21850
21851    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21852        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21853        ipw.println();
21854        ipw.println("Dexopt state:");
21855        ipw.increaseIndent();
21856        Collection<PackageParser.Package> packages = null;
21857        if (packageName != null) {
21858            PackageParser.Package targetPackage = mPackages.get(packageName);
21859            if (targetPackage != null) {
21860                packages = Collections.singletonList(targetPackage);
21861            } else {
21862                ipw.println("Unable to find package: " + packageName);
21863                return;
21864            }
21865        } else {
21866            packages = mPackages.values();
21867        }
21868
21869        for (PackageParser.Package pkg : packages) {
21870            ipw.println("[" + pkg.packageName + "]");
21871            ipw.increaseIndent();
21872            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21873                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21874            ipw.decreaseIndent();
21875        }
21876    }
21877
21878    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21879        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21880        ipw.println();
21881        ipw.println("Compiler stats:");
21882        ipw.increaseIndent();
21883        Collection<PackageParser.Package> packages = null;
21884        if (packageName != null) {
21885            PackageParser.Package targetPackage = mPackages.get(packageName);
21886            if (targetPackage != null) {
21887                packages = Collections.singletonList(targetPackage);
21888            } else {
21889                ipw.println("Unable to find package: " + packageName);
21890                return;
21891            }
21892        } else {
21893            packages = mPackages.values();
21894        }
21895
21896        for (PackageParser.Package pkg : packages) {
21897            ipw.println("[" + pkg.packageName + "]");
21898            ipw.increaseIndent();
21899
21900            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21901            if (stats == null) {
21902                ipw.println("(No recorded stats)");
21903            } else {
21904                stats.dump(ipw);
21905            }
21906            ipw.decreaseIndent();
21907        }
21908    }
21909
21910    private String dumpDomainString(String packageName) {
21911        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21912                .getList();
21913        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21914
21915        ArraySet<String> result = new ArraySet<>();
21916        if (iviList.size() > 0) {
21917            for (IntentFilterVerificationInfo ivi : iviList) {
21918                for (String host : ivi.getDomains()) {
21919                    result.add(host);
21920                }
21921            }
21922        }
21923        if (filters != null && filters.size() > 0) {
21924            for (IntentFilter filter : filters) {
21925                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21926                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21927                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21928                    result.addAll(filter.getHostsList());
21929                }
21930            }
21931        }
21932
21933        StringBuilder sb = new StringBuilder(result.size() * 16);
21934        for (String domain : result) {
21935            if (sb.length() > 0) sb.append(" ");
21936            sb.append(domain);
21937        }
21938        return sb.toString();
21939    }
21940
21941    // ------- apps on sdcard specific code -------
21942    static final boolean DEBUG_SD_INSTALL = false;
21943
21944    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21945
21946    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21947
21948    private boolean mMediaMounted = false;
21949
21950    static String getEncryptKey() {
21951        try {
21952            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21953                    SD_ENCRYPTION_KEYSTORE_NAME);
21954            if (sdEncKey == null) {
21955                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21956                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21957                if (sdEncKey == null) {
21958                    Slog.e(TAG, "Failed to create encryption keys");
21959                    return null;
21960                }
21961            }
21962            return sdEncKey;
21963        } catch (NoSuchAlgorithmException nsae) {
21964            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21965            return null;
21966        } catch (IOException ioe) {
21967            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21968            return null;
21969        }
21970    }
21971
21972    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21973            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21974        final int size = infos.size();
21975        final String[] packageNames = new String[size];
21976        final int[] packageUids = new int[size];
21977        for (int i = 0; i < size; i++) {
21978            final ApplicationInfo info = infos.get(i);
21979            packageNames[i] = info.packageName;
21980            packageUids[i] = info.uid;
21981        }
21982        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21983                finishedReceiver);
21984    }
21985
21986    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21987            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21988        sendResourcesChangedBroadcast(mediaStatus, replacing,
21989                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21990    }
21991
21992    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21993            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21994        int size = pkgList.length;
21995        if (size > 0) {
21996            // Send broadcasts here
21997            Bundle extras = new Bundle();
21998            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21999            if (uidArr != null) {
22000                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22001            }
22002            if (replacing) {
22003                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22004            }
22005            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22006                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22007            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22008        }
22009    }
22010
22011    private void loadPrivatePackages(final VolumeInfo vol) {
22012        mHandler.post(new Runnable() {
22013            @Override
22014            public void run() {
22015                loadPrivatePackagesInner(vol);
22016            }
22017        });
22018    }
22019
22020    private void loadPrivatePackagesInner(VolumeInfo vol) {
22021        final String volumeUuid = vol.fsUuid;
22022        if (TextUtils.isEmpty(volumeUuid)) {
22023            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22024            return;
22025        }
22026
22027        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22028        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22029        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22030
22031        final VersionInfo ver;
22032        final List<PackageSetting> packages;
22033        synchronized (mPackages) {
22034            ver = mSettings.findOrCreateVersion(volumeUuid);
22035            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22036        }
22037
22038        for (PackageSetting ps : packages) {
22039            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22040            synchronized (mInstallLock) {
22041                final PackageParser.Package pkg;
22042                try {
22043                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22044                    loaded.add(pkg.applicationInfo);
22045
22046                } catch (PackageManagerException e) {
22047                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22048                }
22049
22050                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22051                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22052                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22053                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22054                }
22055            }
22056        }
22057
22058        // Reconcile app data for all started/unlocked users
22059        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22060        final UserManager um = mContext.getSystemService(UserManager.class);
22061        UserManagerInternal umInternal = getUserManagerInternal();
22062        for (UserInfo user : um.getUsers()) {
22063            final int flags;
22064            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22065                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22066            } else if (umInternal.isUserRunning(user.id)) {
22067                flags = StorageManager.FLAG_STORAGE_DE;
22068            } else {
22069                continue;
22070            }
22071
22072            try {
22073                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22074                synchronized (mInstallLock) {
22075                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22076                }
22077            } catch (IllegalStateException e) {
22078                // Device was probably ejected, and we'll process that event momentarily
22079                Slog.w(TAG, "Failed to prepare storage: " + e);
22080            }
22081        }
22082
22083        synchronized (mPackages) {
22084            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22085            if (sdkUpdated) {
22086                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22087                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22088            }
22089            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22090                    mPermissionCallback);
22091
22092            // Yay, everything is now upgraded
22093            ver.forceCurrent();
22094
22095            mSettings.writeLPr();
22096        }
22097
22098        for (PackageFreezer freezer : freezers) {
22099            freezer.close();
22100        }
22101
22102        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22103        sendResourcesChangedBroadcast(true, false, loaded, null);
22104        mLoadedVolumes.add(vol.getId());
22105    }
22106
22107    private void unloadPrivatePackages(final VolumeInfo vol) {
22108        mHandler.post(new Runnable() {
22109            @Override
22110            public void run() {
22111                unloadPrivatePackagesInner(vol);
22112            }
22113        });
22114    }
22115
22116    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22117        final String volumeUuid = vol.fsUuid;
22118        if (TextUtils.isEmpty(volumeUuid)) {
22119            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22120            return;
22121        }
22122
22123        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22124        synchronized (mInstallLock) {
22125        synchronized (mPackages) {
22126            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22127            for (PackageSetting ps : packages) {
22128                if (ps.pkg == null) continue;
22129
22130                final ApplicationInfo info = ps.pkg.applicationInfo;
22131                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22132                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22133
22134                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22135                        "unloadPrivatePackagesInner")) {
22136                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22137                            false, null)) {
22138                        unloaded.add(info);
22139                    } else {
22140                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22141                    }
22142                }
22143
22144                // Try very hard to release any references to this package
22145                // so we don't risk the system server being killed due to
22146                // open FDs
22147                AttributeCache.instance().removePackage(ps.name);
22148            }
22149
22150            mSettings.writeLPr();
22151        }
22152        }
22153
22154        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22155        sendResourcesChangedBroadcast(false, false, unloaded, null);
22156        mLoadedVolumes.remove(vol.getId());
22157
22158        // Try very hard to release any references to this path so we don't risk
22159        // the system server being killed due to open FDs
22160        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22161
22162        for (int i = 0; i < 3; i++) {
22163            System.gc();
22164            System.runFinalization();
22165        }
22166    }
22167
22168    private void assertPackageKnown(String volumeUuid, String packageName)
22169            throws PackageManagerException {
22170        synchronized (mPackages) {
22171            // Normalize package name to handle renamed packages
22172            packageName = normalizePackageNameLPr(packageName);
22173
22174            final PackageSetting ps = mSettings.mPackages.get(packageName);
22175            if (ps == null) {
22176                throw new PackageManagerException("Package " + packageName + " is unknown");
22177            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22178                throw new PackageManagerException(
22179                        "Package " + packageName + " found on unknown volume " + volumeUuid
22180                                + "; expected volume " + ps.volumeUuid);
22181            }
22182        }
22183    }
22184
22185    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22186            throws PackageManagerException {
22187        synchronized (mPackages) {
22188            // Normalize package name to handle renamed packages
22189            packageName = normalizePackageNameLPr(packageName);
22190
22191            final PackageSetting ps = mSettings.mPackages.get(packageName);
22192            if (ps == null) {
22193                throw new PackageManagerException("Package " + packageName + " is unknown");
22194            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22195                throw new PackageManagerException(
22196                        "Package " + packageName + " found on unknown volume " + volumeUuid
22197                                + "; expected volume " + ps.volumeUuid);
22198            } else if (!ps.getInstalled(userId)) {
22199                throw new PackageManagerException(
22200                        "Package " + packageName + " not installed for user " + userId);
22201            }
22202        }
22203    }
22204
22205    private List<String> collectAbsoluteCodePaths() {
22206        synchronized (mPackages) {
22207            List<String> codePaths = new ArrayList<>();
22208            final int packageCount = mSettings.mPackages.size();
22209            for (int i = 0; i < packageCount; i++) {
22210                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22211                codePaths.add(ps.codePath.getAbsolutePath());
22212            }
22213            return codePaths;
22214        }
22215    }
22216
22217    /**
22218     * Examine all apps present on given mounted volume, and destroy apps that
22219     * aren't expected, either due to uninstallation or reinstallation on
22220     * another volume.
22221     */
22222    private void reconcileApps(String volumeUuid) {
22223        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22224        List<File> filesToDelete = null;
22225
22226        final File[] files = FileUtils.listFilesOrEmpty(
22227                Environment.getDataAppDirectory(volumeUuid));
22228        for (File file : files) {
22229            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22230                    && !PackageInstallerService.isStageName(file.getName());
22231            if (!isPackage) {
22232                // Ignore entries which are not packages
22233                continue;
22234            }
22235
22236            String absolutePath = file.getAbsolutePath();
22237
22238            boolean pathValid = false;
22239            final int absoluteCodePathCount = absoluteCodePaths.size();
22240            for (int i = 0; i < absoluteCodePathCount; i++) {
22241                String absoluteCodePath = absoluteCodePaths.get(i);
22242                if (absolutePath.startsWith(absoluteCodePath)) {
22243                    pathValid = true;
22244                    break;
22245                }
22246            }
22247
22248            if (!pathValid) {
22249                if (filesToDelete == null) {
22250                    filesToDelete = new ArrayList<>();
22251                }
22252                filesToDelete.add(file);
22253            }
22254        }
22255
22256        if (filesToDelete != null) {
22257            final int fileToDeleteCount = filesToDelete.size();
22258            for (int i = 0; i < fileToDeleteCount; i++) {
22259                File fileToDelete = filesToDelete.get(i);
22260                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22261                synchronized (mInstallLock) {
22262                    removeCodePathLI(fileToDelete);
22263                }
22264            }
22265        }
22266    }
22267
22268    /**
22269     * Reconcile all app data for the given user.
22270     * <p>
22271     * Verifies that directories exist and that ownership and labeling is
22272     * correct for all installed apps on all mounted volumes.
22273     */
22274    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22275        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22276        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22277            final String volumeUuid = vol.getFsUuid();
22278            synchronized (mInstallLock) {
22279                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22280            }
22281        }
22282    }
22283
22284    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22285            boolean migrateAppData) {
22286        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22287    }
22288
22289    /**
22290     * Reconcile all app data on given mounted volume.
22291     * <p>
22292     * Destroys app data that isn't expected, either due to uninstallation or
22293     * reinstallation on another volume.
22294     * <p>
22295     * Verifies that directories exist and that ownership and labeling is
22296     * correct for all installed apps.
22297     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22298     */
22299    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22300            boolean migrateAppData, boolean onlyCoreApps) {
22301        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22302                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22303        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22304
22305        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22306        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22307
22308        // First look for stale data that doesn't belong, and check if things
22309        // have changed since we did our last restorecon
22310        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22311            if (StorageManager.isFileEncryptedNativeOrEmulated()
22312                    && !StorageManager.isUserKeyUnlocked(userId)) {
22313                throw new RuntimeException(
22314                        "Yikes, someone asked us to reconcile CE storage while " + userId
22315                                + " was still locked; this would have caused massive data loss!");
22316            }
22317
22318            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22319            for (File file : files) {
22320                final String packageName = file.getName();
22321                try {
22322                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22323                } catch (PackageManagerException e) {
22324                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22325                    try {
22326                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22327                                StorageManager.FLAG_STORAGE_CE, 0);
22328                    } catch (InstallerException e2) {
22329                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22330                    }
22331                }
22332            }
22333        }
22334        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22335            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22336            for (File file : files) {
22337                final String packageName = file.getName();
22338                try {
22339                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22340                } catch (PackageManagerException e) {
22341                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22342                    try {
22343                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22344                                StorageManager.FLAG_STORAGE_DE, 0);
22345                    } catch (InstallerException e2) {
22346                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22347                    }
22348                }
22349            }
22350        }
22351
22352        // Ensure that data directories are ready to roll for all packages
22353        // installed for this volume and user
22354        final List<PackageSetting> packages;
22355        synchronized (mPackages) {
22356            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22357        }
22358        int preparedCount = 0;
22359        for (PackageSetting ps : packages) {
22360            final String packageName = ps.name;
22361            if (ps.pkg == null) {
22362                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22363                // TODO: might be due to legacy ASEC apps; we should circle back
22364                // and reconcile again once they're scanned
22365                continue;
22366            }
22367            // Skip non-core apps if requested
22368            if (onlyCoreApps && !ps.pkg.coreApp) {
22369                result.add(packageName);
22370                continue;
22371            }
22372
22373            if (ps.getInstalled(userId)) {
22374                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22375                preparedCount++;
22376            }
22377        }
22378
22379        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22380        return result;
22381    }
22382
22383    /**
22384     * Prepare app data for the given app just after it was installed or
22385     * upgraded. This method carefully only touches users that it's installed
22386     * for, and it forces a restorecon to handle any seinfo changes.
22387     * <p>
22388     * Verifies that directories exist and that ownership and labeling is
22389     * correct for all installed apps. If there is an ownership mismatch, it
22390     * will try recovering system apps by wiping data; third-party app data is
22391     * left intact.
22392     * <p>
22393     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22394     */
22395    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22396        final PackageSetting ps;
22397        synchronized (mPackages) {
22398            ps = mSettings.mPackages.get(pkg.packageName);
22399            mSettings.writeKernelMappingLPr(ps);
22400        }
22401
22402        final UserManager um = mContext.getSystemService(UserManager.class);
22403        UserManagerInternal umInternal = getUserManagerInternal();
22404        for (UserInfo user : um.getUsers()) {
22405            final int flags;
22406            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22407                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22408            } else if (umInternal.isUserRunning(user.id)) {
22409                flags = StorageManager.FLAG_STORAGE_DE;
22410            } else {
22411                continue;
22412            }
22413
22414            if (ps.getInstalled(user.id)) {
22415                // TODO: when user data is locked, mark that we're still dirty
22416                prepareAppDataLIF(pkg, user.id, flags);
22417            }
22418        }
22419    }
22420
22421    /**
22422     * Prepare app data for the given app.
22423     * <p>
22424     * Verifies that directories exist and that ownership and labeling is
22425     * correct for all installed apps. If there is an ownership mismatch, this
22426     * will try recovering system apps by wiping data; third-party app data is
22427     * left intact.
22428     */
22429    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22430        if (pkg == null) {
22431            Slog.wtf(TAG, "Package was null!", new Throwable());
22432            return;
22433        }
22434        prepareAppDataLeafLIF(pkg, userId, flags);
22435        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22436        for (int i = 0; i < childCount; i++) {
22437            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22438        }
22439    }
22440
22441    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22442            boolean maybeMigrateAppData) {
22443        prepareAppDataLIF(pkg, userId, flags);
22444
22445        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22446            // We may have just shuffled around app data directories, so
22447            // prepare them one more time
22448            prepareAppDataLIF(pkg, userId, flags);
22449        }
22450    }
22451
22452    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22453        if (DEBUG_APP_DATA) {
22454            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22455                    + Integer.toHexString(flags));
22456        }
22457
22458        final PackageSetting ps;
22459        synchronized (mPackages) {
22460            ps = mSettings.mPackages.get(pkg.packageName);
22461        }
22462        final String volumeUuid = pkg.volumeUuid;
22463        final String packageName = pkg.packageName;
22464
22465        ApplicationInfo app = (ps == null)
22466                ? pkg.applicationInfo
22467                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22468        if (app == null) {
22469            app = pkg.applicationInfo;
22470        }
22471
22472        final int appId = UserHandle.getAppId(app.uid);
22473
22474        Preconditions.checkNotNull(app.seInfo);
22475
22476        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22477        long ceDataInode = -1;
22478        try {
22479            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22480                    appId, seInfo, app.targetSdkVersion);
22481        } catch (InstallerException e) {
22482            if (app.isSystemApp()) {
22483                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22484                        + ", but trying to recover: " + e);
22485                destroyAppDataLeafLIF(pkg, userId, flags);
22486                try {
22487                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22488                            appId, seInfo, app.targetSdkVersion);
22489                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22490                } catch (InstallerException e2) {
22491                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22492                }
22493            } else {
22494                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22495            }
22496        }
22497        // Prepare the application profiles only for upgrades and first boot (so that we don't
22498        // repeat the same operation at each boot).
22499        // We only have to cover the upgrade and first boot here because for app installs we
22500        // prepare the profiles before invoking dexopt (in installPackageLI).
22501        //
22502        // We also have to cover non system users because we do not call the usual install package
22503        // methods for them.
22504        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22505            mArtManagerService.prepareAppProfiles(pkg, userId);
22506        }
22507
22508        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22509            // TODO: mark this structure as dirty so we persist it!
22510            synchronized (mPackages) {
22511                if (ps != null) {
22512                    ps.setCeDataInode(ceDataInode, userId);
22513                }
22514            }
22515        }
22516
22517        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22518    }
22519
22520    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22521        if (pkg == null) {
22522            Slog.wtf(TAG, "Package was null!", new Throwable());
22523            return;
22524        }
22525        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22526        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22527        for (int i = 0; i < childCount; i++) {
22528            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22529        }
22530    }
22531
22532    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22533        final String volumeUuid = pkg.volumeUuid;
22534        final String packageName = pkg.packageName;
22535        final ApplicationInfo app = pkg.applicationInfo;
22536
22537        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22538            // Create a native library symlink only if we have native libraries
22539            // and if the native libraries are 32 bit libraries. We do not provide
22540            // this symlink for 64 bit libraries.
22541            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22542                final String nativeLibPath = app.nativeLibraryDir;
22543                try {
22544                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22545                            nativeLibPath, userId);
22546                } catch (InstallerException e) {
22547                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22548                }
22549            }
22550        }
22551    }
22552
22553    /**
22554     * For system apps on non-FBE devices, this method migrates any existing
22555     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22556     * requested by the app.
22557     */
22558    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22559        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22560                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22561            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22562                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22563            try {
22564                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22565                        storageTarget);
22566            } catch (InstallerException e) {
22567                logCriticalInfo(Log.WARN,
22568                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22569            }
22570            return true;
22571        } else {
22572            return false;
22573        }
22574    }
22575
22576    public PackageFreezer freezePackage(String packageName, String killReason) {
22577        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22578    }
22579
22580    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22581        return new PackageFreezer(packageName, userId, killReason);
22582    }
22583
22584    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22585            String killReason) {
22586        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22587    }
22588
22589    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22590            String killReason) {
22591        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22592            return new PackageFreezer();
22593        } else {
22594            return freezePackage(packageName, userId, killReason);
22595        }
22596    }
22597
22598    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22599            String killReason) {
22600        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22601    }
22602
22603    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22604            String killReason) {
22605        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22606            return new PackageFreezer();
22607        } else {
22608            return freezePackage(packageName, userId, killReason);
22609        }
22610    }
22611
22612    /**
22613     * Class that freezes and kills the given package upon creation, and
22614     * unfreezes it upon closing. This is typically used when doing surgery on
22615     * app code/data to prevent the app from running while you're working.
22616     */
22617    private class PackageFreezer implements AutoCloseable {
22618        private final String mPackageName;
22619        private final PackageFreezer[] mChildren;
22620
22621        private final boolean mWeFroze;
22622
22623        private final AtomicBoolean mClosed = new AtomicBoolean();
22624        private final CloseGuard mCloseGuard = CloseGuard.get();
22625
22626        /**
22627         * Create and return a stub freezer that doesn't actually do anything,
22628         * typically used when someone requested
22629         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22630         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22631         */
22632        public PackageFreezer() {
22633            mPackageName = null;
22634            mChildren = null;
22635            mWeFroze = false;
22636            mCloseGuard.open("close");
22637        }
22638
22639        public PackageFreezer(String packageName, int userId, String killReason) {
22640            synchronized (mPackages) {
22641                mPackageName = packageName;
22642                mWeFroze = mFrozenPackages.add(mPackageName);
22643
22644                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22645                if (ps != null) {
22646                    killApplication(ps.name, ps.appId, userId, killReason);
22647                }
22648
22649                final PackageParser.Package p = mPackages.get(packageName);
22650                if (p != null && p.childPackages != null) {
22651                    final int N = p.childPackages.size();
22652                    mChildren = new PackageFreezer[N];
22653                    for (int i = 0; i < N; i++) {
22654                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22655                                userId, killReason);
22656                    }
22657                } else {
22658                    mChildren = null;
22659                }
22660            }
22661            mCloseGuard.open("close");
22662        }
22663
22664        @Override
22665        protected void finalize() throws Throwable {
22666            try {
22667                if (mCloseGuard != null) {
22668                    mCloseGuard.warnIfOpen();
22669                }
22670
22671                close();
22672            } finally {
22673                super.finalize();
22674            }
22675        }
22676
22677        @Override
22678        public void close() {
22679            mCloseGuard.close();
22680            if (mClosed.compareAndSet(false, true)) {
22681                synchronized (mPackages) {
22682                    if (mWeFroze) {
22683                        mFrozenPackages.remove(mPackageName);
22684                    }
22685
22686                    if (mChildren != null) {
22687                        for (PackageFreezer freezer : mChildren) {
22688                            freezer.close();
22689                        }
22690                    }
22691                }
22692            }
22693        }
22694    }
22695
22696    /**
22697     * Verify that given package is currently frozen.
22698     */
22699    private void checkPackageFrozen(String packageName) {
22700        synchronized (mPackages) {
22701            if (!mFrozenPackages.contains(packageName)) {
22702                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22703            }
22704        }
22705    }
22706
22707    @Override
22708    public int movePackage(final String packageName, final String volumeUuid) {
22709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22710
22711        final int callingUid = Binder.getCallingUid();
22712        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22713        final int moveId = mNextMoveId.getAndIncrement();
22714        mHandler.post(new Runnable() {
22715            @Override
22716            public void run() {
22717                try {
22718                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22719                } catch (PackageManagerException e) {
22720                    Slog.w(TAG, "Failed to move " + packageName, e);
22721                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22722                }
22723            }
22724        });
22725        return moveId;
22726    }
22727
22728    private void movePackageInternal(final String packageName, final String volumeUuid,
22729            final int moveId, final int callingUid, UserHandle user)
22730                    throws PackageManagerException {
22731        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22732        final PackageManager pm = mContext.getPackageManager();
22733
22734        final boolean currentAsec;
22735        final String currentVolumeUuid;
22736        final File codeFile;
22737        final String installerPackageName;
22738        final String packageAbiOverride;
22739        final int appId;
22740        final String seinfo;
22741        final String label;
22742        final int targetSdkVersion;
22743        final PackageFreezer freezer;
22744        final int[] installedUserIds;
22745
22746        // reader
22747        synchronized (mPackages) {
22748            final PackageParser.Package pkg = mPackages.get(packageName);
22749            final PackageSetting ps = mSettings.mPackages.get(packageName);
22750            if (pkg == null
22751                    || ps == null
22752                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22753                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22754            }
22755            if (pkg.applicationInfo.isSystemApp()) {
22756                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22757                        "Cannot move system application");
22758            }
22759
22760            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22761            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22762                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22763            if (isInternalStorage && !allow3rdPartyOnInternal) {
22764                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22765                        "3rd party apps are not allowed on internal storage");
22766            }
22767
22768            if (pkg.applicationInfo.isExternalAsec()) {
22769                currentAsec = true;
22770                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22771            } else if (pkg.applicationInfo.isForwardLocked()) {
22772                currentAsec = true;
22773                currentVolumeUuid = "forward_locked";
22774            } else {
22775                currentAsec = false;
22776                currentVolumeUuid = ps.volumeUuid;
22777
22778                final File probe = new File(pkg.codePath);
22779                final File probeOat = new File(probe, "oat");
22780                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22781                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22782                            "Move only supported for modern cluster style installs");
22783                }
22784            }
22785
22786            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22787                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22788                        "Package already moved to " + volumeUuid);
22789            }
22790            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22791                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22792                        "Device admin cannot be moved");
22793            }
22794
22795            if (mFrozenPackages.contains(packageName)) {
22796                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22797                        "Failed to move already frozen package");
22798            }
22799
22800            codeFile = new File(pkg.codePath);
22801            installerPackageName = ps.installerPackageName;
22802            packageAbiOverride = ps.cpuAbiOverrideString;
22803            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22804            seinfo = pkg.applicationInfo.seInfo;
22805            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22806            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22807            freezer = freezePackage(packageName, "movePackageInternal");
22808            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22809        }
22810
22811        final Bundle extras = new Bundle();
22812        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22813        extras.putString(Intent.EXTRA_TITLE, label);
22814        mMoveCallbacks.notifyCreated(moveId, extras);
22815
22816        int installFlags;
22817        final boolean moveCompleteApp;
22818        final File measurePath;
22819
22820        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22821            installFlags = INSTALL_INTERNAL;
22822            moveCompleteApp = !currentAsec;
22823            measurePath = Environment.getDataAppDirectory(volumeUuid);
22824        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22825            installFlags = INSTALL_EXTERNAL;
22826            moveCompleteApp = false;
22827            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22828        } else {
22829            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22830            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22831                    || !volume.isMountedWritable()) {
22832                freezer.close();
22833                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22834                        "Move location not mounted private volume");
22835            }
22836
22837            Preconditions.checkState(!currentAsec);
22838
22839            installFlags = INSTALL_INTERNAL;
22840            moveCompleteApp = true;
22841            measurePath = Environment.getDataAppDirectory(volumeUuid);
22842        }
22843
22844        // If we're moving app data around, we need all the users unlocked
22845        if (moveCompleteApp) {
22846            for (int userId : installedUserIds) {
22847                if (StorageManager.isFileEncryptedNativeOrEmulated()
22848                        && !StorageManager.isUserKeyUnlocked(userId)) {
22849                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22850                            "User " + userId + " must be unlocked");
22851                }
22852            }
22853        }
22854
22855        final PackageStats stats = new PackageStats(null, -1);
22856        synchronized (mInstaller) {
22857            for (int userId : installedUserIds) {
22858                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22859                    freezer.close();
22860                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22861                            "Failed to measure package size");
22862                }
22863            }
22864        }
22865
22866        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22867                + stats.dataSize);
22868
22869        final long startFreeBytes = measurePath.getUsableSpace();
22870        final long sizeBytes;
22871        if (moveCompleteApp) {
22872            sizeBytes = stats.codeSize + stats.dataSize;
22873        } else {
22874            sizeBytes = stats.codeSize;
22875        }
22876
22877        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22878            freezer.close();
22879            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22880                    "Not enough free space to move");
22881        }
22882
22883        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22884
22885        final CountDownLatch installedLatch = new CountDownLatch(1);
22886        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22887            @Override
22888            public void onUserActionRequired(Intent intent) throws RemoteException {
22889                throw new IllegalStateException();
22890            }
22891
22892            @Override
22893            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22894                    Bundle extras) throws RemoteException {
22895                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22896                        + PackageManager.installStatusToString(returnCode, msg));
22897
22898                installedLatch.countDown();
22899                freezer.close();
22900
22901                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22902                switch (status) {
22903                    case PackageInstaller.STATUS_SUCCESS:
22904                        mMoveCallbacks.notifyStatusChanged(moveId,
22905                                PackageManager.MOVE_SUCCEEDED);
22906                        break;
22907                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22908                        mMoveCallbacks.notifyStatusChanged(moveId,
22909                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22910                        break;
22911                    default:
22912                        mMoveCallbacks.notifyStatusChanged(moveId,
22913                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22914                        break;
22915                }
22916            }
22917        };
22918
22919        final MoveInfo move;
22920        if (moveCompleteApp) {
22921            // Kick off a thread to report progress estimates
22922            new Thread() {
22923                @Override
22924                public void run() {
22925                    while (true) {
22926                        try {
22927                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22928                                break;
22929                            }
22930                        } catch (InterruptedException ignored) {
22931                        }
22932
22933                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22934                        final int progress = 10 + (int) MathUtils.constrain(
22935                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22936                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22937                    }
22938                }
22939            }.start();
22940
22941            final String dataAppName = codeFile.getName();
22942            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22943                    dataAppName, appId, seinfo, targetSdkVersion);
22944        } else {
22945            move = null;
22946        }
22947
22948        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22949
22950        final Message msg = mHandler.obtainMessage(INIT_COPY);
22951        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22952        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22953                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22954                packageAbiOverride, null /*grantedPermissions*/,
22955                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22956        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22957        msg.obj = params;
22958
22959        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22960                System.identityHashCode(msg.obj));
22961        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22962                System.identityHashCode(msg.obj));
22963
22964        mHandler.sendMessage(msg);
22965    }
22966
22967    @Override
22968    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22969        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22970
22971        final int realMoveId = mNextMoveId.getAndIncrement();
22972        final Bundle extras = new Bundle();
22973        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22974        mMoveCallbacks.notifyCreated(realMoveId, extras);
22975
22976        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22977            @Override
22978            public void onCreated(int moveId, Bundle extras) {
22979                // Ignored
22980            }
22981
22982            @Override
22983            public void onStatusChanged(int moveId, int status, long estMillis) {
22984                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22985            }
22986        };
22987
22988        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22989        storage.setPrimaryStorageUuid(volumeUuid, callback);
22990        return realMoveId;
22991    }
22992
22993    @Override
22994    public int getMoveStatus(int moveId) {
22995        mContext.enforceCallingOrSelfPermission(
22996                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22997        return mMoveCallbacks.mLastStatus.get(moveId);
22998    }
22999
23000    @Override
23001    public void registerMoveCallback(IPackageMoveObserver callback) {
23002        mContext.enforceCallingOrSelfPermission(
23003                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23004        mMoveCallbacks.register(callback);
23005    }
23006
23007    @Override
23008    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23009        mContext.enforceCallingOrSelfPermission(
23010                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23011        mMoveCallbacks.unregister(callback);
23012    }
23013
23014    @Override
23015    public boolean setInstallLocation(int loc) {
23016        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23017                null);
23018        if (getInstallLocation() == loc) {
23019            return true;
23020        }
23021        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23022                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23023            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23024                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23025            return true;
23026        }
23027        return false;
23028   }
23029
23030    @Override
23031    public int getInstallLocation() {
23032        // allow instant app access
23033        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23034                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23035                PackageHelper.APP_INSTALL_AUTO);
23036    }
23037
23038    /** Called by UserManagerService */
23039    void cleanUpUser(UserManagerService userManager, int userHandle) {
23040        synchronized (mPackages) {
23041            mDirtyUsers.remove(userHandle);
23042            mUserNeedsBadging.delete(userHandle);
23043            mSettings.removeUserLPw(userHandle);
23044            mPendingBroadcasts.remove(userHandle);
23045            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23046            removeUnusedPackagesLPw(userManager, userHandle);
23047        }
23048    }
23049
23050    /**
23051     * We're removing userHandle and would like to remove any downloaded packages
23052     * that are no longer in use by any other user.
23053     * @param userHandle the user being removed
23054     */
23055    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23056        final boolean DEBUG_CLEAN_APKS = false;
23057        int [] users = userManager.getUserIds();
23058        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23059        while (psit.hasNext()) {
23060            PackageSetting ps = psit.next();
23061            if (ps.pkg == null) {
23062                continue;
23063            }
23064            final String packageName = ps.pkg.packageName;
23065            // Skip over if system app
23066            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23067                continue;
23068            }
23069            if (DEBUG_CLEAN_APKS) {
23070                Slog.i(TAG, "Checking package " + packageName);
23071            }
23072            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23073            if (keep) {
23074                if (DEBUG_CLEAN_APKS) {
23075                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23076                }
23077            } else {
23078                for (int i = 0; i < users.length; i++) {
23079                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23080                        keep = true;
23081                        if (DEBUG_CLEAN_APKS) {
23082                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23083                                    + users[i]);
23084                        }
23085                        break;
23086                    }
23087                }
23088            }
23089            if (!keep) {
23090                if (DEBUG_CLEAN_APKS) {
23091                    Slog.i(TAG, "  Removing package " + packageName);
23092                }
23093                mHandler.post(new Runnable() {
23094                    public void run() {
23095                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23096                                userHandle, 0);
23097                    } //end run
23098                });
23099            }
23100        }
23101    }
23102
23103    /** Called by UserManagerService */
23104    void createNewUser(int userId, String[] disallowedPackages) {
23105        synchronized (mInstallLock) {
23106            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23107        }
23108        synchronized (mPackages) {
23109            scheduleWritePackageRestrictionsLocked(userId);
23110            scheduleWritePackageListLocked(userId);
23111            applyFactoryDefaultBrowserLPw(userId);
23112            primeDomainVerificationsLPw(userId);
23113        }
23114    }
23115
23116    void onNewUserCreated(final int userId) {
23117        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23118        synchronized(mPackages) {
23119            // If permission review for legacy apps is required, we represent
23120            // dagerous permissions for such apps as always granted runtime
23121            // permissions to keep per user flag state whether review is needed.
23122            // Hence, if a new user is added we have to propagate dangerous
23123            // permission grants for these legacy apps.
23124            if (mSettings.mPermissions.mPermissionReviewRequired) {
23125// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23126                mPermissionManager.updateAllPermissions(
23127                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23128                        mPermissionCallback);
23129            }
23130        }
23131    }
23132
23133    @Override
23134    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23135        mContext.enforceCallingOrSelfPermission(
23136                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23137                "Only package verification agents can read the verifier device identity");
23138
23139        synchronized (mPackages) {
23140            return mSettings.getVerifierDeviceIdentityLPw();
23141        }
23142    }
23143
23144    @Override
23145    public void setPermissionEnforced(String permission, boolean enforced) {
23146        // TODO: Now that we no longer change GID for storage, this should to away.
23147        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23148                "setPermissionEnforced");
23149        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23150            synchronized (mPackages) {
23151                if (mSettings.mReadExternalStorageEnforced == null
23152                        || mSettings.mReadExternalStorageEnforced != enforced) {
23153                    mSettings.mReadExternalStorageEnforced =
23154                            enforced ? Boolean.TRUE : Boolean.FALSE;
23155                    mSettings.writeLPr();
23156                }
23157            }
23158            // kill any non-foreground processes so we restart them and
23159            // grant/revoke the GID.
23160            final IActivityManager am = ActivityManager.getService();
23161            if (am != null) {
23162                final long token = Binder.clearCallingIdentity();
23163                try {
23164                    am.killProcessesBelowForeground("setPermissionEnforcement");
23165                } catch (RemoteException e) {
23166                } finally {
23167                    Binder.restoreCallingIdentity(token);
23168                }
23169            }
23170        } else {
23171            throw new IllegalArgumentException("No selective enforcement for " + permission);
23172        }
23173    }
23174
23175    @Override
23176    @Deprecated
23177    public boolean isPermissionEnforced(String permission) {
23178        // allow instant applications
23179        return true;
23180    }
23181
23182    @Override
23183    public boolean isStorageLow() {
23184        // allow instant applications
23185        final long token = Binder.clearCallingIdentity();
23186        try {
23187            final DeviceStorageMonitorInternal
23188                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23189            if (dsm != null) {
23190                return dsm.isMemoryLow();
23191            } else {
23192                return false;
23193            }
23194        } finally {
23195            Binder.restoreCallingIdentity(token);
23196        }
23197    }
23198
23199    @Override
23200    public IPackageInstaller getPackageInstaller() {
23201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23202            return null;
23203        }
23204        return mInstallerService;
23205    }
23206
23207    @Override
23208    public IArtManager getArtManager() {
23209        return mArtManagerService;
23210    }
23211
23212    private boolean userNeedsBadging(int userId) {
23213        int index = mUserNeedsBadging.indexOfKey(userId);
23214        if (index < 0) {
23215            final UserInfo userInfo;
23216            final long token = Binder.clearCallingIdentity();
23217            try {
23218                userInfo = sUserManager.getUserInfo(userId);
23219            } finally {
23220                Binder.restoreCallingIdentity(token);
23221            }
23222            final boolean b;
23223            if (userInfo != null && userInfo.isManagedProfile()) {
23224                b = true;
23225            } else {
23226                b = false;
23227            }
23228            mUserNeedsBadging.put(userId, b);
23229            return b;
23230        }
23231        return mUserNeedsBadging.valueAt(index);
23232    }
23233
23234    @Override
23235    public KeySet getKeySetByAlias(String packageName, String alias) {
23236        if (packageName == null || alias == null) {
23237            return null;
23238        }
23239        synchronized(mPackages) {
23240            final PackageParser.Package pkg = mPackages.get(packageName);
23241            if (pkg == null) {
23242                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23243                throw new IllegalArgumentException("Unknown package: " + packageName);
23244            }
23245            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23246            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23247                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23248                throw new IllegalArgumentException("Unknown package: " + packageName);
23249            }
23250            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23251            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23252        }
23253    }
23254
23255    @Override
23256    public KeySet getSigningKeySet(String packageName) {
23257        if (packageName == null) {
23258            return null;
23259        }
23260        synchronized(mPackages) {
23261            final int callingUid = Binder.getCallingUid();
23262            final int callingUserId = UserHandle.getUserId(callingUid);
23263            final PackageParser.Package pkg = mPackages.get(packageName);
23264            if (pkg == null) {
23265                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23266                throw new IllegalArgumentException("Unknown package: " + packageName);
23267            }
23268            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23269            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23270                // filter and pretend the package doesn't exist
23271                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23272                        + ", uid:" + callingUid);
23273                throw new IllegalArgumentException("Unknown package: " + packageName);
23274            }
23275            if (pkg.applicationInfo.uid != callingUid
23276                    && Process.SYSTEM_UID != callingUid) {
23277                throw new SecurityException("May not access signing KeySet of other apps.");
23278            }
23279            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23280            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23281        }
23282    }
23283
23284    @Override
23285    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23286        final int callingUid = Binder.getCallingUid();
23287        if (getInstantAppPackageName(callingUid) != null) {
23288            return false;
23289        }
23290        if (packageName == null || ks == null) {
23291            return false;
23292        }
23293        synchronized(mPackages) {
23294            final PackageParser.Package pkg = mPackages.get(packageName);
23295            if (pkg == null
23296                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23297                            UserHandle.getUserId(callingUid))) {
23298                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23299                throw new IllegalArgumentException("Unknown package: " + packageName);
23300            }
23301            IBinder ksh = ks.getToken();
23302            if (ksh instanceof KeySetHandle) {
23303                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23304                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23305            }
23306            return false;
23307        }
23308    }
23309
23310    @Override
23311    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23312        final int callingUid = Binder.getCallingUid();
23313        if (getInstantAppPackageName(callingUid) != null) {
23314            return false;
23315        }
23316        if (packageName == null || ks == null) {
23317            return false;
23318        }
23319        synchronized(mPackages) {
23320            final PackageParser.Package pkg = mPackages.get(packageName);
23321            if (pkg == null
23322                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23323                            UserHandle.getUserId(callingUid))) {
23324                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23325                throw new IllegalArgumentException("Unknown package: " + packageName);
23326            }
23327            IBinder ksh = ks.getToken();
23328            if (ksh instanceof KeySetHandle) {
23329                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23330                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23331            }
23332            return false;
23333        }
23334    }
23335
23336    private void deletePackageIfUnusedLPr(final String packageName) {
23337        PackageSetting ps = mSettings.mPackages.get(packageName);
23338        if (ps == null) {
23339            return;
23340        }
23341        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23342            // TODO Implement atomic delete if package is unused
23343            // It is currently possible that the package will be deleted even if it is installed
23344            // after this method returns.
23345            mHandler.post(new Runnable() {
23346                public void run() {
23347                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23348                            0, PackageManager.DELETE_ALL_USERS);
23349                }
23350            });
23351        }
23352    }
23353
23354    /**
23355     * Check and throw if the given before/after packages would be considered a
23356     * downgrade.
23357     */
23358    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23359            throws PackageManagerException {
23360        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23361            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23362                    "Update version code " + after.versionCode + " is older than current "
23363                    + before.getLongVersionCode());
23364        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23365            if (after.baseRevisionCode < before.baseRevisionCode) {
23366                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23367                        "Update base revision code " + after.baseRevisionCode
23368                        + " is older than current " + before.baseRevisionCode);
23369            }
23370
23371            if (!ArrayUtils.isEmpty(after.splitNames)) {
23372                for (int i = 0; i < after.splitNames.length; i++) {
23373                    final String splitName = after.splitNames[i];
23374                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23375                    if (j != -1) {
23376                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23377                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23378                                    "Update split " + splitName + " revision code "
23379                                    + after.splitRevisionCodes[i] + " is older than current "
23380                                    + before.splitRevisionCodes[j]);
23381                        }
23382                    }
23383                }
23384            }
23385        }
23386    }
23387
23388    private static class MoveCallbacks extends Handler {
23389        private static final int MSG_CREATED = 1;
23390        private static final int MSG_STATUS_CHANGED = 2;
23391
23392        private final RemoteCallbackList<IPackageMoveObserver>
23393                mCallbacks = new RemoteCallbackList<>();
23394
23395        private final SparseIntArray mLastStatus = new SparseIntArray();
23396
23397        public MoveCallbacks(Looper looper) {
23398            super(looper);
23399        }
23400
23401        public void register(IPackageMoveObserver callback) {
23402            mCallbacks.register(callback);
23403        }
23404
23405        public void unregister(IPackageMoveObserver callback) {
23406            mCallbacks.unregister(callback);
23407        }
23408
23409        @Override
23410        public void handleMessage(Message msg) {
23411            final SomeArgs args = (SomeArgs) msg.obj;
23412            final int n = mCallbacks.beginBroadcast();
23413            for (int i = 0; i < n; i++) {
23414                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23415                try {
23416                    invokeCallback(callback, msg.what, args);
23417                } catch (RemoteException ignored) {
23418                }
23419            }
23420            mCallbacks.finishBroadcast();
23421            args.recycle();
23422        }
23423
23424        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23425                throws RemoteException {
23426            switch (what) {
23427                case MSG_CREATED: {
23428                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23429                    break;
23430                }
23431                case MSG_STATUS_CHANGED: {
23432                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23433                    break;
23434                }
23435            }
23436        }
23437
23438        private void notifyCreated(int moveId, Bundle extras) {
23439            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23440
23441            final SomeArgs args = SomeArgs.obtain();
23442            args.argi1 = moveId;
23443            args.arg2 = extras;
23444            obtainMessage(MSG_CREATED, args).sendToTarget();
23445        }
23446
23447        private void notifyStatusChanged(int moveId, int status) {
23448            notifyStatusChanged(moveId, status, -1);
23449        }
23450
23451        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23452            Slog.v(TAG, "Move " + moveId + " status " + status);
23453
23454            final SomeArgs args = SomeArgs.obtain();
23455            args.argi1 = moveId;
23456            args.argi2 = status;
23457            args.arg3 = estMillis;
23458            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23459
23460            synchronized (mLastStatus) {
23461                mLastStatus.put(moveId, status);
23462            }
23463        }
23464    }
23465
23466    private final static class OnPermissionChangeListeners extends Handler {
23467        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23468
23469        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23470                new RemoteCallbackList<>();
23471
23472        public OnPermissionChangeListeners(Looper looper) {
23473            super(looper);
23474        }
23475
23476        @Override
23477        public void handleMessage(Message msg) {
23478            switch (msg.what) {
23479                case MSG_ON_PERMISSIONS_CHANGED: {
23480                    final int uid = msg.arg1;
23481                    handleOnPermissionsChanged(uid);
23482                } break;
23483            }
23484        }
23485
23486        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23487            mPermissionListeners.register(listener);
23488
23489        }
23490
23491        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23492            mPermissionListeners.unregister(listener);
23493        }
23494
23495        public void onPermissionsChanged(int uid) {
23496            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23497                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23498            }
23499        }
23500
23501        private void handleOnPermissionsChanged(int uid) {
23502            final int count = mPermissionListeners.beginBroadcast();
23503            try {
23504                for (int i = 0; i < count; i++) {
23505                    IOnPermissionsChangeListener callback = mPermissionListeners
23506                            .getBroadcastItem(i);
23507                    try {
23508                        callback.onPermissionsChanged(uid);
23509                    } catch (RemoteException e) {
23510                        Log.e(TAG, "Permission listener is dead", e);
23511                    }
23512                }
23513            } finally {
23514                mPermissionListeners.finishBroadcast();
23515            }
23516        }
23517    }
23518
23519    private class PackageManagerNative extends IPackageManagerNative.Stub {
23520        @Override
23521        public String[] getNamesForUids(int[] uids) throws RemoteException {
23522            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23523            // massage results so they can be parsed by the native binder
23524            for (int i = results.length - 1; i >= 0; --i) {
23525                if (results[i] == null) {
23526                    results[i] = "";
23527                }
23528            }
23529            return results;
23530        }
23531
23532        // NB: this differentiates between preloads and sideloads
23533        @Override
23534        public String getInstallerForPackage(String packageName) throws RemoteException {
23535            final String installerName = getInstallerPackageName(packageName);
23536            if (!TextUtils.isEmpty(installerName)) {
23537                return installerName;
23538            }
23539            // differentiate between preload and sideload
23540            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23541            ApplicationInfo appInfo = getApplicationInfo(packageName,
23542                                    /*flags*/ 0,
23543                                    /*userId*/ callingUser);
23544            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23545                return "preload";
23546            }
23547            return "";
23548        }
23549
23550        @Override
23551        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23552            try {
23553                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23554                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23555                if (pInfo != null) {
23556                    return pInfo.getLongVersionCode();
23557                }
23558            } catch (Exception e) {
23559            }
23560            return 0;
23561        }
23562    }
23563
23564    private class PackageManagerInternalImpl extends PackageManagerInternal {
23565        @Override
23566        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23567                int flagValues, int userId) {
23568            PackageManagerService.this.updatePermissionFlags(
23569                    permName, packageName, flagMask, flagValues, userId);
23570        }
23571
23572        @Override
23573        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23574            SigningDetails sd = getSigningDetails(packageName);
23575            if (sd == null) {
23576                return false;
23577            }
23578            return sd.hasSha256Certificate(restoringFromSigHash,
23579                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23580        }
23581
23582        @Override
23583        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23584            SigningDetails sd = getSigningDetails(packageName);
23585            if (sd == null) {
23586                return false;
23587            }
23588            return sd.hasCertificate(restoringFromSig,
23589                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23590        }
23591
23592        @Override
23593        public boolean hasSignatureCapability(int serverUid, int clientUid,
23594                @SigningDetails.CertCapabilities int capability) {
23595            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23596            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23597            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23598                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23599
23600        }
23601
23602        private SigningDetails getSigningDetails(@NonNull String packageName) {
23603            synchronized (mPackages) {
23604                PackageParser.Package p = mPackages.get(packageName);
23605                if (p == null) {
23606                    return null;
23607                }
23608                return p.mSigningDetails;
23609            }
23610        }
23611
23612        private SigningDetails getSigningDetails(int uid) {
23613            synchronized (mPackages) {
23614                final int appId = UserHandle.getAppId(uid);
23615                final Object obj = mSettings.getUserIdLPr(appId);
23616                if (obj != null) {
23617                    if (obj instanceof SharedUserSetting) {
23618                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23619                    } else if (obj instanceof PackageSetting) {
23620                        final PackageSetting ps = (PackageSetting) obj;
23621                        return ps.signatures.mSigningDetails;
23622                    }
23623                }
23624                return SigningDetails.UNKNOWN;
23625            }
23626        }
23627
23628        @Override
23629        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23630            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23631        }
23632
23633        @Override
23634        public boolean isInstantApp(String packageName, int userId) {
23635            return PackageManagerService.this.isInstantApp(packageName, userId);
23636        }
23637
23638        @Override
23639        public String getInstantAppPackageName(int uid) {
23640            return PackageManagerService.this.getInstantAppPackageName(uid);
23641        }
23642
23643        @Override
23644        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23645            synchronized (mPackages) {
23646                return PackageManagerService.this.filterAppAccessLPr(
23647                        (PackageSetting) pkg.mExtras, callingUid, userId);
23648            }
23649        }
23650
23651        @Override
23652        public PackageParser.Package getPackage(String packageName) {
23653            synchronized (mPackages) {
23654                packageName = resolveInternalPackageNameLPr(
23655                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23656                return mPackages.get(packageName);
23657            }
23658        }
23659
23660        @Override
23661        public PackageList getPackageList(PackageListObserver observer) {
23662            synchronized (mPackages) {
23663                final int N = mPackages.size();
23664                final ArrayList<String> list = new ArrayList<>(N);
23665                for (int i = 0; i < N; i++) {
23666                    list.add(mPackages.keyAt(i));
23667                }
23668                final PackageList packageList = new PackageList(list, observer);
23669                if (observer != null) {
23670                    mPackageListObservers.add(packageList);
23671                }
23672                return packageList;
23673            }
23674        }
23675
23676        @Override
23677        public void removePackageListObserver(PackageListObserver observer) {
23678            synchronized (mPackages) {
23679                mPackageListObservers.remove(observer);
23680            }
23681        }
23682
23683        @Override
23684        public PackageParser.Package getDisabledPackage(String packageName) {
23685            synchronized (mPackages) {
23686                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23687                return (ps != null) ? ps.pkg : null;
23688            }
23689        }
23690
23691        @Override
23692        public String getKnownPackageName(int knownPackage, int userId) {
23693            switch(knownPackage) {
23694                case PackageManagerInternal.PACKAGE_BROWSER:
23695                    return getDefaultBrowserPackageName(userId);
23696                case PackageManagerInternal.PACKAGE_INSTALLER:
23697                    return mRequiredInstallerPackage;
23698                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23699                    return mSetupWizardPackage;
23700                case PackageManagerInternal.PACKAGE_SYSTEM:
23701                    return "android";
23702                case PackageManagerInternal.PACKAGE_VERIFIER:
23703                    return mRequiredVerifierPackage;
23704                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23705                    return mSystemTextClassifierPackage;
23706            }
23707            return null;
23708        }
23709
23710        @Override
23711        public boolean isResolveActivityComponent(ComponentInfo component) {
23712            return mResolveActivity.packageName.equals(component.packageName)
23713                    && mResolveActivity.name.equals(component.name);
23714        }
23715
23716        @Override
23717        public void setLocationPackagesProvider(PackagesProvider provider) {
23718            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23719        }
23720
23721        @Override
23722        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23723            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23724        }
23725
23726        @Override
23727        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23728            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23729        }
23730
23731        @Override
23732        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23733            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23734        }
23735
23736        @Override
23737        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23738            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23739        }
23740
23741        @Override
23742        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23743            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23744        }
23745
23746        @Override
23747        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23748            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23749        }
23750
23751        @Override
23752        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23753            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23754        }
23755
23756        @Override
23757        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23758            synchronized (mPackages) {
23759                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23760            }
23761            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23762        }
23763
23764        @Override
23765        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23766            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23767                    packageName, userId);
23768        }
23769
23770        @Override
23771        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23772            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23773                    packageName, userId);
23774        }
23775
23776        @Override
23777        public void setKeepUninstalledPackages(final List<String> packageList) {
23778            Preconditions.checkNotNull(packageList);
23779            List<String> removedFromList = null;
23780            synchronized (mPackages) {
23781                if (mKeepUninstalledPackages != null) {
23782                    final int packagesCount = mKeepUninstalledPackages.size();
23783                    for (int i = 0; i < packagesCount; i++) {
23784                        String oldPackage = mKeepUninstalledPackages.get(i);
23785                        if (packageList != null && packageList.contains(oldPackage)) {
23786                            continue;
23787                        }
23788                        if (removedFromList == null) {
23789                            removedFromList = new ArrayList<>();
23790                        }
23791                        removedFromList.add(oldPackage);
23792                    }
23793                }
23794                mKeepUninstalledPackages = new ArrayList<>(packageList);
23795                if (removedFromList != null) {
23796                    final int removedCount = removedFromList.size();
23797                    for (int i = 0; i < removedCount; i++) {
23798                        deletePackageIfUnusedLPr(removedFromList.get(i));
23799                    }
23800                }
23801            }
23802        }
23803
23804        @Override
23805        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23806            synchronized (mPackages) {
23807                return mPermissionManager.isPermissionsReviewRequired(
23808                        mPackages.get(packageName), userId);
23809            }
23810        }
23811
23812        @Override
23813        public PackageInfo getPackageInfo(
23814                String packageName, int flags, int filterCallingUid, int userId) {
23815            return PackageManagerService.this
23816                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23817                            flags, filterCallingUid, userId);
23818        }
23819
23820        @Override
23821        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23822            synchronized (mPackages) {
23823                final PackageSetting ps = mSettings.mPackages.get(packageName);
23824                PersistableBundle launcherExtras = null;
23825                if (ps != null) {
23826                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23827                }
23828                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23829            }
23830        }
23831
23832        @Override
23833        public boolean isPackageSuspended(String packageName, int userId) {
23834            synchronized (mPackages) {
23835                final PackageSetting ps = mSettings.mPackages.get(packageName);
23836                return (ps != null) ? ps.getSuspended(userId) : false;
23837            }
23838        }
23839
23840        @Override
23841        public String getSuspendingPackage(String suspendedPackage, int userId) {
23842            synchronized (mPackages) {
23843                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23844                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23845            }
23846        }
23847
23848        @Override
23849        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23850            synchronized (mPackages) {
23851                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23852                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23853            }
23854        }
23855
23856        @Override
23857        public int getPackageUid(String packageName, int flags, int userId) {
23858            return PackageManagerService.this
23859                    .getPackageUid(packageName, flags, userId);
23860        }
23861
23862        @Override
23863        public ApplicationInfo getApplicationInfo(
23864                String packageName, int flags, int filterCallingUid, int userId) {
23865            return PackageManagerService.this
23866                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23867        }
23868
23869        @Override
23870        public ActivityInfo getActivityInfo(
23871                ComponentName component, int flags, int filterCallingUid, int userId) {
23872            return PackageManagerService.this
23873                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23874        }
23875
23876        @Override
23877        public List<ResolveInfo> queryIntentActivities(
23878                Intent intent, int flags, int filterCallingUid, int userId) {
23879            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23880            return PackageManagerService.this
23881                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23882                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23883        }
23884
23885        @Override
23886        public List<ResolveInfo> queryIntentServices(
23887                Intent intent, int flags, int callingUid, int userId) {
23888            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23889            return PackageManagerService.this
23890                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23891                            false);
23892        }
23893
23894        @Override
23895        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23896                int userId) {
23897            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23898        }
23899
23900        @Override
23901        public ComponentName getDefaultHomeActivity(int userId) {
23902            return PackageManagerService.this.getDefaultHomeActivity(userId);
23903        }
23904
23905        @Override
23906        public void setDeviceAndProfileOwnerPackages(
23907                int deviceOwnerUserId, String deviceOwnerPackage,
23908                SparseArray<String> profileOwnerPackages) {
23909            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23910                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23911        }
23912
23913        @Override
23914        public boolean isPackageDataProtected(int userId, String packageName) {
23915            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23916        }
23917
23918        @Override
23919        public boolean isPackageStateProtected(String packageName, int userId) {
23920            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23921        }
23922
23923        @Override
23924        public boolean isPackageEphemeral(int userId, String packageName) {
23925            synchronized (mPackages) {
23926                final PackageSetting ps = mSettings.mPackages.get(packageName);
23927                return ps != null ? ps.getInstantApp(userId) : false;
23928            }
23929        }
23930
23931        @Override
23932        public boolean wasPackageEverLaunched(String packageName, int userId) {
23933            synchronized (mPackages) {
23934                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23935            }
23936        }
23937
23938        @Override
23939        public void grantRuntimePermission(String packageName, String permName, int userId,
23940                boolean overridePolicy) {
23941            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23942                    permName, packageName, overridePolicy, getCallingUid(), userId,
23943                    mPermissionCallback);
23944        }
23945
23946        @Override
23947        public void revokeRuntimePermission(String packageName, String permName, int userId,
23948                boolean overridePolicy) {
23949            mPermissionManager.revokeRuntimePermission(
23950                    permName, packageName, overridePolicy, getCallingUid(), userId,
23951                    mPermissionCallback);
23952        }
23953
23954        @Override
23955        public String getNameForUid(int uid) {
23956            return PackageManagerService.this.getNameForUid(uid);
23957        }
23958
23959        @Override
23960        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23961                Intent origIntent, String resolvedType, String callingPackage,
23962                Bundle verificationBundle, int userId) {
23963            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23964                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23965                    userId);
23966        }
23967
23968        @Override
23969        public void grantEphemeralAccess(int userId, Intent intent,
23970                int targetAppId, int ephemeralAppId) {
23971            synchronized (mPackages) {
23972                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23973                        targetAppId, ephemeralAppId);
23974            }
23975        }
23976
23977        @Override
23978        public boolean isInstantAppInstallerComponent(ComponentName component) {
23979            synchronized (mPackages) {
23980                return mInstantAppInstallerActivity != null
23981                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23982            }
23983        }
23984
23985        @Override
23986        public void pruneInstantApps() {
23987            mInstantAppRegistry.pruneInstantApps();
23988        }
23989
23990        @Override
23991        public String getSetupWizardPackageName() {
23992            return mSetupWizardPackage;
23993        }
23994
23995        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23996            if (policy != null) {
23997                mExternalSourcesPolicy = policy;
23998            }
23999        }
24000
24001        @Override
24002        public boolean isPackagePersistent(String packageName) {
24003            synchronized (mPackages) {
24004                PackageParser.Package pkg = mPackages.get(packageName);
24005                return pkg != null
24006                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24007                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24008                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24009                        : false;
24010            }
24011        }
24012
24013        @Override
24014        public boolean isLegacySystemApp(Package pkg) {
24015            synchronized (mPackages) {
24016                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24017                return mPromoteSystemApps
24018                        && ps.isSystem()
24019                        && mExistingSystemPackages.contains(ps.name);
24020            }
24021        }
24022
24023        @Override
24024        public List<PackageInfo> getOverlayPackages(int userId) {
24025            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24026            synchronized (mPackages) {
24027                for (PackageParser.Package p : mPackages.values()) {
24028                    if (p.mOverlayTarget != null) {
24029                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24030                        if (pkg != null) {
24031                            overlayPackages.add(pkg);
24032                        }
24033                    }
24034                }
24035            }
24036            return overlayPackages;
24037        }
24038
24039        @Override
24040        public List<String> getTargetPackageNames(int userId) {
24041            List<String> targetPackages = new ArrayList<>();
24042            synchronized (mPackages) {
24043                for (PackageParser.Package p : mPackages.values()) {
24044                    if (p.mOverlayTarget == null) {
24045                        targetPackages.add(p.packageName);
24046                    }
24047                }
24048            }
24049            return targetPackages;
24050        }
24051
24052        @Override
24053        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24054                @Nullable List<String> overlayPackageNames) {
24055            synchronized (mPackages) {
24056                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24057                    Slog.e(TAG, "failed to find package " + targetPackageName);
24058                    return false;
24059                }
24060                ArrayList<String> overlayPaths = null;
24061                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24062                    final int N = overlayPackageNames.size();
24063                    overlayPaths = new ArrayList<>(N);
24064                    for (int i = 0; i < N; i++) {
24065                        final String packageName = overlayPackageNames.get(i);
24066                        final PackageParser.Package pkg = mPackages.get(packageName);
24067                        if (pkg == null) {
24068                            Slog.e(TAG, "failed to find package " + packageName);
24069                            return false;
24070                        }
24071                        overlayPaths.add(pkg.baseCodePath);
24072                    }
24073                }
24074
24075                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24076                ps.setOverlayPaths(overlayPaths, userId);
24077                return true;
24078            }
24079        }
24080
24081        @Override
24082        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24083                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24084            return resolveIntentInternal(
24085                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24086        }
24087
24088        @Override
24089        public ResolveInfo resolveService(Intent intent, String resolvedType,
24090                int flags, int userId, int callingUid) {
24091            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24092        }
24093
24094        @Override
24095        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24096            return PackageManagerService.this.resolveContentProviderInternal(
24097                    name, flags, userId);
24098        }
24099
24100        @Override
24101        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24102            synchronized (mPackages) {
24103                mIsolatedOwners.put(isolatedUid, ownerUid);
24104            }
24105        }
24106
24107        @Override
24108        public void removeIsolatedUid(int isolatedUid) {
24109            synchronized (mPackages) {
24110                mIsolatedOwners.delete(isolatedUid);
24111            }
24112        }
24113
24114        @Override
24115        public int getUidTargetSdkVersion(int uid) {
24116            synchronized (mPackages) {
24117                return getUidTargetSdkVersionLockedLPr(uid);
24118            }
24119        }
24120
24121        @Override
24122        public int getPackageTargetSdkVersion(String packageName) {
24123            synchronized (mPackages) {
24124                return getPackageTargetSdkVersionLockedLPr(packageName);
24125            }
24126        }
24127
24128        @Override
24129        public boolean canAccessInstantApps(int callingUid, int userId) {
24130            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24131        }
24132
24133        @Override
24134        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24135            synchronized (mPackages) {
24136                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24137                return !PackageManagerService.this.filterAppAccessLPr(
24138                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24139            }
24140        }
24141
24142        @Override
24143        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24144            synchronized (mPackages) {
24145                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24146            }
24147        }
24148
24149        @Override
24150        public void notifyPackageUse(String packageName, int reason) {
24151            synchronized (mPackages) {
24152                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24153            }
24154        }
24155    }
24156
24157    @Override
24158    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24159        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24160        synchronized (mPackages) {
24161            final long identity = Binder.clearCallingIdentity();
24162            try {
24163                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24164                        packageNames, userId);
24165            } finally {
24166                Binder.restoreCallingIdentity(identity);
24167            }
24168        }
24169    }
24170
24171    @Override
24172    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24173        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24174        synchronized (mPackages) {
24175            final long identity = Binder.clearCallingIdentity();
24176            try {
24177                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24178                        packageNames, userId);
24179            } finally {
24180                Binder.restoreCallingIdentity(identity);
24181            }
24182        }
24183    }
24184
24185    @Override
24186    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24187            String[] packageNames, int userId) {
24188        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24189        synchronized (mPackages) {
24190            Binder.withCleanCallingIdentity( () -> {
24191                mDefaultPermissionPolicy.
24192                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24193                                packageNames, userId);
24194            });
24195        }
24196    }
24197
24198    @Override
24199    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24200            String[] packageNames, int userId) {
24201        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24202        synchronized (mPackages) {
24203            Binder.withCleanCallingIdentity( () -> {
24204                mDefaultPermissionPolicy.
24205                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24206                                packageNames, userId);
24207            });
24208        }
24209    }
24210
24211    @Override
24212    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24213        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24214        synchronized (mPackages) {
24215            final long identity = Binder.clearCallingIdentity();
24216            try {
24217                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24218                        packageName, userId);
24219            } finally {
24220                Binder.restoreCallingIdentity(identity);
24221            }
24222        }
24223    }
24224
24225    @Override
24226    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24227        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24228        synchronized (mPackages) {
24229            final long identity = Binder.clearCallingIdentity();
24230            try {
24231                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24232            } finally {
24233                Binder.restoreCallingIdentity(identity);
24234            }
24235        }
24236    }
24237
24238    private static void enforceSystemOrPhoneCaller(String tag) {
24239        int callingUid = Binder.getCallingUid();
24240        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24241            throw new SecurityException(
24242                    "Cannot call " + tag + " from UID " + callingUid);
24243        }
24244    }
24245
24246    boolean isHistoricalPackageUsageAvailable() {
24247        return mPackageUsage.isHistoricalPackageUsageAvailable();
24248    }
24249
24250    /**
24251     * Return a <b>copy</b> of the collection of packages known to the package manager.
24252     * @return A copy of the values of mPackages.
24253     */
24254    Collection<PackageParser.Package> getPackages() {
24255        synchronized (mPackages) {
24256            return new ArrayList<>(mPackages.values());
24257        }
24258    }
24259
24260    /**
24261     * Logs process start information (including base APK hash) to the security log.
24262     * @hide
24263     */
24264    @Override
24265    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24266            String apkFile, int pid) {
24267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24268            return;
24269        }
24270        if (!SecurityLog.isLoggingEnabled()) {
24271            return;
24272        }
24273        Bundle data = new Bundle();
24274        data.putLong("startTimestamp", System.currentTimeMillis());
24275        data.putString("processName", processName);
24276        data.putInt("uid", uid);
24277        data.putString("seinfo", seinfo);
24278        data.putString("apkFile", apkFile);
24279        data.putInt("pid", pid);
24280        Message msg = mProcessLoggingHandler.obtainMessage(
24281                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24282        msg.setData(data);
24283        mProcessLoggingHandler.sendMessage(msg);
24284    }
24285
24286    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24287        return mCompilerStats.getPackageStats(pkgName);
24288    }
24289
24290    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24291        return getOrCreateCompilerPackageStats(pkg.packageName);
24292    }
24293
24294    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24295        return mCompilerStats.getOrCreatePackageStats(pkgName);
24296    }
24297
24298    public void deleteCompilerPackageStats(String pkgName) {
24299        mCompilerStats.deletePackageStats(pkgName);
24300    }
24301
24302    @Override
24303    public int getInstallReason(String packageName, int userId) {
24304        final int callingUid = Binder.getCallingUid();
24305        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24306                true /* requireFullPermission */, false /* checkShell */,
24307                "get install reason");
24308        synchronized (mPackages) {
24309            final PackageSetting ps = mSettings.mPackages.get(packageName);
24310            if (filterAppAccessLPr(ps, callingUid, userId)) {
24311                return PackageManager.INSTALL_REASON_UNKNOWN;
24312            }
24313            if (ps != null) {
24314                return ps.getInstallReason(userId);
24315            }
24316        }
24317        return PackageManager.INSTALL_REASON_UNKNOWN;
24318    }
24319
24320    @Override
24321    public boolean canRequestPackageInstalls(String packageName, int userId) {
24322        return canRequestPackageInstallsInternal(packageName, 0, userId,
24323                true /* throwIfPermNotDeclared*/);
24324    }
24325
24326    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24327            boolean throwIfPermNotDeclared) {
24328        int callingUid = Binder.getCallingUid();
24329        int uid = getPackageUid(packageName, 0, userId);
24330        if (callingUid != uid && callingUid != Process.ROOT_UID
24331                && callingUid != Process.SYSTEM_UID) {
24332            throw new SecurityException(
24333                    "Caller uid " + callingUid + " does not own package " + packageName);
24334        }
24335        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24336        if (info == null) {
24337            return false;
24338        }
24339        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24340            return false;
24341        }
24342        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24343        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24344        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24345            if (throwIfPermNotDeclared) {
24346                throw new SecurityException("Need to declare " + appOpPermission
24347                        + " to call this api");
24348            } else {
24349                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24350                return false;
24351            }
24352        }
24353        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24354            return false;
24355        }
24356        if (mExternalSourcesPolicy != null) {
24357            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24358            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24359                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24360            }
24361        }
24362        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24363    }
24364
24365    @Override
24366    public ComponentName getInstantAppResolverSettingsComponent() {
24367        return mInstantAppResolverSettingsComponent;
24368    }
24369
24370    @Override
24371    public ComponentName getInstantAppInstallerComponent() {
24372        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24373            return null;
24374        }
24375        return mInstantAppInstallerActivity == null
24376                ? null : mInstantAppInstallerActivity.getComponentName();
24377    }
24378
24379    @Override
24380    public String getInstantAppAndroidId(String packageName, int userId) {
24381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24382                "getInstantAppAndroidId");
24383        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24384                true /* requireFullPermission */, false /* checkShell */,
24385                "getInstantAppAndroidId");
24386        // Make sure the target is an Instant App.
24387        if (!isInstantApp(packageName, userId)) {
24388            return null;
24389        }
24390        synchronized (mPackages) {
24391            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24392        }
24393    }
24394
24395    boolean canHaveOatDir(String packageName) {
24396        synchronized (mPackages) {
24397            PackageParser.Package p = mPackages.get(packageName);
24398            if (p == null) {
24399                return false;
24400            }
24401            return p.canHaveOatDir();
24402        }
24403    }
24404
24405    private String getOatDir(PackageParser.Package pkg) {
24406        if (!pkg.canHaveOatDir()) {
24407            return null;
24408        }
24409        File codePath = new File(pkg.codePath);
24410        if (codePath.isDirectory()) {
24411            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24412        }
24413        return null;
24414    }
24415
24416    void deleteOatArtifactsOfPackage(String packageName) {
24417        final String[] instructionSets;
24418        final List<String> codePaths;
24419        final String oatDir;
24420        final PackageParser.Package pkg;
24421        synchronized (mPackages) {
24422            pkg = mPackages.get(packageName);
24423        }
24424        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24425        codePaths = pkg.getAllCodePaths();
24426        oatDir = getOatDir(pkg);
24427
24428        for (String codePath : codePaths) {
24429            for (String isa : instructionSets) {
24430                try {
24431                    mInstaller.deleteOdex(codePath, isa, oatDir);
24432                } catch (InstallerException e) {
24433                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24434                }
24435            }
24436        }
24437    }
24438
24439    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24440        Set<String> unusedPackages = new HashSet<>();
24441        long currentTimeInMillis = System.currentTimeMillis();
24442        synchronized (mPackages) {
24443            for (PackageParser.Package pkg : mPackages.values()) {
24444                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24445                if (ps == null) {
24446                    continue;
24447                }
24448                PackageDexUsage.PackageUseInfo packageUseInfo =
24449                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24450                if (PackageManagerServiceUtils
24451                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24452                                downgradeTimeThresholdMillis, packageUseInfo,
24453                                pkg.getLatestPackageUseTimeInMills(),
24454                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24455                    unusedPackages.add(pkg.packageName);
24456                }
24457            }
24458        }
24459        return unusedPackages;
24460    }
24461
24462    @Override
24463    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24464            int userId) {
24465        final int callingUid = Binder.getCallingUid();
24466        final int callingAppId = UserHandle.getAppId(callingUid);
24467
24468        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24469                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24470
24471        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24472                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24473            throw new SecurityException("Caller must have the "
24474                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24475        }
24476
24477        synchronized(mPackages) {
24478            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24479            scheduleWritePackageRestrictionsLocked(userId);
24480        }
24481    }
24482
24483    @Nullable
24484    @Override
24485    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24486        final int callingUid = Binder.getCallingUid();
24487        final int callingAppId = UserHandle.getAppId(callingUid);
24488
24489        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24490                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24491
24492        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24493                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24494            throw new SecurityException("Caller must have the "
24495                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24496        }
24497
24498        synchronized(mPackages) {
24499            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24500        }
24501    }
24502
24503    @Override
24504    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24505        final int callingUid = Binder.getCallingUid();
24506        final int callingAppId = UserHandle.getAppId(callingUid);
24507
24508        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24509                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24510
24511        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24512                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24513            throw new SecurityException("Caller must have the "
24514                    + MANAGE_DEVICE_ADMINS + " permission.");
24515        }
24516
24517        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24518    }
24519}
24520
24521interface PackageSender {
24522    /**
24523     * @param userIds User IDs where the action occurred on a full application
24524     * @param instantUserIds User IDs where the action occurred on an instant application
24525     */
24526    void sendPackageBroadcast(final String action, final String pkg,
24527        final Bundle extras, final int flags, final String targetPkg,
24528        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24529    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24530        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24531    void notifyPackageAdded(String packageName);
24532    void notifyPackageRemoved(String packageName);
24533}
24534