PackageManagerService.java revision cca0dc316cd67fba59721f2801d4329bc098e0fd
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.Process;
217import android.os.RemoteCallbackList;
218import android.os.RemoteException;
219import android.os.ResultReceiver;
220import android.os.SELinux;
221import android.os.ServiceManager;
222import android.os.ShellCallback;
223import android.os.SystemClock;
224import android.os.SystemProperties;
225import android.os.Trace;
226import android.os.UserHandle;
227import android.os.UserManager;
228import android.os.UserManagerInternal;
229import android.os.storage.IStorageManager;
230import android.os.storage.StorageEventListener;
231import android.os.storage.StorageManager;
232import android.os.storage.StorageManagerInternal;
233import android.os.storage.VolumeInfo;
234import android.os.storage.VolumeRecord;
235import android.provider.Settings.Global;
236import android.provider.Settings.Secure;
237import android.security.KeyStore;
238import android.security.SystemKeyStore;
239import android.service.pm.PackageServiceDumpProto;
240import android.system.ErrnoException;
241import android.system.Os;
242import android.text.TextUtils;
243import android.text.format.DateUtils;
244import android.util.ArrayMap;
245import android.util.ArraySet;
246import android.util.Base64;
247import android.util.ByteStringUtils;
248import android.util.DisplayMetrics;
249import android.util.EventLog;
250import android.util.ExceptionUtils;
251import android.util.Log;
252import android.util.LogPrinter;
253import android.util.LongSparseArray;
254import android.util.LongSparseLongArray;
255import android.util.MathUtils;
256import android.util.PackageUtils;
257import android.util.Pair;
258import android.util.PrintStreamPrinter;
259import android.util.Slog;
260import android.util.SparseArray;
261import android.util.SparseBooleanArray;
262import android.util.SparseIntArray;
263import android.util.TimingsTraceLog;
264import android.util.Xml;
265import android.util.jar.StrictJarFile;
266import android.util.proto.ProtoOutputStream;
267import android.view.Display;
268
269import com.android.internal.R;
270import com.android.internal.annotations.GuardedBy;
271import com.android.internal.app.IMediaContainerService;
272import com.android.internal.app.ResolverActivity;
273import com.android.internal.content.NativeLibraryHelper;
274import com.android.internal.content.PackageHelper;
275import com.android.internal.logging.MetricsLogger;
276import com.android.internal.os.IParcelFileDescriptorFactory;
277import com.android.internal.os.SomeArgs;
278import com.android.internal.os.Zygote;
279import com.android.internal.telephony.CarrierAppUtils;
280import com.android.internal.util.ArrayUtils;
281import com.android.internal.util.ConcurrentUtils;
282import com.android.internal.util.DumpUtils;
283import com.android.internal.util.FastXmlSerializer;
284import com.android.internal.util.IndentingPrintWriter;
285import com.android.internal.util.Preconditions;
286import com.android.internal.util.XmlUtils;
287import com.android.server.AttributeCache;
288import com.android.server.DeviceIdleController;
289import com.android.server.EventLogTags;
290import com.android.server.FgThread;
291import com.android.server.IntentResolver;
292import com.android.server.LocalServices;
293import com.android.server.LockGuard;
294import com.android.server.ServiceThread;
295import com.android.server.SystemConfig;
296import com.android.server.SystemServerInitThreadPool;
297import com.android.server.Watchdog;
298import com.android.server.net.NetworkPolicyManagerInternal;
299import com.android.server.pm.Installer.InstallerException;
300import com.android.server.pm.Settings.DatabaseVersion;
301import com.android.server.pm.Settings.VersionInfo;
302import com.android.server.pm.dex.ArtManagerService;
303import com.android.server.pm.dex.DexLogger;
304import com.android.server.pm.dex.DexManager;
305import com.android.server.pm.dex.DexoptOptions;
306import com.android.server.pm.dex.PackageDexUsage;
307import com.android.server.pm.permission.BasePermission;
308import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
309import com.android.server.pm.permission.PermissionManagerService;
310import com.android.server.pm.permission.PermissionManagerInternal;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
312import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
313import com.android.server.pm.permission.PermissionsState;
314import com.android.server.pm.permission.PermissionsState.PermissionState;
315import com.android.server.security.VerityUtils;
316import com.android.server.storage.DeviceStorageMonitorInternal;
317
318import dalvik.system.CloseGuard;
319import dalvik.system.VMRuntime;
320
321import libcore.io.IoUtils;
322
323import org.xmlpull.v1.XmlPullParser;
324import org.xmlpull.v1.XmlPullParserException;
325import org.xmlpull.v1.XmlSerializer;
326
327import java.io.BufferedOutputStream;
328import java.io.ByteArrayInputStream;
329import java.io.ByteArrayOutputStream;
330import java.io.File;
331import java.io.FileDescriptor;
332import java.io.FileInputStream;
333import java.io.FileOutputStream;
334import java.io.FilenameFilter;
335import java.io.IOException;
336import java.io.PrintWriter;
337import java.lang.annotation.Retention;
338import java.lang.annotation.RetentionPolicy;
339import java.nio.charset.StandardCharsets;
340import java.security.DigestException;
341import java.security.DigestInputStream;
342import java.security.MessageDigest;
343import java.security.NoSuchAlgorithmException;
344import java.security.PublicKey;
345import java.security.SecureRandom;
346import java.security.cert.CertificateException;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.HashMap;
353import java.util.HashSet;
354import java.util.Iterator;
355import java.util.LinkedHashSet;
356import java.util.List;
357import java.util.Map;
358import java.util.Objects;
359import java.util.Set;
360import java.util.concurrent.CountDownLatch;
361import java.util.concurrent.Future;
362import java.util.concurrent.TimeUnit;
363import java.util.concurrent.atomic.AtomicBoolean;
364import java.util.concurrent.atomic.AtomicInteger;
365
366/**
367 * Keep track of all those APKs everywhere.
368 * <p>
369 * Internally there are two important locks:
370 * <ul>
371 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
372 * and other related state. It is a fine-grained lock that should only be held
373 * momentarily, as it's one of the most contended locks in the system.
374 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
375 * operations typically involve heavy lifting of application data on disk. Since
376 * {@code installd} is single-threaded, and it's operations can often be slow,
377 * this lock should never be acquired while already holding {@link #mPackages}.
378 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
379 * holding {@link #mInstallLock}.
380 * </ul>
381 * Many internal methods rely on the caller to hold the appropriate locks, and
382 * this contract is expressed through method name suffixes:
383 * <ul>
384 * <li>fooLI(): the caller must hold {@link #mInstallLock}
385 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
386 * being modified must be frozen
387 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
388 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
389 * </ul>
390 * <p>
391 * Because this class is very central to the platform's security; please run all
392 * CTS and unit tests whenever making modifications:
393 *
394 * <pre>
395 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
396 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
397 * </pre>
398 */
399public class PackageManagerService extends IPackageManager.Stub
400        implements PackageSender {
401    static final String TAG = "PackageManager";
402    public static final boolean DEBUG_SETTINGS = false;
403    static final boolean DEBUG_PREFERRED = false;
404    static final boolean DEBUG_UPGRADE = false;
405    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
406    private static final boolean DEBUG_BACKUP = false;
407    public static final boolean DEBUG_INSTALL = false;
408    public static final boolean DEBUG_REMOVE = false;
409    private static final boolean DEBUG_BROADCASTS = false;
410    private static final boolean DEBUG_SHOW_INFO = false;
411    private static final boolean DEBUG_PACKAGE_INFO = false;
412    private static final boolean DEBUG_INTENT_MATCHING = false;
413    public static final boolean DEBUG_PACKAGE_SCANNING = false;
414    private static final boolean DEBUG_VERIFY = false;
415    private static final boolean DEBUG_FILTERS = false;
416    public static final boolean DEBUG_PERMISSIONS = false;
417    private static final boolean DEBUG_SHARED_LIBRARIES = false;
418    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
419
420    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
421    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
422    // user, but by default initialize to this.
423    public static final boolean DEBUG_DEXOPT = false;
424
425    private static final boolean DEBUG_ABI_SELECTION = false;
426    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443    private static final int SE_UID = Process.SE_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
454    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
455    static final int SCAN_REQUIRE_KNOWN = 1<<7;
456    static final int SCAN_MOVE = 1<<8;
457    static final int SCAN_INITIAL = 1<<9;
458    static final int SCAN_CHECK_ONLY = 1<<10;
459    static final int SCAN_DONT_KILL_APP = 1<<11;
460    static final int SCAN_IGNORE_FROZEN = 1<<12;
461    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
462    static final int SCAN_AS_INSTANT_APP = 1<<14;
463    static final int SCAN_AS_FULL_APP = 1<<15;
464    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
465    static final int SCAN_AS_SYSTEM = 1<<17;
466    static final int SCAN_AS_PRIVILEGED = 1<<18;
467    static final int SCAN_AS_OEM = 1<<19;
468    static final int SCAN_AS_VENDOR = 1<<20;
469    static final int SCAN_AS_PRODUCT = 1<<21;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
575
576    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
577
578    /** Canonical intent used to identify what counts as a "web browser" app */
579    private static final Intent sBrowserIntent;
580    static {
581        sBrowserIntent = new Intent();
582        sBrowserIntent.setAction(Intent.ACTION_VIEW);
583        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
584        sBrowserIntent.setData(Uri.parse("http:"));
585        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        @GuardedBy("mInstallLock")
801        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
802                String targetPackageName, String targetPath) {
803            if ("android".equals(targetPackageName)) {
804                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
805                // native AssetManager.
806                return null;
807            }
808            List<PackageParser.Package> overlayPackages =
809                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
810            if (overlayPackages == null || overlayPackages.isEmpty()) {
811                return null;
812            }
813            List<String> overlayPathList = null;
814            for (PackageParser.Package overlayPackage : overlayPackages) {
815                if (targetPath == null) {
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                    continue;
821                }
822
823                try {
824                    // Creates idmaps for system to parse correctly the Android manifest of the
825                    // target package.
826                    //
827                    // OverlayManagerService will update each of them with a correct gid from its
828                    // target package app id.
829                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
830                            UserHandle.getSharedAppGid(
831                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
832                    if (overlayPathList == null) {
833                        overlayPathList = new ArrayList<String>();
834                    }
835                    overlayPathList.add(overlayPackage.baseCodePath);
836                } catch (InstallerException e) {
837                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
838                            overlayPackage.baseCodePath);
839                }
840            }
841            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
842        }
843
844        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
845            synchronized (mPackages) {
846                return getStaticOverlayPathsLocked(
847                        mPackages.values(), targetPackageName, targetPath);
848            }
849        }
850
851        @Override public final String[] getOverlayApks(String targetPackageName) {
852            return getStaticOverlayPaths(targetPackageName, null);
853        }
854
855        @Override public final String[] getOverlayPaths(String targetPackageName,
856                String targetPath) {
857            return getStaticOverlayPaths(targetPackageName, targetPath);
858        }
859    }
860
861    class ParallelPackageParserCallback extends PackageParserCallback {
862        List<PackageParser.Package> mOverlayPackages = null;
863
864        void findStaticOverlayPackages() {
865            synchronized (mPackages) {
866                for (PackageParser.Package p : mPackages.values()) {
867                    if (p.mOverlayIsStatic) {
868                        if (mOverlayPackages == null) {
869                            mOverlayPackages = new ArrayList<PackageParser.Package>();
870                        }
871                        mOverlayPackages.add(p);
872                    }
873                }
874            }
875        }
876
877        @Override
878        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
879            // We can trust mOverlayPackages without holding mPackages because package uninstall
880            // can't happen while running parallel parsing.
881            // Moreover holding mPackages on each parsing thread causes dead-lock.
882            return mOverlayPackages == null ? null :
883                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
884        }
885    }
886
887    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
888    final ParallelPackageParserCallback mParallelPackageParserCallback =
889            new ParallelPackageParserCallback();
890
891    public static final class SharedLibraryEntry {
892        public final @Nullable String path;
893        public final @Nullable String apk;
894        public final @NonNull SharedLibraryInfo info;
895
896        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
897                String declaringPackageName, long declaringPackageVersionCode) {
898            path = _path;
899            apk = _apk;
900            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
901                    declaringPackageName, declaringPackageVersionCode), null);
902        }
903    }
904
905    // Currently known shared libraries.
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
907    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
908            new ArrayMap<>();
909
910    // All available activities, for your resolving pleasure.
911    final ActivityIntentResolver mActivities =
912            new ActivityIntentResolver();
913
914    // All available receivers, for your resolving pleasure.
915    final ActivityIntentResolver mReceivers =
916            new ActivityIntentResolver();
917
918    // All available services, for your resolving pleasure.
919    final ServiceIntentResolver mServices = new ServiceIntentResolver();
920
921    // All available providers, for your resolving pleasure.
922    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
923
924    // Mapping from provider base names (first directory in content URI codePath)
925    // to the provider information.
926    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
927            new ArrayMap<String, PackageParser.Provider>();
928
929    // Mapping from instrumentation class names to info about them.
930    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
931            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
932
933    // Packages whose data we have transfered into another package, thus
934    // should no longer exist.
935    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
936
937    // Broadcast actions that are only available to the system.
938    @GuardedBy("mProtectedBroadcasts")
939    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
940
941    /** List of packages waiting for verification. */
942    final SparseArray<PackageVerificationState> mPendingVerification
943            = new SparseArray<PackageVerificationState>();
944
945    final PackageInstallerService mInstallerService;
946
947    final ArtManagerService mArtManagerService;
948
949    private final PackageDexOptimizer mPackageDexOptimizer;
950    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
951    // is used by other apps).
952    private final DexManager mDexManager;
953
954    private AtomicInteger mNextMoveId = new AtomicInteger();
955    private final MoveCallbacks mMoveCallbacks;
956
957    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
958
959    // Cache of users who need badging.
960    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
961
962    /** Token for keys in mPendingVerification. */
963    private int mPendingVerificationToken = 0;
964
965    volatile boolean mSystemReady;
966    volatile boolean mSafeMode;
967    volatile boolean mHasSystemUidErrors;
968    private volatile boolean mWebInstantAppsDisabled;
969
970    ApplicationInfo mAndroidApplication;
971    final ActivityInfo mResolveActivity = new ActivityInfo();
972    final ResolveInfo mResolveInfo = new ResolveInfo();
973    ComponentName mResolveComponentName;
974    PackageParser.Package mPlatformPackage;
975    ComponentName mCustomResolverComponentName;
976
977    boolean mResolverReplaced = false;
978
979    private final @Nullable ComponentName mIntentFilterVerifierComponent;
980    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
981
982    private int mIntentFilterVerificationToken = 0;
983
984    /** The service connection to the ephemeral resolver */
985    final InstantAppResolverConnection mInstantAppResolverConnection;
986    /** Component used to show resolver settings for Instant Apps */
987    final ComponentName mInstantAppResolverSettingsComponent;
988
989    /** Activity used to install instant applications */
990    ActivityInfo mInstantAppInstallerActivity;
991    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
992
993    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
994            = new SparseArray<IntentFilterVerificationState>();
995
996    // TODO remove this and go through mPermissonManager directly
997    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
998    private final PermissionManagerInternal mPermissionManager;
999
1000    // List of packages names to keep cached, even if they are uninstalled for all users
1001    private List<String> mKeepUninstalledPackages;
1002
1003    private UserManagerInternal mUserManagerInternal;
1004    private ActivityManagerInternal mActivityManagerInternal;
1005
1006    private DeviceIdleController.LocalService mDeviceIdleController;
1007
1008    private File mCacheDir;
1009
1010    private Future<?> mPrepareAppDataFuture;
1011
1012    private static class IFVerificationParams {
1013        PackageParser.Package pkg;
1014        boolean replacing;
1015        int userId;
1016        int verifierUid;
1017
1018        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1019                int _userId, int _verifierUid) {
1020            pkg = _pkg;
1021            replacing = _replacing;
1022            userId = _userId;
1023            replacing = _replacing;
1024            verifierUid = _verifierUid;
1025        }
1026    }
1027
1028    private interface IntentFilterVerifier<T extends IntentFilter> {
1029        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1030                                               T filter, String packageName);
1031        void startVerifications(int userId);
1032        void receiveVerificationResponse(int verificationId);
1033    }
1034
1035    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1036        private Context mContext;
1037        private ComponentName mIntentFilterVerifierComponent;
1038        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1039
1040        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1041            mContext = context;
1042            mIntentFilterVerifierComponent = verifierComponent;
1043        }
1044
1045        private String getDefaultScheme() {
1046            return IntentFilter.SCHEME_HTTPS;
1047        }
1048
1049        @Override
1050        public void startVerifications(int userId) {
1051            // Launch verifications requests
1052            int count = mCurrentIntentFilterVerifications.size();
1053            for (int n=0; n<count; n++) {
1054                int verificationId = mCurrentIntentFilterVerifications.get(n);
1055                final IntentFilterVerificationState ivs =
1056                        mIntentFilterVerificationStates.get(verificationId);
1057
1058                String packageName = ivs.getPackageName();
1059
1060                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1061                final int filterCount = filters.size();
1062                ArraySet<String> domainsSet = new ArraySet<>();
1063                for (int m=0; m<filterCount; m++) {
1064                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1065                    domainsSet.addAll(filter.getHostsList());
1066                }
1067                synchronized (mPackages) {
1068                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1069                            packageName, domainsSet) != null) {
1070                        scheduleWriteSettingsLocked();
1071                    }
1072                }
1073                sendVerificationRequest(verificationId, ivs);
1074            }
1075            mCurrentIntentFilterVerifications.clear();
1076        }
1077
1078        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1079            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1082                    verificationId);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1085                    getDefaultScheme());
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1088                    ivs.getHostsString());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1091                    ivs.getPackageName());
1092            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1093            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1094
1095            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1096            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1097                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1098                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1099
1100            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1101            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1102                    "Sending IntentFilter verification broadcast");
1103        }
1104
1105        public void receiveVerificationResponse(int verificationId) {
1106            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1107
1108            final boolean verified = ivs.isVerified();
1109
1110            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1111            final int count = filters.size();
1112            if (DEBUG_DOMAIN_VERIFICATION) {
1113                Slog.i(TAG, "Received verification response " + verificationId
1114                        + " for " + count + " filters, verified=" + verified);
1115            }
1116            for (int n=0; n<count; n++) {
1117                PackageParser.ActivityIntentInfo filter = filters.get(n);
1118                filter.setVerified(verified);
1119
1120                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1121                        + " verified with result:" + verified + " and hosts:"
1122                        + ivs.getHostsString());
1123            }
1124
1125            mIntentFilterVerificationStates.remove(verificationId);
1126
1127            final String packageName = ivs.getPackageName();
1128            IntentFilterVerificationInfo ivi = null;
1129
1130            synchronized (mPackages) {
1131                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1132            }
1133            if (ivi == null) {
1134                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1135                        + verificationId + " packageName:" + packageName);
1136                return;
1137            }
1138            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1139                    "Updating IntentFilterVerificationInfo for package " + packageName
1140                            +" verificationId:" + verificationId);
1141
1142            synchronized (mPackages) {
1143                if (verified) {
1144                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1145                } else {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1147                }
1148                scheduleWriteSettingsLocked();
1149
1150                final int userId = ivs.getUserId();
1151                if (userId != UserHandle.USER_ALL) {
1152                    final int userStatus =
1153                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1154
1155                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1156                    boolean needUpdate = false;
1157
1158                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1159                    // already been set by the User thru the Disambiguation dialog
1160                    switch (userStatus) {
1161                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1162                            if (verified) {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1164                            } else {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1166                            }
1167                            needUpdate = true;
1168                            break;
1169
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                                needUpdate = true;
1174                            }
1175                            break;
1176
1177                        default:
1178                            // Nothing to do
1179                    }
1180
1181                    if (needUpdate) {
1182                        mSettings.updateIntentFilterVerificationStatusLPw(
1183                                packageName, updatedStatus, userId);
1184                        scheduleWritePackageRestrictionsLocked(userId);
1185                    }
1186                }
1187            }
1188        }
1189
1190        @Override
1191        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1192                    ActivityIntentInfo filter, String packageName) {
1193            if (!hasValidDomains(filter)) {
1194                return false;
1195            }
1196            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1197            if (ivs == null) {
1198                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1199                        packageName);
1200            }
1201            if (DEBUG_DOMAIN_VERIFICATION) {
1202                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1203            }
1204            ivs.addFilter(filter);
1205            return true;
1206        }
1207
1208        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1209                int userId, int verificationId, String packageName) {
1210            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1211                    verifierUid, userId, packageName);
1212            ivs.setPendingState();
1213            synchronized (mPackages) {
1214                mIntentFilterVerificationStates.append(verificationId, ivs);
1215                mCurrentIntentFilterVerifications.add(verificationId);
1216            }
1217            return ivs;
1218        }
1219    }
1220
1221    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1222        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1223                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1224                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1225    }
1226
1227    // Set of pending broadcasts for aggregating enable/disable of components.
1228    static class PendingPackageBroadcasts {
1229        // for each user id, a map of <package name -> components within that package>
1230        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1231
1232        public PendingPackageBroadcasts() {
1233            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1234        }
1235
1236        public ArrayList<String> get(int userId, String packageName) {
1237            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1238            return packages.get(packageName);
1239        }
1240
1241        public void put(int userId, String packageName, ArrayList<String> components) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            packages.put(packageName, components);
1244        }
1245
1246        public void remove(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1248            if (packages != null) {
1249                packages.remove(packageName);
1250            }
1251        }
1252
1253        public void remove(int userId) {
1254            mUidMap.remove(userId);
1255        }
1256
1257        public int userIdCount() {
1258            return mUidMap.size();
1259        }
1260
1261        public int userIdAt(int n) {
1262            return mUidMap.keyAt(n);
1263        }
1264
1265        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1266            return mUidMap.get(userId);
1267        }
1268
1269        public int size() {
1270            // total number of pending broadcast entries across all userIds
1271            int num = 0;
1272            for (int i = 0; i< mUidMap.size(); i++) {
1273                num += mUidMap.valueAt(i).size();
1274            }
1275            return num;
1276        }
1277
1278        public void clear() {
1279            mUidMap.clear();
1280        }
1281
1282        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1283            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1284            if (map == null) {
1285                map = new ArrayMap<String, ArrayList<String>>();
1286                mUidMap.put(userId, map);
1287            }
1288            return map;
1289        }
1290    }
1291    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1292
1293    // Service Connection to remote media container service to copy
1294    // package uri's from external media onto secure containers
1295    // or internal storage.
1296    private IMediaContainerService mContainerService = null;
1297
1298    static final int SEND_PENDING_BROADCAST = 1;
1299    static final int MCS_BOUND = 3;
1300    static final int END_COPY = 4;
1301    static final int INIT_COPY = 5;
1302    static final int MCS_UNBIND = 6;
1303    static final int START_CLEANING_PACKAGE = 7;
1304    static final int FIND_INSTALL_LOC = 8;
1305    static final int POST_INSTALL = 9;
1306    static final int MCS_RECONNECT = 10;
1307    static final int MCS_GIVE_UP = 11;
1308    static final int WRITE_SETTINGS = 13;
1309    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1310    static final int PACKAGE_VERIFIED = 15;
1311    static final int CHECK_PENDING_VERIFICATION = 16;
1312    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1313    static final int INTENT_FILTER_VERIFIED = 18;
1314    static final int WRITE_PACKAGE_LIST = 19;
1315    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1316
1317    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1318
1319    // Delay time in millisecs
1320    static final int BROADCAST_DELAY = 10 * 1000;
1321
1322    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1323            2 * 60 * 60 * 1000L; /* two hours */
1324
1325    static UserManagerService sUserManager;
1326
1327    // Stores a list of users whose package restrictions file needs to be updated
1328    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1329
1330    final private DefaultContainerConnection mDefContainerConn =
1331            new DefaultContainerConnection();
1332    class DefaultContainerConnection implements ServiceConnection {
1333        public void onServiceConnected(ComponentName name, IBinder service) {
1334            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1335            final IMediaContainerService imcs = IMediaContainerService.Stub
1336                    .asInterface(Binder.allowBlocking(service));
1337            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1338        }
1339
1340        public void onServiceDisconnected(ComponentName name) {
1341            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1342        }
1343    }
1344
1345    // Recordkeeping of restore-after-install operations that are currently in flight
1346    // between the Package Manager and the Backup Manager
1347    static class PostInstallData {
1348        public InstallArgs args;
1349        public PackageInstalledInfo res;
1350
1351        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1352            args = _a;
1353            res = _r;
1354        }
1355    }
1356
1357    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1358    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1359
1360    // XML tags for backup/restore of various bits of state
1361    private static final String TAG_PREFERRED_BACKUP = "pa";
1362    private static final String TAG_DEFAULT_APPS = "da";
1363    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1364
1365    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1366    private static final String TAG_ALL_GRANTS = "rt-grants";
1367    private static final String TAG_GRANT = "grant";
1368    private static final String ATTR_PACKAGE_NAME = "pkg";
1369
1370    private static final String TAG_PERMISSION = "perm";
1371    private static final String ATTR_PERMISSION_NAME = "name";
1372    private static final String ATTR_IS_GRANTED = "g";
1373    private static final String ATTR_USER_SET = "set";
1374    private static final String ATTR_USER_FIXED = "fixed";
1375    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1376
1377    // System/policy permission grants are not backed up
1378    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_POLICY_FIXED
1380            | FLAG_PERMISSION_SYSTEM_FIXED
1381            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1382
1383    // And we back up these user-adjusted states
1384    private static final int USER_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_USER_SET
1386            | FLAG_PERMISSION_USER_FIXED
1387            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1388
1389    final @Nullable String mRequiredVerifierPackage;
1390    final @NonNull String mRequiredInstallerPackage;
1391    final @NonNull String mRequiredUninstallerPackage;
1392    final @Nullable String mSetupWizardPackage;
1393    final @Nullable String mStorageManagerPackage;
1394    final @NonNull String mServicesSystemSharedLibraryPackageName;
1395    final @NonNull String mSharedSystemSharedLibraryPackageName;
1396
1397    private final PackageUsage mPackageUsage = new PackageUsage();
1398    private final CompilerStats mCompilerStats = new CompilerStats();
1399
1400    class PackageHandler extends Handler {
1401        private boolean mBound = false;
1402        final ArrayList<HandlerParams> mPendingInstalls =
1403            new ArrayList<HandlerParams>();
1404
1405        private boolean connectToService() {
1406            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1407                    " DefaultContainerService");
1408            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1409            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1410            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1411                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1412                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413                mBound = true;
1414                return true;
1415            }
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417            return false;
1418        }
1419
1420        private void disconnectService() {
1421            mContainerService = null;
1422            mBound = false;
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            mContext.unbindService(mDefContainerConn);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426        }
1427
1428        PackageHandler(Looper looper) {
1429            super(looper);
1430        }
1431
1432        public void handleMessage(Message msg) {
1433            try {
1434                doHandleMessage(msg);
1435            } finally {
1436                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437            }
1438        }
1439
1440        void doHandleMessage(Message msg) {
1441            switch (msg.what) {
1442                case INIT_COPY: {
1443                    HandlerParams params = (HandlerParams) msg.obj;
1444                    int idx = mPendingInstalls.size();
1445                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1446                    // If a bind was already initiated we dont really
1447                    // need to do anything. The pending install
1448                    // will be processed later on.
1449                    if (!mBound) {
1450                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1451                                System.identityHashCode(mHandler));
1452                        // If this is the only one pending we might
1453                        // have to bind to the service again.
1454                        if (!connectToService()) {
1455                            Slog.e(TAG, "Failed to bind to media container service");
1456                            params.serviceError();
1457                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                    System.identityHashCode(mHandler));
1459                            if (params.traceMethod != null) {
1460                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1461                                        params.traceCookie);
1462                            }
1463                            return;
1464                        } else {
1465                            // Once we bind to the service, the first
1466                            // pending request will be processed.
1467                            mPendingInstalls.add(idx, params);
1468                        }
1469                    } else {
1470                        mPendingInstalls.add(idx, params);
1471                        // Already bound to the service. Just make
1472                        // sure we trigger off processing the first request.
1473                        if (idx == 0) {
1474                            mHandler.sendEmptyMessage(MCS_BOUND);
1475                        }
1476                    }
1477                    break;
1478                }
1479                case MCS_BOUND: {
1480                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1481                    if (msg.obj != null) {
1482                        mContainerService = (IMediaContainerService) msg.obj;
1483                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1484                                System.identityHashCode(mHandler));
1485                    }
1486                    if (mContainerService == null) {
1487                        if (!mBound) {
1488                            // Something seriously wrong since we are not bound and we are not
1489                            // waiting for connection. Bail out.
1490                            Slog.e(TAG, "Cannot bind to media container service");
1491                            for (HandlerParams params : mPendingInstalls) {
1492                                // Indicate service bind error
1493                                params.serviceError();
1494                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1495                                        System.identityHashCode(params));
1496                                if (params.traceMethod != null) {
1497                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1498                                            params.traceMethod, params.traceCookie);
1499                                }
1500                                return;
1501                            }
1502                            mPendingInstalls.clear();
1503                        } else {
1504                            Slog.w(TAG, "Waiting to connect to media container service");
1505                        }
1506                    } else if (mPendingInstalls.size() > 0) {
1507                        HandlerParams params = mPendingInstalls.get(0);
1508                        if (params != null) {
1509                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                                    System.identityHashCode(params));
1511                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1512                            if (params.startCopy()) {
1513                                // We are done...  look for more work or to
1514                                // go idle.
1515                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1516                                        "Checking for more work or unbind...");
1517                                // Delete pending install
1518                                if (mPendingInstalls.size() > 0) {
1519                                    mPendingInstalls.remove(0);
1520                                }
1521                                if (mPendingInstalls.size() == 0) {
1522                                    if (mBound) {
1523                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                                "Posting delayed MCS_UNBIND");
1525                                        removeMessages(MCS_UNBIND);
1526                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1527                                        // Unbind after a little delay, to avoid
1528                                        // continual thrashing.
1529                                        sendMessageDelayed(ubmsg, 10000);
1530                                    }
1531                                } else {
1532                                    // There are more pending requests in queue.
1533                                    // Just post MCS_BOUND message to trigger processing
1534                                    // of next pending install.
1535                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                            "Posting MCS_BOUND for next work");
1537                                    mHandler.sendEmptyMessage(MCS_BOUND);
1538                                }
1539                            }
1540                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1541                        }
1542                    } else {
1543                        // Should never happen ideally.
1544                        Slog.w(TAG, "Empty queue");
1545                    }
1546                    break;
1547                }
1548                case MCS_RECONNECT: {
1549                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1550                    if (mPendingInstalls.size() > 0) {
1551                        if (mBound) {
1552                            disconnectService();
1553                        }
1554                        if (!connectToService()) {
1555                            Slog.e(TAG, "Failed to bind to media container service");
1556                            for (HandlerParams params : mPendingInstalls) {
1557                                // Indicate service bind error
1558                                params.serviceError();
1559                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1560                                        System.identityHashCode(params));
1561                            }
1562                            mPendingInstalls.clear();
1563                        }
1564                    }
1565                    break;
1566                }
1567                case MCS_UNBIND: {
1568                    // If there is no actual work left, then time to unbind.
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1570
1571                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1572                        if (mBound) {
1573                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1574
1575                            disconnectService();
1576                        }
1577                    } else if (mPendingInstalls.size() > 0) {
1578                        // There are more pending requests in queue.
1579                        // Just post MCS_BOUND message to trigger processing
1580                        // of next pending install.
1581                        mHandler.sendEmptyMessage(MCS_BOUND);
1582                    }
1583
1584                    break;
1585                }
1586                case MCS_GIVE_UP: {
1587                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1588                    HandlerParams params = mPendingInstalls.remove(0);
1589                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1590                            System.identityHashCode(params));
1591                    break;
1592                }
1593                case SEND_PENDING_BROADCAST: {
1594                    String packages[];
1595                    ArrayList<String> components[];
1596                    int size = 0;
1597                    int uids[];
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1599                    synchronized (mPackages) {
1600                        if (mPendingBroadcasts == null) {
1601                            return;
1602                        }
1603                        size = mPendingBroadcasts.size();
1604                        if (size <= 0) {
1605                            // Nothing to be done. Just return
1606                            return;
1607                        }
1608                        packages = new String[size];
1609                        components = new ArrayList[size];
1610                        uids = new int[size];
1611                        int i = 0;  // filling out the above arrays
1612
1613                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1614                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1615                            Iterator<Map.Entry<String, ArrayList<String>>> it
1616                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1617                                            .entrySet().iterator();
1618                            while (it.hasNext() && i < size) {
1619                                Map.Entry<String, ArrayList<String>> ent = it.next();
1620                                packages[i] = ent.getKey();
1621                                components[i] = ent.getValue();
1622                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1623                                uids[i] = (ps != null)
1624                                        ? UserHandle.getUid(packageUserId, ps.appId)
1625                                        : -1;
1626                                i++;
1627                            }
1628                        }
1629                        size = i;
1630                        mPendingBroadcasts.clear();
1631                    }
1632                    // Send broadcasts
1633                    for (int i = 0; i < size; i++) {
1634                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1635                    }
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1637                    break;
1638                }
1639                case START_CLEANING_PACKAGE: {
1640                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1641                    final String packageName = (String)msg.obj;
1642                    final int userId = msg.arg1;
1643                    final boolean andCode = msg.arg2 != 0;
1644                    synchronized (mPackages) {
1645                        if (userId == UserHandle.USER_ALL) {
1646                            int[] users = sUserManager.getUserIds();
1647                            for (int user : users) {
1648                                mSettings.addPackageToCleanLPw(
1649                                        new PackageCleanItem(user, packageName, andCode));
1650                            }
1651                        } else {
1652                            mSettings.addPackageToCleanLPw(
1653                                    new PackageCleanItem(userId, packageName, andCode));
1654                        }
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                    startCleaningPackages();
1658                } break;
1659                case POST_INSTALL: {
1660                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1661
1662                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1663                    final boolean didRestore = (msg.arg2 != 0);
1664                    mRunningInstalls.delete(msg.arg1);
1665
1666                    if (data != null) {
1667                        InstallArgs args = data.args;
1668                        PackageInstalledInfo parentRes = data.res;
1669
1670                        final boolean grantPermissions = (args.installFlags
1671                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1672                        final boolean killApp = (args.installFlags
1673                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1674                        final boolean virtualPreload = ((args.installFlags
1675                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1676                        final String[] grantedPermissions = args.installGrantPermissions;
1677
1678                        // Handle the parent package
1679                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1680                                virtualPreload, grantedPermissions, didRestore,
1681                                args.installerPackageName, args.observer);
1682
1683                        // Handle the child packages
1684                        final int childCount = (parentRes.addedChildPackages != null)
1685                                ? parentRes.addedChildPackages.size() : 0;
1686                        for (int i = 0; i < childCount; i++) {
1687                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1688                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1689                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1690                                    args.installerPackageName, args.observer);
1691                        }
1692
1693                        // Log tracing if needed
1694                        if (args.traceMethod != null) {
1695                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1696                                    args.traceCookie);
1697                        }
1698                    } else {
1699                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1700                    }
1701
1702                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1703                } break;
1704                case WRITE_SETTINGS: {
1705                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1706                    synchronized (mPackages) {
1707                        removeMessages(WRITE_SETTINGS);
1708                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1709                        mSettings.writeLPr();
1710                        mDirtyUsers.clear();
1711                    }
1712                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1713                } break;
1714                case WRITE_PACKAGE_RESTRICTIONS: {
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1716                    synchronized (mPackages) {
1717                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1718                        for (int userId : mDirtyUsers) {
1719                            mSettings.writePackageRestrictionsLPr(userId);
1720                        }
1721                        mDirtyUsers.clear();
1722                    }
1723                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1724                } break;
1725                case WRITE_PACKAGE_LIST: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_PACKAGE_LIST);
1729                        mSettings.writePackageListLPr(msg.arg1);
1730                    }
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1732                } break;
1733                case CHECK_PENDING_VERIFICATION: {
1734                    final int verificationId = msg.arg1;
1735                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1736
1737                    if ((state != null) && !state.timeoutExtended()) {
1738                        final InstallArgs args = state.getInstallArgs();
1739                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1740
1741                        Slog.i(TAG, "Verification timed out for " + originUri);
1742                        mPendingVerification.remove(verificationId);
1743
1744                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1745
1746                        final UserHandle user = args.getUser();
1747                        if (getDefaultVerificationResponse(user)
1748                                == PackageManager.VERIFICATION_ALLOW) {
1749                            Slog.i(TAG, "Continuing with installation of " + originUri);
1750                            state.setVerifierResponse(Binder.getCallingUid(),
1751                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1752                            broadcastPackageVerified(verificationId, originUri,
1753                                    PackageManager.VERIFICATION_ALLOW, user);
1754                            try {
1755                                ret = args.copyApk(mContainerService, true);
1756                            } catch (RemoteException e) {
1757                                Slog.e(TAG, "Could not contact the ContainerService");
1758                            }
1759                        } else {
1760                            broadcastPackageVerified(verificationId, originUri,
1761                                    PackageManager.VERIFICATION_REJECT, user);
1762                        }
1763
1764                        Trace.asyncTraceEnd(
1765                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1766
1767                        processPendingInstall(args, ret);
1768                        mHandler.sendEmptyMessage(MCS_UNBIND);
1769                    }
1770                    break;
1771                }
1772                case PACKAGE_VERIFIED: {
1773                    final int verificationId = msg.arg1;
1774
1775                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1776                    if (state == null) {
1777                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1778                        break;
1779                    }
1780
1781                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1782
1783                    state.setVerifierResponse(response.callerUid, response.code);
1784
1785                    if (state.isVerificationComplete()) {
1786                        mPendingVerification.remove(verificationId);
1787
1788                        final InstallArgs args = state.getInstallArgs();
1789                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1790
1791                        int ret;
1792                        if (state.isInstallAllowed()) {
1793                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    response.code, state.getInstallArgs().getUser());
1796                            try {
1797                                ret = args.copyApk(mContainerService, true);
1798                            } catch (RemoteException e) {
1799                                Slog.e(TAG, "Could not contact the ContainerService");
1800                            }
1801                        } else {
1802                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1803                        }
1804
1805                        Trace.asyncTraceEnd(
1806                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1807
1808                        processPendingInstall(args, ret);
1809                        mHandler.sendEmptyMessage(MCS_UNBIND);
1810                    }
1811
1812                    break;
1813                }
1814                case START_INTENT_FILTER_VERIFICATIONS: {
1815                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1816                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1817                            params.replacing, params.pkg);
1818                    break;
1819                }
1820                case INTENT_FILTER_VERIFIED: {
1821                    final int verificationId = msg.arg1;
1822
1823                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1824                            verificationId);
1825                    if (state == null) {
1826                        Slog.w(TAG, "Invalid IntentFilter verification token "
1827                                + verificationId + " received");
1828                        break;
1829                    }
1830
1831                    final int userId = state.getUserId();
1832
1833                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1834                            "Processing IntentFilter verification with token:"
1835                            + verificationId + " and userId:" + userId);
1836
1837                    final IntentFilterVerificationResponse response =
1838                            (IntentFilterVerificationResponse) msg.obj;
1839
1840                    state.setVerifierResponse(response.callerUid, response.code);
1841
1842                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1843                            "IntentFilter verification with token:" + verificationId
1844                            + " and userId:" + userId
1845                            + " is settings verifier response with response code:"
1846                            + response.code);
1847
1848                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1849                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1850                                + response.getFailedDomainsString());
1851                    }
1852
1853                    if (state.isVerificationComplete()) {
1854                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1855                    } else {
1856                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                                "IntentFilter verification with token:" + verificationId
1858                                + " was not said to be complete");
1859                    }
1860
1861                    break;
1862                }
1863                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1864                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1865                            mInstantAppResolverConnection,
1866                            (InstantAppRequest) msg.obj,
1867                            mInstantAppInstallerActivity,
1868                            mHandler);
1869                }
1870            }
1871        }
1872    }
1873
1874    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1875        @Override
1876        public void onGidsChanged(int appId, int userId) {
1877            mHandler.post(new Runnable() {
1878                @Override
1879                public void run() {
1880                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1881                }
1882            });
1883        }
1884        @Override
1885        public void onPermissionGranted(int uid, int userId) {
1886            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1887
1888            // Not critical; if this is lost, the application has to request again.
1889            synchronized (mPackages) {
1890                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1891            }
1892        }
1893        @Override
1894        public void onInstallPermissionGranted() {
1895            synchronized (mPackages) {
1896                scheduleWriteSettingsLocked();
1897            }
1898        }
1899        @Override
1900        public void onPermissionRevoked(int uid, int userId) {
1901            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1902
1903            synchronized (mPackages) {
1904                // Critical; after this call the application should never have the permission
1905                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1906            }
1907
1908            final int appId = UserHandle.getAppId(uid);
1909            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1910        }
1911        @Override
1912        public void onInstallPermissionRevoked() {
1913            synchronized (mPackages) {
1914                scheduleWriteSettingsLocked();
1915            }
1916        }
1917        @Override
1918        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1919            synchronized (mPackages) {
1920                for (int userId : updatedUserIds) {
1921                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1922                }
1923            }
1924        }
1925        @Override
1926        public void onInstallPermissionUpdated() {
1927            synchronized (mPackages) {
1928                scheduleWriteSettingsLocked();
1929            }
1930        }
1931        @Override
1932        public void onPermissionRemoved() {
1933            synchronized (mPackages) {
1934                mSettings.writeLPr();
1935            }
1936        }
1937    };
1938
1939    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1940            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1941            boolean launchedForRestore, String installerPackage,
1942            IPackageInstallObserver2 installObserver) {
1943        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1944            // Send the removed broadcasts
1945            if (res.removedInfo != null) {
1946                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1947            }
1948
1949            // Now that we successfully installed the package, grant runtime
1950            // permissions if requested before broadcasting the install. Also
1951            // for legacy apps in permission review mode we clear the permission
1952            // review flag which is used to emulate runtime permissions for
1953            // legacy apps.
1954            if (grantPermissions) {
1955                final int callingUid = Binder.getCallingUid();
1956                mPermissionManager.grantRequestedRuntimePermissions(
1957                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1958                        mPermissionCallback);
1959            }
1960
1961            final boolean update = res.removedInfo != null
1962                    && res.removedInfo.removedPackage != null;
1963            final String installerPackageName =
1964                    res.installerPackageName != null
1965                            ? res.installerPackageName
1966                            : res.removedInfo != null
1967                                    ? res.removedInfo.installerPackageName
1968                                    : null;
1969
1970            // If this is the first time we have child packages for a disabled privileged
1971            // app that had no children, we grant requested runtime permissions to the new
1972            // children if the parent on the system image had them already granted.
1973            if (res.pkg.parentPackage != null) {
1974                final int callingUid = Binder.getCallingUid();
1975                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1976                        res.pkg, callingUid, mPermissionCallback);
1977            }
1978
1979            synchronized (mPackages) {
1980                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1981            }
1982
1983            final String packageName = res.pkg.applicationInfo.packageName;
1984
1985            // Determine the set of users who are adding this package for
1986            // the first time vs. those who are seeing an update.
1987            int[] firstUserIds = EMPTY_INT_ARRAY;
1988            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1989            int[] updateUserIds = EMPTY_INT_ARRAY;
1990            int[] instantUserIds = EMPTY_INT_ARRAY;
1991            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1992            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1993            for (int newUser : res.newUsers) {
1994                final boolean isInstantApp = ps.getInstantApp(newUser);
1995                if (allNewUsers) {
1996                    if (isInstantApp) {
1997                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1998                    } else {
1999                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2000                    }
2001                    continue;
2002                }
2003                boolean isNew = true;
2004                for (int origUser : res.origUsers) {
2005                    if (origUser == newUser) {
2006                        isNew = false;
2007                        break;
2008                    }
2009                }
2010                if (isNew) {
2011                    if (isInstantApp) {
2012                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2013                    } else {
2014                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2015                    }
2016                } else {
2017                    if (isInstantApp) {
2018                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2019                    } else {
2020                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2021                    }
2022                }
2023            }
2024
2025            // Send installed broadcasts if the package is not a static shared lib.
2026            if (res.pkg.staticSharedLibName == null) {
2027                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2028
2029                // Send added for users that see the package for the first time
2030                // sendPackageAddedForNewUsers also deals with system apps
2031                int appId = UserHandle.getAppId(res.uid);
2032                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2033                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2034                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2035
2036                // Send added for users that don't see the package for the first time
2037                Bundle extras = new Bundle(1);
2038                extras.putInt(Intent.EXTRA_UID, res.uid);
2039                if (update) {
2040                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2041                }
2042                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2043                        extras, 0 /*flags*/,
2044                        null /*targetPackage*/, null /*finishedReceiver*/,
2045                        updateUserIds, instantUserIds);
2046                if (installerPackageName != null) {
2047                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2048                            extras, 0 /*flags*/,
2049                            installerPackageName, null /*finishedReceiver*/,
2050                            updateUserIds, instantUserIds);
2051                }
2052
2053                // Send replaced for users that don't see the package for the first time
2054                if (update) {
2055                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2056                            packageName, extras, 0 /*flags*/,
2057                            null /*targetPackage*/, null /*finishedReceiver*/,
2058                            updateUserIds, instantUserIds);
2059                    if (installerPackageName != null) {
2060                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2061                                extras, 0 /*flags*/,
2062                                installerPackageName, null /*finishedReceiver*/,
2063                                updateUserIds, instantUserIds);
2064                    }
2065                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2066                            null /*package*/, null /*extras*/, 0 /*flags*/,
2067                            packageName /*targetPackage*/,
2068                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2069                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2070                    // First-install and we did a restore, so we're responsible for the
2071                    // first-launch broadcast.
2072                    if (DEBUG_BACKUP) {
2073                        Slog.i(TAG, "Post-restore of " + packageName
2074                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2075                    }
2076                    sendFirstLaunchBroadcast(packageName, installerPackage,
2077                            firstUserIds, firstInstantUserIds);
2078                }
2079
2080                // Send broadcast package appeared if forward locked/external for all users
2081                // treat asec-hosted packages like removable media on upgrade
2082                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2083                    if (DEBUG_INSTALL) {
2084                        Slog.i(TAG, "upgrading pkg " + res.pkg
2085                                + " is ASEC-hosted -> AVAILABLE");
2086                    }
2087                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2088                    ArrayList<String> pkgList = new ArrayList<>(1);
2089                    pkgList.add(packageName);
2090                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2091                }
2092            }
2093
2094            // Work that needs to happen on first install within each user
2095            if (firstUserIds != null && firstUserIds.length > 0) {
2096                synchronized (mPackages) {
2097                    for (int userId : firstUserIds) {
2098                        // If this app is a browser and it's newly-installed for some
2099                        // users, clear any default-browser state in those users. The
2100                        // app's nature doesn't depend on the user, so we can just check
2101                        // its browser nature in any user and generalize.
2102                        if (packageIsBrowser(packageName, userId)) {
2103                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2104                        }
2105
2106                        // We may also need to apply pending (restored) runtime
2107                        // permission grants within these users.
2108                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2109                    }
2110                }
2111            }
2112
2113            if (allNewUsers && !update) {
2114                notifyPackageAdded(packageName);
2115            }
2116
2117            // Log current value of "unknown sources" setting
2118            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2119                    getUnknownSourcesSettings());
2120
2121            // Remove the replaced package's older resources safely now
2122            // We delete after a gc for applications  on sdcard.
2123            if (res.removedInfo != null && res.removedInfo.args != null) {
2124                Runtime.getRuntime().gc();
2125                synchronized (mInstallLock) {
2126                    res.removedInfo.args.doPostDeleteLI(true);
2127                }
2128            } else {
2129                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2130                // and not block here.
2131                VMRuntime.getRuntime().requestConcurrentGC();
2132            }
2133
2134            // Notify DexManager that the package was installed for new users.
2135            // The updated users should already be indexed and the package code paths
2136            // should not change.
2137            // Don't notify the manager for ephemeral apps as they are not expected to
2138            // survive long enough to benefit of background optimizations.
2139            for (int userId : firstUserIds) {
2140                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2141                // There's a race currently where some install events may interleave with an uninstall.
2142                // This can lead to package info being null (b/36642664).
2143                if (info != null) {
2144                    mDexManager.notifyPackageInstalled(info, userId);
2145                }
2146            }
2147        }
2148
2149        // If someone is watching installs - notify them
2150        if (installObserver != null) {
2151            try {
2152                Bundle extras = extrasForInstallResult(res);
2153                installObserver.onPackageInstalled(res.name, res.returnCode,
2154                        res.returnMsg, extras);
2155            } catch (RemoteException e) {
2156                Slog.i(TAG, "Observer no longer exists.");
2157            }
2158        }
2159    }
2160
2161    private StorageEventListener mStorageListener = new StorageEventListener() {
2162        @Override
2163        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2164            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2165                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2166                    final String volumeUuid = vol.getFsUuid();
2167
2168                    // Clean up any users or apps that were removed or recreated
2169                    // while this volume was missing
2170                    sUserManager.reconcileUsers(volumeUuid);
2171                    reconcileApps(volumeUuid);
2172
2173                    // Clean up any install sessions that expired or were
2174                    // cancelled while this volume was missing
2175                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2176
2177                    loadPrivatePackages(vol);
2178
2179                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2180                    unloadPrivatePackages(vol);
2181                }
2182            }
2183        }
2184
2185        @Override
2186        public void onVolumeForgotten(String fsUuid) {
2187            if (TextUtils.isEmpty(fsUuid)) {
2188                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2189                return;
2190            }
2191
2192            // Remove any apps installed on the forgotten volume
2193            synchronized (mPackages) {
2194                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2195                for (PackageSetting ps : packages) {
2196                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2197                    deletePackageVersioned(new VersionedPackage(ps.name,
2198                            PackageManager.VERSION_CODE_HIGHEST),
2199                            new LegacyPackageDeleteObserver(null).getBinder(),
2200                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2201                    // Try very hard to release any references to this package
2202                    // so we don't risk the system server being killed due to
2203                    // open FDs
2204                    AttributeCache.instance().removePackage(ps.name);
2205                }
2206
2207                mSettings.onVolumeForgotten(fsUuid);
2208                mSettings.writeLPr();
2209            }
2210        }
2211    };
2212
2213    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2214        Bundle extras = null;
2215        switch (res.returnCode) {
2216            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2217                extras = new Bundle();
2218                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2219                        res.origPermission);
2220                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2221                        res.origPackage);
2222                break;
2223            }
2224            case PackageManager.INSTALL_SUCCEEDED: {
2225                extras = new Bundle();
2226                extras.putBoolean(Intent.EXTRA_REPLACING,
2227                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2228                break;
2229            }
2230        }
2231        return extras;
2232    }
2233
2234    void scheduleWriteSettingsLocked() {
2235        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2236            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2237        }
2238    }
2239
2240    void scheduleWritePackageListLocked(int userId) {
2241        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2242            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2243            msg.arg1 = userId;
2244            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2245        }
2246    }
2247
2248    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2249        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2250        scheduleWritePackageRestrictionsLocked(userId);
2251    }
2252
2253    void scheduleWritePackageRestrictionsLocked(int userId) {
2254        final int[] userIds = (userId == UserHandle.USER_ALL)
2255                ? sUserManager.getUserIds() : new int[]{userId};
2256        for (int nextUserId : userIds) {
2257            if (!sUserManager.exists(nextUserId)) return;
2258            mDirtyUsers.add(nextUserId);
2259            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2260                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2261            }
2262        }
2263    }
2264
2265    public static PackageManagerService main(Context context, Installer installer,
2266            boolean factoryTest, boolean onlyCore) {
2267        // Self-check for initial settings.
2268        PackageManagerServiceCompilerMapping.checkProperties();
2269
2270        PackageManagerService m = new PackageManagerService(context, installer,
2271                factoryTest, onlyCore);
2272        m.enableSystemUserPackages();
2273        ServiceManager.addService("package", m);
2274        final PackageManagerNative pmn = m.new PackageManagerNative();
2275        ServiceManager.addService("package_native", pmn);
2276        return m;
2277    }
2278
2279    private void enableSystemUserPackages() {
2280        if (!UserManager.isSplitSystemUser()) {
2281            return;
2282        }
2283        // For system user, enable apps based on the following conditions:
2284        // - app is whitelisted or belong to one of these groups:
2285        //   -- system app which has no launcher icons
2286        //   -- system app which has INTERACT_ACROSS_USERS permission
2287        //   -- system IME app
2288        // - app is not in the blacklist
2289        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2290        Set<String> enableApps = new ArraySet<>();
2291        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2292                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2293                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2294        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2295        enableApps.addAll(wlApps);
2296        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2297                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2298        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2299        enableApps.removeAll(blApps);
2300        Log.i(TAG, "Applications installed for system user: " + enableApps);
2301        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2302                UserHandle.SYSTEM);
2303        final int allAppsSize = allAps.size();
2304        synchronized (mPackages) {
2305            for (int i = 0; i < allAppsSize; i++) {
2306                String pName = allAps.get(i);
2307                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2308                // Should not happen, but we shouldn't be failing if it does
2309                if (pkgSetting == null) {
2310                    continue;
2311                }
2312                boolean install = enableApps.contains(pName);
2313                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2314                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2315                            + " for system user");
2316                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2317                }
2318            }
2319            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2320        }
2321    }
2322
2323    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2324        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2325                Context.DISPLAY_SERVICE);
2326        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2327    }
2328
2329    /**
2330     * Requests that files preopted on a secondary system partition be copied to the data partition
2331     * if possible.  Note that the actual copying of the files is accomplished by init for security
2332     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2333     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2334     */
2335    private static void requestCopyPreoptedFiles() {
2336        final int WAIT_TIME_MS = 100;
2337        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2338        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2339            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2340            // We will wait for up to 100 seconds.
2341            final long timeStart = SystemClock.uptimeMillis();
2342            final long timeEnd = timeStart + 100 * 1000;
2343            long timeNow = timeStart;
2344            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2345                try {
2346                    Thread.sleep(WAIT_TIME_MS);
2347                } catch (InterruptedException e) {
2348                    // Do nothing
2349                }
2350                timeNow = SystemClock.uptimeMillis();
2351                if (timeNow > timeEnd) {
2352                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2353                    Slog.wtf(TAG, "cppreopt did not finish!");
2354                    break;
2355                }
2356            }
2357
2358            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2359        }
2360    }
2361
2362    public PackageManagerService(Context context, Installer installer,
2363            boolean factoryTest, boolean onlyCore) {
2364        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2365        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2366        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2367                SystemClock.uptimeMillis());
2368
2369        if (mSdkVersion <= 0) {
2370            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2371        }
2372
2373        mContext = context;
2374
2375        mFactoryTest = factoryTest;
2376        mOnlyCore = onlyCore;
2377        mMetrics = new DisplayMetrics();
2378        mInstaller = installer;
2379
2380        // Create sub-components that provide services / data. Order here is important.
2381        synchronized (mInstallLock) {
2382        synchronized (mPackages) {
2383            // Expose private service for system components to use.
2384            LocalServices.addService(
2385                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2386            sUserManager = new UserManagerService(context, this,
2387                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2388            mPermissionManager = PermissionManagerService.create(context,
2389                    new DefaultPermissionGrantedCallback() {
2390                        @Override
2391                        public void onDefaultRuntimePermissionsGranted(int userId) {
2392                            synchronized(mPackages) {
2393                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2394                            }
2395                        }
2396                    }, mPackages /*externalLock*/);
2397            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2398            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2399        }
2400        }
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415
2416        String separateProcesses = SystemProperties.get("debug.separate_processes");
2417        if (separateProcesses != null && separateProcesses.length() > 0) {
2418            if ("*".equals(separateProcesses)) {
2419                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2420                mSeparateProcesses = null;
2421                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2422            } else {
2423                mDefParseFlags = 0;
2424                mSeparateProcesses = separateProcesses.split(",");
2425                Slog.w(TAG, "Running with debug.separate_processes: "
2426                        + separateProcesses);
2427            }
2428        } else {
2429            mDefParseFlags = 0;
2430            mSeparateProcesses = null;
2431        }
2432
2433        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2434                "*dexopt*");
2435        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2436                installer, mInstallLock);
2437        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2438                dexManagerListener);
2439        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2440        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2441
2442        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2443                FgThread.get().getLooper());
2444
2445        getDefaultDisplayMetrics(context, mMetrics);
2446
2447        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2448        SystemConfig systemConfig = SystemConfig.getInstance();
2449        mAvailableFeatures = systemConfig.getAvailableFeatures();
2450        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2451
2452        mProtectedPackages = new ProtectedPackages(mContext);
2453
2454        synchronized (mInstallLock) {
2455        // writer
2456        synchronized (mPackages) {
2457            mHandlerThread = new ServiceThread(TAG,
2458                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2459            mHandlerThread.start();
2460            mHandler = new PackageHandler(mHandlerThread.getLooper());
2461            mProcessLoggingHandler = new ProcessLoggingHandler();
2462            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2463            mInstantAppRegistry = new InstantAppRegistry(this);
2464
2465            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2466            final int builtInLibCount = libConfig.size();
2467            for (int i = 0; i < builtInLibCount; i++) {
2468                String name = libConfig.keyAt(i);
2469                String path = libConfig.valueAt(i);
2470                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2471                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2472            }
2473
2474            SELinuxMMAC.readInstallPolicy();
2475
2476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2477            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2479
2480            // Clean up orphaned packages for which the code path doesn't exist
2481            // and they are an update to a system app - caused by bug/32321269
2482            final int packageSettingCount = mSettings.mPackages.size();
2483            for (int i = packageSettingCount - 1; i >= 0; i--) {
2484                PackageSetting ps = mSettings.mPackages.valueAt(i);
2485                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2486                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2487                    mSettings.mPackages.removeAt(i);
2488                    mSettings.enableSystemPackageLPw(ps.name);
2489                }
2490            }
2491
2492            if (mFirstBoot) {
2493                requestCopyPreoptedFiles();
2494            }
2495
2496            String customResolverActivity = Resources.getSystem().getString(
2497                    R.string.config_customResolverActivity);
2498            if (TextUtils.isEmpty(customResolverActivity)) {
2499                customResolverActivity = null;
2500            } else {
2501                mCustomResolverComponentName = ComponentName.unflattenFromString(
2502                        customResolverActivity);
2503            }
2504
2505            long startTime = SystemClock.uptimeMillis();
2506
2507            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2508                    startTime);
2509
2510            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2511            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2512
2513            if (bootClassPath == null) {
2514                Slog.w(TAG, "No BOOTCLASSPATH found!");
2515            }
2516
2517            if (systemServerClassPath == null) {
2518                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2519            }
2520
2521            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2522
2523            final VersionInfo ver = mSettings.getInternalVersion();
2524            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2525            if (mIsUpgrade) {
2526                logCriticalInfo(Log.INFO,
2527                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2528            }
2529
2530            // when upgrading from pre-M, promote system app permissions from install to runtime
2531            mPromoteSystemApps =
2532                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2533
2534            // When upgrading from pre-N, we need to handle package extraction like first boot,
2535            // as there is no profiling data available.
2536            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2537
2538            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2539
2540            // save off the names of pre-existing system packages prior to scanning; we don't
2541            // want to automatically grant runtime permissions for new system apps
2542            if (mPromoteSystemApps) {
2543                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2544                while (pkgSettingIter.hasNext()) {
2545                    PackageSetting ps = pkgSettingIter.next();
2546                    if (isSystemApp(ps)) {
2547                        mExistingSystemPackages.add(ps.name);
2548                    }
2549                }
2550            }
2551
2552            mCacheDir = preparePackageParserCache(mIsUpgrade);
2553
2554            // Set flag to monitor and not change apk file paths when
2555            // scanning install directories.
2556            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2557
2558            if (mIsUpgrade || mFirstBoot) {
2559                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2560            }
2561
2562            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2563            // For security and version matching reason, only consider
2564            // overlay packages if they reside in the right directory.
2565            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2566                    mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2568                    scanFlags
2569                    | SCAN_AS_SYSTEM
2570                    | SCAN_AS_VENDOR,
2571                    0);
2572            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2573                    mDefParseFlags
2574                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2575                    scanFlags
2576                    | SCAN_AS_SYSTEM
2577                    | SCAN_AS_PRODUCT,
2578                    0);
2579
2580            mParallelPackageParserCallback.findStaticOverlayPackages();
2581
2582            // Find base frameworks (resource packages without code).
2583            scanDirTracedLI(frameworkDir,
2584                    mDefParseFlags
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2586                    scanFlags
2587                    | SCAN_NO_DEX
2588                    | SCAN_AS_SYSTEM
2589                    | SCAN_AS_PRIVILEGED,
2590                    0);
2591
2592            // Collected privileged system packages.
2593            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2594            scanDirTracedLI(privilegedAppDir,
2595                    mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2597                    scanFlags
2598                    | SCAN_AS_SYSTEM
2599                    | SCAN_AS_PRIVILEGED,
2600                    0);
2601
2602            // Collect ordinary system packages.
2603            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604            scanDirTracedLI(systemAppDir,
2605                    mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2607                    scanFlags
2608                    | SCAN_AS_SYSTEM,
2609                    0);
2610
2611            // Collected privileged vendor packages.
2612            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2613            try {
2614                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2615            } catch (IOException e) {
2616                // failed to look up canonical path, continue with original one
2617            }
2618            scanDirTracedLI(privilegedVendorAppDir,
2619                    mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2621                    scanFlags
2622                    | SCAN_AS_SYSTEM
2623                    | SCAN_AS_VENDOR
2624                    | SCAN_AS_PRIVILEGED,
2625                    0);
2626
2627            // Collect ordinary vendor packages.
2628            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2629            try {
2630                vendorAppDir = vendorAppDir.getCanonicalFile();
2631            } catch (IOException e) {
2632                // failed to look up canonical path, continue with original one
2633            }
2634            scanDirTracedLI(vendorAppDir,
2635                    mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2637                    scanFlags
2638                    | SCAN_AS_SYSTEM
2639                    | SCAN_AS_VENDOR,
2640                    0);
2641
2642            // Collect all OEM packages.
2643            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2644            scanDirTracedLI(oemAppDir,
2645                    mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2647                    scanFlags
2648                    | SCAN_AS_SYSTEM
2649                    | SCAN_AS_OEM,
2650                    0);
2651
2652            // Collected privileged product packages.
2653            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2654            try {
2655                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2656            } catch (IOException e) {
2657                // failed to look up canonical path, continue with original one
2658            }
2659            scanDirTracedLI(privilegedProductAppDir,
2660                    mDefParseFlags
2661                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2662                    scanFlags
2663                    | SCAN_AS_SYSTEM
2664                    | SCAN_AS_PRODUCT
2665                    | SCAN_AS_PRIVILEGED,
2666                    0);
2667
2668            // Collect ordinary product packages.
2669            File productAppDir = new File(Environment.getProductDirectory(), "app");
2670            try {
2671                productAppDir = productAppDir.getCanonicalFile();
2672            } catch (IOException e) {
2673                // failed to look up canonical path, continue with original one
2674            }
2675            scanDirTracedLI(productAppDir,
2676                    mDefParseFlags
2677                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2678                    scanFlags
2679                    | SCAN_AS_SYSTEM
2680                    | SCAN_AS_PRODUCT,
2681                    0);
2682
2683            // Prune any system packages that no longer exist.
2684            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2685            // Stub packages must either be replaced with full versions in the /data
2686            // partition or be disabled.
2687            final List<String> stubSystemApps = new ArrayList<>();
2688            if (!mOnlyCore) {
2689                // do this first before mucking with mPackages for the "expecting better" case
2690                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2691                while (pkgIterator.hasNext()) {
2692                    final PackageParser.Package pkg = pkgIterator.next();
2693                    if (pkg.isStub) {
2694                        stubSystemApps.add(pkg.packageName);
2695                    }
2696                }
2697
2698                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2699                while (psit.hasNext()) {
2700                    PackageSetting ps = psit.next();
2701
2702                    /*
2703                     * If this is not a system app, it can't be a
2704                     * disable system app.
2705                     */
2706                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2707                        continue;
2708                    }
2709
2710                    /*
2711                     * If the package is scanned, it's not erased.
2712                     */
2713                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2714                    if (scannedPkg != null) {
2715                        /*
2716                         * If the system app is both scanned and in the
2717                         * disabled packages list, then it must have been
2718                         * added via OTA. Remove it from the currently
2719                         * scanned package so the previously user-installed
2720                         * application can be scanned.
2721                         */
2722                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2723                            logCriticalInfo(Log.WARN,
2724                                    "Expecting better updated system app for " + ps.name
2725                                    + "; removing system app.  Last known"
2726                                    + " codePath=" + ps.codePathString
2727                                    + ", versionCode=" + ps.versionCode
2728                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2729                            removePackageLI(scannedPkg, true);
2730                            mExpectingBetter.put(ps.name, ps.codePath);
2731                        }
2732
2733                        continue;
2734                    }
2735
2736                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2737                        psit.remove();
2738                        logCriticalInfo(Log.WARN, "System package " + ps.name
2739                                + " no longer exists; it's data will be wiped");
2740                        // Actual deletion of code and data will be handled by later
2741                        // reconciliation step
2742                    } else {
2743                        // we still have a disabled system package, but, it still might have
2744                        // been removed. check the code path still exists and check there's
2745                        // still a package. the latter can happen if an OTA keeps the same
2746                        // code path, but, changes the package name.
2747                        final PackageSetting disabledPs =
2748                                mSettings.getDisabledSystemPkgLPr(ps.name);
2749                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2750                                || disabledPs.pkg == null) {
2751                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2752                        }
2753                    }
2754                }
2755            }
2756
2757            //delete tmp files
2758            deleteTempPackageFiles();
2759
2760            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2761
2762            // Remove any shared userIDs that have no associated packages
2763            mSettings.pruneSharedUsersLPw();
2764            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2765            final int systemPackagesCount = mPackages.size();
2766            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2767                    + " ms, packageCount: " + systemPackagesCount
2768                    + " , timePerPackage: "
2769                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2770                    + " , cached: " + cachedSystemApps);
2771            if (mIsUpgrade && systemPackagesCount > 0) {
2772                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2773                        ((int) systemScanTime) / systemPackagesCount);
2774            }
2775            if (!mOnlyCore) {
2776                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2777                        SystemClock.uptimeMillis());
2778                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2779
2780                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2781                        | PackageParser.PARSE_FORWARD_LOCK,
2782                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2783
2784                // Remove disable package settings for updated system apps that were
2785                // removed via an OTA. If the update is no longer present, remove the
2786                // app completely. Otherwise, revoke their system privileges.
2787                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2788                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2789                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2790                    final String msg;
2791                    if (deletedPkg == null) {
2792                        // should have found an update, but, we didn't; remove everything
2793                        msg = "Updated system package " + deletedAppName
2794                                + " no longer exists; removing its data";
2795                        // Actual deletion of code and data will be handled by later
2796                        // reconciliation step
2797                    } else {
2798                        // found an update; revoke system privileges
2799                        msg = "Updated system package + " + deletedAppName
2800                                + " no longer exists; revoking system privileges";
2801
2802                        // Don't do anything if a stub is removed from the system image. If
2803                        // we were to remove the uncompressed version from the /data partition,
2804                        // this is where it'd be done.
2805
2806                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2807                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2808                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2809                    }
2810                    logCriticalInfo(Log.WARN, msg);
2811                }
2812
2813                /*
2814                 * Make sure all system apps that we expected to appear on
2815                 * the userdata partition actually showed up. If they never
2816                 * appeared, crawl back and revive the system version.
2817                 */
2818                for (int i = 0; i < mExpectingBetter.size(); i++) {
2819                    final String packageName = mExpectingBetter.keyAt(i);
2820                    if (!mPackages.containsKey(packageName)) {
2821                        final File scanFile = mExpectingBetter.valueAt(i);
2822
2823                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2824                                + " but never showed up; reverting to system");
2825
2826                        final @ParseFlags int reparseFlags;
2827                        final @ScanFlags int rescanFlags;
2828                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2829                            reparseFlags =
2830                                    mDefParseFlags |
2831                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2832                            rescanFlags =
2833                                    scanFlags
2834                                    | SCAN_AS_SYSTEM
2835                                    | SCAN_AS_PRIVILEGED;
2836                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2837                            reparseFlags =
2838                                    mDefParseFlags |
2839                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2840                            rescanFlags =
2841                                    scanFlags
2842                                    | SCAN_AS_SYSTEM;
2843                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2844                            reparseFlags =
2845                                    mDefParseFlags |
2846                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2847                            rescanFlags =
2848                                    scanFlags
2849                                    | SCAN_AS_SYSTEM
2850                                    | SCAN_AS_VENDOR
2851                                    | SCAN_AS_PRIVILEGED;
2852                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2853                            reparseFlags =
2854                                    mDefParseFlags |
2855                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2856                            rescanFlags =
2857                                    scanFlags
2858                                    | SCAN_AS_SYSTEM
2859                                    | SCAN_AS_VENDOR;
2860                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2861                            reparseFlags =
2862                                    mDefParseFlags |
2863                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2864                            rescanFlags =
2865                                    scanFlags
2866                                    | SCAN_AS_SYSTEM
2867                                    | SCAN_AS_OEM;
2868                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2869                            reparseFlags =
2870                                    mDefParseFlags |
2871                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2872                            rescanFlags =
2873                                    scanFlags
2874                                    | SCAN_AS_SYSTEM
2875                                    | SCAN_AS_PRODUCT
2876                                    | SCAN_AS_PRIVILEGED;
2877                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2878                            reparseFlags =
2879                                    mDefParseFlags |
2880                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2881                            rescanFlags =
2882                                    scanFlags
2883                                    | SCAN_AS_SYSTEM
2884                                    | SCAN_AS_PRODUCT;
2885                        } else {
2886                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2887                            continue;
2888                        }
2889
2890                        mSettings.enableSystemPackageLPw(packageName);
2891
2892                        try {
2893                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2894                        } catch (PackageManagerException e) {
2895                            Slog.e(TAG, "Failed to parse original system package: "
2896                                    + e.getMessage());
2897                        }
2898                    }
2899                }
2900
2901                // Uncompress and install any stubbed system applications.
2902                // This must be done last to ensure all stubs are replaced or disabled.
2903                decompressSystemApplications(stubSystemApps, scanFlags);
2904
2905                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2906                                - cachedSystemApps;
2907
2908                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2909                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2910                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2911                        + " ms, packageCount: " + dataPackagesCount
2912                        + " , timePerPackage: "
2913                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2914                        + " , cached: " + cachedNonSystemApps);
2915                if (mIsUpgrade && dataPackagesCount > 0) {
2916                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2917                            ((int) dataScanTime) / dataPackagesCount);
2918                }
2919            }
2920            mExpectingBetter.clear();
2921
2922            // Resolve the storage manager.
2923            mStorageManagerPackage = getStorageManagerPackageName();
2924
2925            // Resolve protected action filters. Only the setup wizard is allowed to
2926            // have a high priority filter for these actions.
2927            mSetupWizardPackage = getSetupWizardPackageName();
2928            if (mProtectedFilters.size() > 0) {
2929                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2930                    Slog.i(TAG, "No setup wizard;"
2931                        + " All protected intents capped to priority 0");
2932                }
2933                for (ActivityIntentInfo filter : mProtectedFilters) {
2934                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2935                        if (DEBUG_FILTERS) {
2936                            Slog.i(TAG, "Found setup wizard;"
2937                                + " allow priority " + filter.getPriority() + ";"
2938                                + " package: " + filter.activity.info.packageName
2939                                + " activity: " + filter.activity.className
2940                                + " priority: " + filter.getPriority());
2941                        }
2942                        // skip setup wizard; allow it to keep the high priority filter
2943                        continue;
2944                    }
2945                    if (DEBUG_FILTERS) {
2946                        Slog.i(TAG, "Protected action; cap priority to 0;"
2947                                + " package: " + filter.activity.info.packageName
2948                                + " activity: " + filter.activity.className
2949                                + " origPrio: " + filter.getPriority());
2950                    }
2951                    filter.setPriority(0);
2952                }
2953            }
2954            mDeferProtectedFilters = false;
2955            mProtectedFilters.clear();
2956
2957            // Now that we know all of the shared libraries, update all clients to have
2958            // the correct library paths.
2959            updateAllSharedLibrariesLPw(null);
2960
2961            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2962                // NOTE: We ignore potential failures here during a system scan (like
2963                // the rest of the commands above) because there's precious little we
2964                // can do about it. A settings error is reported, though.
2965                final List<String> changedAbiCodePath =
2966                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2967                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2968                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2969                        final String codePathString = changedAbiCodePath.get(i);
2970                        try {
2971                            mInstaller.rmdex(codePathString,
2972                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2973                        } catch (InstallerException ignored) {
2974                        }
2975                    }
2976                }
2977            }
2978
2979            // Now that we know all the packages we are keeping,
2980            // read and update their last usage times.
2981            mPackageUsage.read(mPackages);
2982            mCompilerStats.read();
2983
2984            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2985                    SystemClock.uptimeMillis());
2986            Slog.i(TAG, "Time to scan packages: "
2987                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2988                    + " seconds");
2989
2990            // If the platform SDK has changed since the last time we booted,
2991            // we need to re-grant app permission to catch any new ones that
2992            // appear.  This is really a hack, and means that apps can in some
2993            // cases get permissions that the user didn't initially explicitly
2994            // allow...  it would be nice to have some better way to handle
2995            // this situation.
2996            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2997            if (sdkUpdated) {
2998                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2999                        + mSdkVersion + "; regranting permissions for internal storage");
3000            }
3001            mPermissionManager.updateAllPermissions(
3002                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3003                    mPermissionCallback);
3004            ver.sdkVersion = mSdkVersion;
3005
3006            // If this is the first boot or an update from pre-M, and it is a normal
3007            // boot, then we need to initialize the default preferred apps across
3008            // all defined users.
3009            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3010                for (UserInfo user : sUserManager.getUsers(true)) {
3011                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3012                    applyFactoryDefaultBrowserLPw(user.id);
3013                    primeDomainVerificationsLPw(user.id);
3014                }
3015            }
3016
3017            // Prepare storage for system user really early during boot,
3018            // since core system apps like SettingsProvider and SystemUI
3019            // can't wait for user to start
3020            final int storageFlags;
3021            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3022                storageFlags = StorageManager.FLAG_STORAGE_DE;
3023            } else {
3024                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3025            }
3026            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3027                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3028                    true /* onlyCoreApps */);
3029            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3030                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3031                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3032                traceLog.traceBegin("AppDataFixup");
3033                try {
3034                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3035                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3036                } catch (InstallerException e) {
3037                    Slog.w(TAG, "Trouble fixing GIDs", e);
3038                }
3039                traceLog.traceEnd();
3040
3041                traceLog.traceBegin("AppDataPrepare");
3042                if (deferPackages == null || deferPackages.isEmpty()) {
3043                    return;
3044                }
3045                int count = 0;
3046                for (String pkgName : deferPackages) {
3047                    PackageParser.Package pkg = null;
3048                    synchronized (mPackages) {
3049                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3050                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3051                            pkg = ps.pkg;
3052                        }
3053                    }
3054                    if (pkg != null) {
3055                        synchronized (mInstallLock) {
3056                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3057                                    true /* maybeMigrateAppData */);
3058                        }
3059                        count++;
3060                    }
3061                }
3062                traceLog.traceEnd();
3063                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3064            }, "prepareAppData");
3065
3066            // If this is first boot after an OTA, and a normal boot, then
3067            // we need to clear code cache directories.
3068            // Note that we do *not* clear the application profiles. These remain valid
3069            // across OTAs and are used to drive profile verification (post OTA) and
3070            // profile compilation (without waiting to collect a fresh set of profiles).
3071            if (mIsUpgrade && !onlyCore) {
3072                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3073                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3074                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3075                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3076                        // No apps are running this early, so no need to freeze
3077                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3078                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3079                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3080                    }
3081                }
3082                ver.fingerprint = Build.FINGERPRINT;
3083            }
3084
3085            checkDefaultBrowser();
3086
3087            // clear only after permissions and other defaults have been updated
3088            mExistingSystemPackages.clear();
3089            mPromoteSystemApps = false;
3090
3091            // All the changes are done during package scanning.
3092            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3093
3094            // can downgrade to reader
3095            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3096            mSettings.writeLPr();
3097            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3098            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3099                    SystemClock.uptimeMillis());
3100
3101            if (!mOnlyCore) {
3102                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3103                mRequiredInstallerPackage = getRequiredInstallerLPr();
3104                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3105                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3106                if (mIntentFilterVerifierComponent != null) {
3107                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3108                            mIntentFilterVerifierComponent);
3109                } else {
3110                    mIntentFilterVerifier = null;
3111                }
3112                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3113                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3114                        SharedLibraryInfo.VERSION_UNDEFINED);
3115                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3116                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3117                        SharedLibraryInfo.VERSION_UNDEFINED);
3118            } else {
3119                mRequiredVerifierPackage = null;
3120                mRequiredInstallerPackage = null;
3121                mRequiredUninstallerPackage = null;
3122                mIntentFilterVerifierComponent = null;
3123                mIntentFilterVerifier = null;
3124                mServicesSystemSharedLibraryPackageName = null;
3125                mSharedSystemSharedLibraryPackageName = null;
3126            }
3127
3128            mInstallerService = new PackageInstallerService(context, this);
3129            final Pair<ComponentName, String> instantAppResolverComponent =
3130                    getInstantAppResolverLPr();
3131            if (instantAppResolverComponent != null) {
3132                if (DEBUG_INSTANT) {
3133                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3134                }
3135                mInstantAppResolverConnection = new InstantAppResolverConnection(
3136                        mContext, instantAppResolverComponent.first,
3137                        instantAppResolverComponent.second);
3138                mInstantAppResolverSettingsComponent =
3139                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3140            } else {
3141                mInstantAppResolverConnection = null;
3142                mInstantAppResolverSettingsComponent = null;
3143            }
3144            updateInstantAppInstallerLocked(null);
3145
3146            // Read and update the usage of dex files.
3147            // Do this at the end of PM init so that all the packages have their
3148            // data directory reconciled.
3149            // At this point we know the code paths of the packages, so we can validate
3150            // the disk file and build the internal cache.
3151            // The usage file is expected to be small so loading and verifying it
3152            // should take a fairly small time compare to the other activities (e.g. package
3153            // scanning).
3154            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3155            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3156            for (int userId : currentUserIds) {
3157                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3158            }
3159            mDexManager.load(userPackages);
3160            if (mIsUpgrade) {
3161                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3162                        (int) (SystemClock.uptimeMillis() - startTime));
3163            }
3164        } // synchronized (mPackages)
3165        } // synchronized (mInstallLock)
3166
3167        // Now after opening every single application zip, make sure they
3168        // are all flushed.  Not really needed, but keeps things nice and
3169        // tidy.
3170        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3171        Runtime.getRuntime().gc();
3172        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3173
3174        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3175        FallbackCategoryProvider.loadFallbacks();
3176        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3177
3178        // The initial scanning above does many calls into installd while
3179        // holding the mPackages lock, but we're mostly interested in yelling
3180        // once we have a booted system.
3181        mInstaller.setWarnIfHeld(mPackages);
3182
3183        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3184    }
3185
3186    /**
3187     * Uncompress and install stub applications.
3188     * <p>In order to save space on the system partition, some applications are shipped in a
3189     * compressed form. In addition the compressed bits for the full application, the
3190     * system image contains a tiny stub comprised of only the Android manifest.
3191     * <p>During the first boot, attempt to uncompress and install the full application. If
3192     * the application can't be installed for any reason, disable the stub and prevent
3193     * uncompressing the full application during future boots.
3194     * <p>In order to forcefully attempt an installation of a full application, go to app
3195     * settings and enable the application.
3196     */
3197    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3198        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3199            final String pkgName = stubSystemApps.get(i);
3200            // skip if the system package is already disabled
3201            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3202                stubSystemApps.remove(i);
3203                continue;
3204            }
3205            // skip if the package isn't installed (?!); this should never happen
3206            final PackageParser.Package pkg = mPackages.get(pkgName);
3207            if (pkg == null) {
3208                stubSystemApps.remove(i);
3209                continue;
3210            }
3211            // skip if the package has been disabled by the user
3212            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3213            if (ps != null) {
3214                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3215                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3216                    stubSystemApps.remove(i);
3217                    continue;
3218                }
3219            }
3220
3221            if (DEBUG_COMPRESSION) {
3222                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3223            }
3224
3225            // uncompress the binary to its eventual destination on /data
3226            final File scanFile = decompressPackage(pkg);
3227            if (scanFile == null) {
3228                continue;
3229            }
3230
3231            // install the package to replace the stub on /system
3232            try {
3233                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3234                removePackageLI(pkg, true /*chatty*/);
3235                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3236                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3237                        UserHandle.USER_SYSTEM, "android");
3238                stubSystemApps.remove(i);
3239                continue;
3240            } catch (PackageManagerException e) {
3241                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3242            }
3243
3244            // any failed attempt to install the package will be cleaned up later
3245        }
3246
3247        // disable any stub still left; these failed to install the full application
3248        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3249            final String pkgName = stubSystemApps.get(i);
3250            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3251            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3252                    UserHandle.USER_SYSTEM, "android");
3253            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3254        }
3255    }
3256
3257    /**
3258     * Decompresses the given package on the system image onto
3259     * the /data partition.
3260     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3261     */
3262    private File decompressPackage(PackageParser.Package pkg) {
3263        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3264        if (compressedFiles == null || compressedFiles.length == 0) {
3265            if (DEBUG_COMPRESSION) {
3266                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3267            }
3268            return null;
3269        }
3270        final File dstCodePath =
3271                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3272        int ret = PackageManager.INSTALL_SUCCEEDED;
3273        try {
3274            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3275            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3276            for (File srcFile : compressedFiles) {
3277                final String srcFileName = srcFile.getName();
3278                final String dstFileName = srcFileName.substring(
3279                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3280                final File dstFile = new File(dstCodePath, dstFileName);
3281                ret = decompressFile(srcFile, dstFile);
3282                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3283                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3284                            + "; pkg: " + pkg.packageName
3285                            + ", file: " + dstFileName);
3286                    break;
3287                }
3288            }
3289        } catch (ErrnoException e) {
3290            logCriticalInfo(Log.ERROR, "Failed to decompress"
3291                    + "; pkg: " + pkg.packageName
3292                    + ", err: " + e.errno);
3293        }
3294        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3295            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3296            NativeLibraryHelper.Handle handle = null;
3297            try {
3298                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3299                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3300                        null /*abiOverride*/);
3301            } catch (IOException e) {
3302                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3303                        + "; pkg: " + pkg.packageName);
3304                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3305            } finally {
3306                IoUtils.closeQuietly(handle);
3307            }
3308        }
3309        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3310            if (dstCodePath == null || !dstCodePath.exists()) {
3311                return null;
3312            }
3313            removeCodePathLI(dstCodePath);
3314            return null;
3315        }
3316
3317        return dstCodePath;
3318    }
3319
3320    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3321        // we're only interested in updating the installer appliction when 1) it's not
3322        // already set or 2) the modified package is the installer
3323        if (mInstantAppInstallerActivity != null
3324                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3325                        .equals(modifiedPackage)) {
3326            return;
3327        }
3328        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3329    }
3330
3331    private static File preparePackageParserCache(boolean isUpgrade) {
3332        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3333            return null;
3334        }
3335
3336        // Disable package parsing on eng builds to allow for faster incremental development.
3337        if (Build.IS_ENG) {
3338            return null;
3339        }
3340
3341        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3342            Slog.i(TAG, "Disabling package parser cache due to system property.");
3343            return null;
3344        }
3345
3346        // The base directory for the package parser cache lives under /data/system/.
3347        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3348                "package_cache");
3349        if (cacheBaseDir == null) {
3350            return null;
3351        }
3352
3353        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3354        // This also serves to "GC" unused entries when the package cache version changes (which
3355        // can only happen during upgrades).
3356        if (isUpgrade) {
3357            FileUtils.deleteContents(cacheBaseDir);
3358        }
3359
3360
3361        // Return the versioned package cache directory. This is something like
3362        // "/data/system/package_cache/1"
3363        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3364
3365        // The following is a workaround to aid development on non-numbered userdebug
3366        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3367        // the system partition is newer.
3368        //
3369        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3370        // that starts with "eng." to signify that this is an engineering build and not
3371        // destined for release.
3372        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3373            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3374
3375            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3376            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3377            // in general and should not be used for production changes. In this specific case,
3378            // we know that they will work.
3379            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3380            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3381                FileUtils.deleteContents(cacheBaseDir);
3382                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3383            }
3384        }
3385
3386        return cacheDir;
3387    }
3388
3389    @Override
3390    public boolean isFirstBoot() {
3391        // allow instant applications
3392        return mFirstBoot;
3393    }
3394
3395    @Override
3396    public boolean isOnlyCoreApps() {
3397        // allow instant applications
3398        return mOnlyCore;
3399    }
3400
3401    @Override
3402    public boolean isUpgrade() {
3403        // allow instant applications
3404        // The system property allows testing ota flow when upgraded to the same image.
3405        return mIsUpgrade || SystemProperties.getBoolean(
3406                "persist.pm.mock-upgrade", false /* default */);
3407    }
3408
3409    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3410        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3411
3412        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3413                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3414                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3415        if (matches.size() == 1) {
3416            return matches.get(0).getComponentInfo().packageName;
3417        } else if (matches.size() == 0) {
3418            Log.e(TAG, "There should probably be a verifier, but, none were found");
3419            return null;
3420        }
3421        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3422    }
3423
3424    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3425        synchronized (mPackages) {
3426            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3427            if (libraryEntry == null) {
3428                throw new IllegalStateException("Missing required shared library:" + name);
3429            }
3430            return libraryEntry.apk;
3431        }
3432    }
3433
3434    private @NonNull String getRequiredInstallerLPr() {
3435        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3436        intent.addCategory(Intent.CATEGORY_DEFAULT);
3437        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3438
3439        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3440                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3441                UserHandle.USER_SYSTEM);
3442        if (matches.size() == 1) {
3443            ResolveInfo resolveInfo = matches.get(0);
3444            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3445                throw new RuntimeException("The installer must be a privileged app");
3446            }
3447            return matches.get(0).getComponentInfo().packageName;
3448        } else {
3449            throw new RuntimeException("There must be exactly one installer; found " + matches);
3450        }
3451    }
3452
3453    private @NonNull String getRequiredUninstallerLPr() {
3454        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3455        intent.addCategory(Intent.CATEGORY_DEFAULT);
3456        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3457
3458        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3459                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3460                UserHandle.USER_SYSTEM);
3461        if (resolveInfo == null ||
3462                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3463            throw new RuntimeException("There must be exactly one uninstaller; found "
3464                    + resolveInfo);
3465        }
3466        return resolveInfo.getComponentInfo().packageName;
3467    }
3468
3469    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3470        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3471
3472        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3473                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3474                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3475        ResolveInfo best = null;
3476        final int N = matches.size();
3477        for (int i = 0; i < N; i++) {
3478            final ResolveInfo cur = matches.get(i);
3479            final String packageName = cur.getComponentInfo().packageName;
3480            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3481                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3482                continue;
3483            }
3484
3485            if (best == null || cur.priority > best.priority) {
3486                best = cur;
3487            }
3488        }
3489
3490        if (best != null) {
3491            return best.getComponentInfo().getComponentName();
3492        }
3493        Slog.w(TAG, "Intent filter verifier not found");
3494        return null;
3495    }
3496
3497    @Override
3498    public @Nullable ComponentName getInstantAppResolverComponent() {
3499        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3500            return null;
3501        }
3502        synchronized (mPackages) {
3503            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3504            if (instantAppResolver == null) {
3505                return null;
3506            }
3507            return instantAppResolver.first;
3508        }
3509    }
3510
3511    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3512        final String[] packageArray =
3513                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3514        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3515            if (DEBUG_INSTANT) {
3516                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3517            }
3518            return null;
3519        }
3520
3521        final int callingUid = Binder.getCallingUid();
3522        final int resolveFlags =
3523                MATCH_DIRECT_BOOT_AWARE
3524                | MATCH_DIRECT_BOOT_UNAWARE
3525                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3526        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3527        final Intent resolverIntent = new Intent(actionName);
3528        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3529                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3530        final int N = resolvers.size();
3531        if (N == 0) {
3532            if (DEBUG_INSTANT) {
3533                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3534            }
3535            return null;
3536        }
3537
3538        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3539        for (int i = 0; i < N; i++) {
3540            final ResolveInfo info = resolvers.get(i);
3541
3542            if (info.serviceInfo == null) {
3543                continue;
3544            }
3545
3546            final String packageName = info.serviceInfo.packageName;
3547            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3548                if (DEBUG_INSTANT) {
3549                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3550                            + " pkg: " + packageName + ", info:" + info);
3551                }
3552                continue;
3553            }
3554
3555            if (DEBUG_INSTANT) {
3556                Slog.v(TAG, "Ephemeral resolver found;"
3557                        + " pkg: " + packageName + ", info:" + info);
3558            }
3559            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3560        }
3561        if (DEBUG_INSTANT) {
3562            Slog.v(TAG, "Ephemeral resolver NOT found");
3563        }
3564        return null;
3565    }
3566
3567    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3568        String[] orderedActions = Build.IS_ENG
3569                ? new String[]{
3570                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3571                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3572                : new String[]{
3573                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3574
3575        final int resolveFlags =
3576                MATCH_DIRECT_BOOT_AWARE
3577                        | MATCH_DIRECT_BOOT_UNAWARE
3578                        | Intent.FLAG_IGNORE_EPHEMERAL
3579                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3580        final Intent intent = new Intent();
3581        intent.addCategory(Intent.CATEGORY_DEFAULT);
3582        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3583        List<ResolveInfo> matches = null;
3584        for (String action : orderedActions) {
3585            intent.setAction(action);
3586            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3587                    resolveFlags, UserHandle.USER_SYSTEM);
3588            if (matches.isEmpty()) {
3589                if (DEBUG_INSTANT) {
3590                    Slog.d(TAG, "Instant App installer not found with " + action);
3591                }
3592            } else {
3593                break;
3594            }
3595        }
3596        Iterator<ResolveInfo> iter = matches.iterator();
3597        while (iter.hasNext()) {
3598            final ResolveInfo rInfo = iter.next();
3599            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3600            if (ps != null) {
3601                final PermissionsState permissionsState = ps.getPermissionsState();
3602                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3603                        || Build.IS_ENG) {
3604                    continue;
3605                }
3606            }
3607            iter.remove();
3608        }
3609        if (matches.size() == 0) {
3610            return null;
3611        } else if (matches.size() == 1) {
3612            return (ActivityInfo) matches.get(0).getComponentInfo();
3613        } else {
3614            throw new RuntimeException(
3615                    "There must be at most one ephemeral installer; found " + matches);
3616        }
3617    }
3618
3619    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3620            @NonNull ComponentName resolver) {
3621        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3622                .addCategory(Intent.CATEGORY_DEFAULT)
3623                .setPackage(resolver.getPackageName());
3624        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3625        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3626                UserHandle.USER_SYSTEM);
3627        if (matches.isEmpty()) {
3628            return null;
3629        }
3630        return matches.get(0).getComponentInfo().getComponentName();
3631    }
3632
3633    private void primeDomainVerificationsLPw(int userId) {
3634        if (DEBUG_DOMAIN_VERIFICATION) {
3635            Slog.d(TAG, "Priming domain verifications in user " + userId);
3636        }
3637
3638        SystemConfig systemConfig = SystemConfig.getInstance();
3639        ArraySet<String> packages = systemConfig.getLinkedApps();
3640
3641        for (String packageName : packages) {
3642            PackageParser.Package pkg = mPackages.get(packageName);
3643            if (pkg != null) {
3644                if (!pkg.isSystem()) {
3645                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3646                    continue;
3647                }
3648
3649                ArraySet<String> domains = null;
3650                for (PackageParser.Activity a : pkg.activities) {
3651                    for (ActivityIntentInfo filter : a.intents) {
3652                        if (hasValidDomains(filter)) {
3653                            if (domains == null) {
3654                                domains = new ArraySet<String>();
3655                            }
3656                            domains.addAll(filter.getHostsList());
3657                        }
3658                    }
3659                }
3660
3661                if (domains != null && domains.size() > 0) {
3662                    if (DEBUG_DOMAIN_VERIFICATION) {
3663                        Slog.v(TAG, "      + " + packageName);
3664                    }
3665                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3666                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3667                    // and then 'always' in the per-user state actually used for intent resolution.
3668                    final IntentFilterVerificationInfo ivi;
3669                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3670                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3671                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3672                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3673                } else {
3674                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3675                            + "' does not handle web links");
3676                }
3677            } else {
3678                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3679            }
3680        }
3681
3682        scheduleWritePackageRestrictionsLocked(userId);
3683        scheduleWriteSettingsLocked();
3684    }
3685
3686    private void applyFactoryDefaultBrowserLPw(int userId) {
3687        // The default browser app's package name is stored in a string resource,
3688        // with a product-specific overlay used for vendor customization.
3689        String browserPkg = mContext.getResources().getString(
3690                com.android.internal.R.string.default_browser);
3691        if (!TextUtils.isEmpty(browserPkg)) {
3692            // non-empty string => required to be a known package
3693            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3694            if (ps == null) {
3695                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3696                browserPkg = null;
3697            } else {
3698                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3699            }
3700        }
3701
3702        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3703        // default.  If there's more than one, just leave everything alone.
3704        if (browserPkg == null) {
3705            calculateDefaultBrowserLPw(userId);
3706        }
3707    }
3708
3709    private void calculateDefaultBrowserLPw(int userId) {
3710        List<String> allBrowsers = resolveAllBrowserApps(userId);
3711        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3712        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3713    }
3714
3715    private List<String> resolveAllBrowserApps(int userId) {
3716        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3717        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3718                PackageManager.MATCH_ALL, userId);
3719
3720        final int count = list.size();
3721        List<String> result = new ArrayList<String>(count);
3722        for (int i=0; i<count; i++) {
3723            ResolveInfo info = list.get(i);
3724            if (info.activityInfo == null
3725                    || !info.handleAllWebDataURI
3726                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3727                    || result.contains(info.activityInfo.packageName)) {
3728                continue;
3729            }
3730            result.add(info.activityInfo.packageName);
3731        }
3732
3733        return result;
3734    }
3735
3736    private boolean packageIsBrowser(String packageName, int userId) {
3737        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3738                PackageManager.MATCH_ALL, userId);
3739        final int N = list.size();
3740        for (int i = 0; i < N; i++) {
3741            ResolveInfo info = list.get(i);
3742            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3743                return true;
3744            }
3745        }
3746        return false;
3747    }
3748
3749    private void checkDefaultBrowser() {
3750        final int myUserId = UserHandle.myUserId();
3751        final String packageName = getDefaultBrowserPackageName(myUserId);
3752        if (packageName != null) {
3753            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3754            if (info == null) {
3755                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3756                synchronized (mPackages) {
3757                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3758                }
3759            }
3760        }
3761    }
3762
3763    @Override
3764    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3765            throws RemoteException {
3766        try {
3767            return super.onTransact(code, data, reply, flags);
3768        } catch (RuntimeException e) {
3769            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3770                Slog.wtf(TAG, "Package Manager Crash", e);
3771            }
3772            throw e;
3773        }
3774    }
3775
3776    static int[] appendInts(int[] cur, int[] add) {
3777        if (add == null) return cur;
3778        if (cur == null) return add;
3779        final int N = add.length;
3780        for (int i=0; i<N; i++) {
3781            cur = appendInt(cur, add[i]);
3782        }
3783        return cur;
3784    }
3785
3786    /**
3787     * Returns whether or not a full application can see an instant application.
3788     * <p>
3789     * Currently, there are three cases in which this can occur:
3790     * <ol>
3791     * <li>The calling application is a "special" process. Special processes
3792     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3793     * <li>The calling application has the permission
3794     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3795     * <li>The calling application is the default launcher on the
3796     *     system partition.</li>
3797     * </ol>
3798     */
3799    private boolean canViewInstantApps(int callingUid, int userId) {
3800        if (callingUid < Process.FIRST_APPLICATION_UID) {
3801            return true;
3802        }
3803        if (mContext.checkCallingOrSelfPermission(
3804                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3805            return true;
3806        }
3807        if (mContext.checkCallingOrSelfPermission(
3808                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3809            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3810            if (homeComponent != null
3811                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3812                return true;
3813            }
3814        }
3815        return false;
3816    }
3817
3818    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3819        if (!sUserManager.exists(userId)) return null;
3820        if (ps == null) {
3821            return null;
3822        }
3823        final int callingUid = Binder.getCallingUid();
3824        // Filter out ephemeral app metadata:
3825        //   * The system/shell/root can see metadata for any app
3826        //   * An installed app can see metadata for 1) other installed apps
3827        //     and 2) ephemeral apps that have explicitly interacted with it
3828        //   * Ephemeral apps can only see their own data and exposed installed apps
3829        //   * Holding a signature permission allows seeing instant apps
3830        if (filterAppAccessLPr(ps, callingUid, userId)) {
3831            return null;
3832        }
3833
3834        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3835                && ps.isSystem()) {
3836            flags |= MATCH_ANY_USER;
3837        }
3838
3839        final PackageUserState state = ps.readUserState(userId);
3840        PackageParser.Package p = ps.pkg;
3841        if (p != null) {
3842            final PermissionsState permissionsState = ps.getPermissionsState();
3843
3844            // Compute GIDs only if requested
3845            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3846                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3847            // Compute granted permissions only if package has requested permissions
3848            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3849                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3850
3851            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3852                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3853
3854            if (packageInfo == null) {
3855                return null;
3856            }
3857
3858            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3859                    resolveExternalPackageNameLPr(p);
3860
3861            return packageInfo;
3862        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3863            PackageInfo pi = new PackageInfo();
3864            pi.packageName = ps.name;
3865            pi.setLongVersionCode(ps.versionCode);
3866            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3867            pi.firstInstallTime = ps.firstInstallTime;
3868            pi.lastUpdateTime = ps.lastUpdateTime;
3869
3870            ApplicationInfo ai = new ApplicationInfo();
3871            ai.packageName = ps.name;
3872            ai.uid = UserHandle.getUid(userId, ps.appId);
3873            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3874            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3875            ai.versionCode = ps.versionCode;
3876            ai.flags = ps.pkgFlags;
3877            ai.privateFlags = ps.pkgPrivateFlags;
3878            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3879
3880            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3881                    + ps.name + "]. Provides a minimum info.");
3882            return pi;
3883        } else {
3884            return null;
3885        }
3886    }
3887
3888    @Override
3889    public void checkPackageStartable(String packageName, int userId) {
3890        final int callingUid = Binder.getCallingUid();
3891        if (getInstantAppPackageName(callingUid) != null) {
3892            throw new SecurityException("Instant applications don't have access to this method");
3893        }
3894        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3895        synchronized (mPackages) {
3896            final PackageSetting ps = mSettings.mPackages.get(packageName);
3897            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3898                throw new SecurityException("Package " + packageName + " was not found!");
3899            }
3900
3901            if (!ps.getInstalled(userId)) {
3902                throw new SecurityException(
3903                        "Package " + packageName + " was not installed for user " + userId + "!");
3904            }
3905
3906            if (mSafeMode && !ps.isSystem()) {
3907                throw new SecurityException("Package " + packageName + " not a system app!");
3908            }
3909
3910            if (mFrozenPackages.contains(packageName)) {
3911                throw new SecurityException("Package " + packageName + " is currently frozen!");
3912            }
3913
3914            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3915                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3916            }
3917        }
3918    }
3919
3920    @Override
3921    public boolean isPackageAvailable(String packageName, int userId) {
3922        if (!sUserManager.exists(userId)) return false;
3923        final int callingUid = Binder.getCallingUid();
3924        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3925                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3926        synchronized (mPackages) {
3927            PackageParser.Package p = mPackages.get(packageName);
3928            if (p != null) {
3929                final PackageSetting ps = (PackageSetting) p.mExtras;
3930                if (filterAppAccessLPr(ps, callingUid, userId)) {
3931                    return false;
3932                }
3933                if (ps != null) {
3934                    final PackageUserState state = ps.readUserState(userId);
3935                    if (state != null) {
3936                        return PackageParser.isAvailable(state);
3937                    }
3938                }
3939            }
3940        }
3941        return false;
3942    }
3943
3944    @Override
3945    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3946        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3947                flags, Binder.getCallingUid(), userId);
3948    }
3949
3950    @Override
3951    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3952            int flags, int userId) {
3953        return getPackageInfoInternal(versionedPackage.getPackageName(),
3954                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3955    }
3956
3957    /**
3958     * Important: The provided filterCallingUid is used exclusively to filter out packages
3959     * that can be seen based on user state. It's typically the original caller uid prior
3960     * to clearing. Because it can only be provided by trusted code, it's value can be
3961     * trusted and will be used as-is; unlike userId which will be validated by this method.
3962     */
3963    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3964            int flags, int filterCallingUid, int userId) {
3965        if (!sUserManager.exists(userId)) return null;
3966        flags = updateFlagsForPackage(flags, userId, packageName);
3967        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3968                false /* requireFullPermission */, false /* checkShell */, "get package info");
3969
3970        // reader
3971        synchronized (mPackages) {
3972            // Normalize package name to handle renamed packages and static libs
3973            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3974
3975            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3976            if (matchFactoryOnly) {
3977                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3978                if (ps != null) {
3979                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3980                        return null;
3981                    }
3982                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3983                        return null;
3984                    }
3985                    return generatePackageInfo(ps, flags, userId);
3986                }
3987            }
3988
3989            PackageParser.Package p = mPackages.get(packageName);
3990            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3991                return null;
3992            }
3993            if (DEBUG_PACKAGE_INFO)
3994                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3995            if (p != null) {
3996                final PackageSetting ps = (PackageSetting) p.mExtras;
3997                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3998                    return null;
3999                }
4000                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4001                    return null;
4002                }
4003                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4004            }
4005            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4006                final PackageSetting ps = mSettings.mPackages.get(packageName);
4007                if (ps == null) return null;
4008                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4009                    return null;
4010                }
4011                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4012                    return null;
4013                }
4014                return generatePackageInfo(ps, flags, userId);
4015            }
4016        }
4017        return null;
4018    }
4019
4020    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4021        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4022            return true;
4023        }
4024        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4025            return true;
4026        }
4027        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4028            return true;
4029        }
4030        return false;
4031    }
4032
4033    private boolean isComponentVisibleToInstantApp(
4034            @Nullable ComponentName component, @ComponentType int type) {
4035        if (type == TYPE_ACTIVITY) {
4036            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4037            return activity != null
4038                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4039                    : false;
4040        } else if (type == TYPE_RECEIVER) {
4041            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4042            return activity != null
4043                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4044                    : false;
4045        } else if (type == TYPE_SERVICE) {
4046            final PackageParser.Service service = mServices.mServices.get(component);
4047            return service != null
4048                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4049                    : false;
4050        } else if (type == TYPE_PROVIDER) {
4051            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4052            return provider != null
4053                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4054                    : false;
4055        } else if (type == TYPE_UNKNOWN) {
4056            return isComponentVisibleToInstantApp(component);
4057        }
4058        return false;
4059    }
4060
4061    /**
4062     * Returns whether or not access to the application should be filtered.
4063     * <p>
4064     * Access may be limited based upon whether the calling or target applications
4065     * are instant applications.
4066     *
4067     * @see #canAccessInstantApps(int)
4068     */
4069    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4070            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4071        // if we're in an isolated process, get the real calling UID
4072        if (Process.isIsolated(callingUid)) {
4073            callingUid = mIsolatedOwners.get(callingUid);
4074        }
4075        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4076        final boolean callerIsInstantApp = instantAppPkgName != null;
4077        if (ps == null) {
4078            if (callerIsInstantApp) {
4079                // pretend the application exists, but, needs to be filtered
4080                return true;
4081            }
4082            return false;
4083        }
4084        // if the target and caller are the same application, don't filter
4085        if (isCallerSameApp(ps.name, callingUid)) {
4086            return false;
4087        }
4088        if (callerIsInstantApp) {
4089            // request for a specific component; if it hasn't been explicitly exposed, filter
4090            if (component != null) {
4091                return !isComponentVisibleToInstantApp(component, componentType);
4092            }
4093            // request for application; if no components have been explicitly exposed, filter
4094            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4095        }
4096        if (ps.getInstantApp(userId)) {
4097            // caller can see all components of all instant applications, don't filter
4098            if (canViewInstantApps(callingUid, userId)) {
4099                return false;
4100            }
4101            // request for a specific instant application component, filter
4102            if (component != null) {
4103                return true;
4104            }
4105            // request for an instant application; if the caller hasn't been granted access, filter
4106            return !mInstantAppRegistry.isInstantAccessGranted(
4107                    userId, UserHandle.getAppId(callingUid), ps.appId);
4108        }
4109        return false;
4110    }
4111
4112    /**
4113     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4114     */
4115    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4116        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4117    }
4118
4119    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4120            int flags) {
4121        // Callers can access only the libs they depend on, otherwise they need to explicitly
4122        // ask for the shared libraries given the caller is allowed to access all static libs.
4123        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4124            // System/shell/root get to see all static libs
4125            final int appId = UserHandle.getAppId(uid);
4126            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4127                    || appId == Process.ROOT_UID) {
4128                return false;
4129            }
4130        }
4131
4132        // No package means no static lib as it is always on internal storage
4133        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4134            return false;
4135        }
4136
4137        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4138                ps.pkg.staticSharedLibVersion);
4139        if (libEntry == null) {
4140            return false;
4141        }
4142
4143        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4144        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4145        if (uidPackageNames == null) {
4146            return true;
4147        }
4148
4149        for (String uidPackageName : uidPackageNames) {
4150            if (ps.name.equals(uidPackageName)) {
4151                return false;
4152            }
4153            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4154            if (uidPs != null) {
4155                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4156                        libEntry.info.getName());
4157                if (index < 0) {
4158                    continue;
4159                }
4160                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4161                    return false;
4162                }
4163            }
4164        }
4165        return true;
4166    }
4167
4168    @Override
4169    public String[] currentToCanonicalPackageNames(String[] names) {
4170        final int callingUid = Binder.getCallingUid();
4171        if (getInstantAppPackageName(callingUid) != null) {
4172            return names;
4173        }
4174        final String[] out = new String[names.length];
4175        // reader
4176        synchronized (mPackages) {
4177            final int callingUserId = UserHandle.getUserId(callingUid);
4178            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4179            for (int i=names.length-1; i>=0; i--) {
4180                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4181                boolean translateName = false;
4182                if (ps != null && ps.realName != null) {
4183                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4184                    translateName = !targetIsInstantApp
4185                            || canViewInstantApps
4186                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4187                                    UserHandle.getAppId(callingUid), ps.appId);
4188                }
4189                out[i] = translateName ? ps.realName : names[i];
4190            }
4191        }
4192        return out;
4193    }
4194
4195    @Override
4196    public String[] canonicalToCurrentPackageNames(String[] names) {
4197        final int callingUid = Binder.getCallingUid();
4198        if (getInstantAppPackageName(callingUid) != null) {
4199            return names;
4200        }
4201        final String[] out = new String[names.length];
4202        // reader
4203        synchronized (mPackages) {
4204            final int callingUserId = UserHandle.getUserId(callingUid);
4205            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4206            for (int i=names.length-1; i>=0; i--) {
4207                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4208                boolean translateName = false;
4209                if (cur != null) {
4210                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4211                    final boolean targetIsInstantApp =
4212                            ps != null && ps.getInstantApp(callingUserId);
4213                    translateName = !targetIsInstantApp
4214                            || canViewInstantApps
4215                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4216                                    UserHandle.getAppId(callingUid), ps.appId);
4217                }
4218                out[i] = translateName ? cur : names[i];
4219            }
4220        }
4221        return out;
4222    }
4223
4224    @Override
4225    public int getPackageUid(String packageName, int flags, int userId) {
4226        if (!sUserManager.exists(userId)) return -1;
4227        final int callingUid = Binder.getCallingUid();
4228        flags = updateFlagsForPackage(flags, userId, packageName);
4229        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4230                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4231
4232        // reader
4233        synchronized (mPackages) {
4234            final PackageParser.Package p = mPackages.get(packageName);
4235            if (p != null && p.isMatch(flags)) {
4236                PackageSetting ps = (PackageSetting) p.mExtras;
4237                if (filterAppAccessLPr(ps, callingUid, userId)) {
4238                    return -1;
4239                }
4240                return UserHandle.getUid(userId, p.applicationInfo.uid);
4241            }
4242            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4243                final PackageSetting ps = mSettings.mPackages.get(packageName);
4244                if (ps != null && ps.isMatch(flags)
4245                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4246                    return UserHandle.getUid(userId, ps.appId);
4247                }
4248            }
4249        }
4250
4251        return -1;
4252    }
4253
4254    @Override
4255    public int[] getPackageGids(String packageName, int flags, int userId) {
4256        if (!sUserManager.exists(userId)) return null;
4257        final int callingUid = Binder.getCallingUid();
4258        flags = updateFlagsForPackage(flags, userId, packageName);
4259        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4260                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4261
4262        // reader
4263        synchronized (mPackages) {
4264            final PackageParser.Package p = mPackages.get(packageName);
4265            if (p != null && p.isMatch(flags)) {
4266                PackageSetting ps = (PackageSetting) p.mExtras;
4267                if (filterAppAccessLPr(ps, callingUid, userId)) {
4268                    return null;
4269                }
4270                // TODO: Shouldn't this be checking for package installed state for userId and
4271                // return null?
4272                return ps.getPermissionsState().computeGids(userId);
4273            }
4274            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4275                final PackageSetting ps = mSettings.mPackages.get(packageName);
4276                if (ps != null && ps.isMatch(flags)
4277                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4278                    return ps.getPermissionsState().computeGids(userId);
4279                }
4280            }
4281        }
4282
4283        return null;
4284    }
4285
4286    @Override
4287    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4288        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4289    }
4290
4291    @Override
4292    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4293            int flags) {
4294        final List<PermissionInfo> permissionList =
4295                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4296        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4297    }
4298
4299    @Override
4300    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4301        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4302    }
4303
4304    @Override
4305    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4306        final List<PermissionGroupInfo> permissionList =
4307                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4308        return (permissionList == null)
4309                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4310    }
4311
4312    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4313            int filterCallingUid, int userId) {
4314        if (!sUserManager.exists(userId)) return null;
4315        PackageSetting ps = mSettings.mPackages.get(packageName);
4316        if (ps != null) {
4317            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4318                return null;
4319            }
4320            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4321                return null;
4322            }
4323            if (ps.pkg == null) {
4324                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4325                if (pInfo != null) {
4326                    return pInfo.applicationInfo;
4327                }
4328                return null;
4329            }
4330            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4331                    ps.readUserState(userId), userId);
4332            if (ai != null) {
4333                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4334            }
4335            return ai;
4336        }
4337        return null;
4338    }
4339
4340    @Override
4341    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4342        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4343    }
4344
4345    /**
4346     * Important: The provided filterCallingUid is used exclusively to filter out applications
4347     * that can be seen based on user state. It's typically the original caller uid prior
4348     * to clearing. Because it can only be provided by trusted code, it's value can be
4349     * trusted and will be used as-is; unlike userId which will be validated by this method.
4350     */
4351    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4352            int filterCallingUid, int userId) {
4353        if (!sUserManager.exists(userId)) return null;
4354        flags = updateFlagsForApplication(flags, userId, packageName);
4355        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4356                false /* requireFullPermission */, false /* checkShell */, "get application info");
4357
4358        // writer
4359        synchronized (mPackages) {
4360            // Normalize package name to handle renamed packages and static libs
4361            packageName = resolveInternalPackageNameLPr(packageName,
4362                    PackageManager.VERSION_CODE_HIGHEST);
4363
4364            PackageParser.Package p = mPackages.get(packageName);
4365            if (DEBUG_PACKAGE_INFO) Log.v(
4366                    TAG, "getApplicationInfo " + packageName
4367                    + ": " + p);
4368            if (p != null) {
4369                PackageSetting ps = mSettings.mPackages.get(packageName);
4370                if (ps == null) return null;
4371                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4372                    return null;
4373                }
4374                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4375                    return null;
4376                }
4377                // Note: isEnabledLP() does not apply here - always return info
4378                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4379                        p, flags, ps.readUserState(userId), userId);
4380                if (ai != null) {
4381                    ai.packageName = resolveExternalPackageNameLPr(p);
4382                }
4383                return ai;
4384            }
4385            if ("android".equals(packageName)||"system".equals(packageName)) {
4386                return mAndroidApplication;
4387            }
4388            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4389                // Already generates the external package name
4390                return generateApplicationInfoFromSettingsLPw(packageName,
4391                        flags, filterCallingUid, userId);
4392            }
4393        }
4394        return null;
4395    }
4396
4397    private String normalizePackageNameLPr(String packageName) {
4398        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4399        return normalizedPackageName != null ? normalizedPackageName : packageName;
4400    }
4401
4402    @Override
4403    public void deletePreloadsFileCache() {
4404        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4405            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4406        }
4407        File dir = Environment.getDataPreloadsFileCacheDirectory();
4408        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4409        FileUtils.deleteContents(dir);
4410    }
4411
4412    @Override
4413    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4414            final int storageFlags, final IPackageDataObserver observer) {
4415        mContext.enforceCallingOrSelfPermission(
4416                android.Manifest.permission.CLEAR_APP_CACHE, null);
4417        mHandler.post(() -> {
4418            boolean success = false;
4419            try {
4420                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4421                success = true;
4422            } catch (IOException e) {
4423                Slog.w(TAG, e);
4424            }
4425            if (observer != null) {
4426                try {
4427                    observer.onRemoveCompleted(null, success);
4428                } catch (RemoteException e) {
4429                    Slog.w(TAG, e);
4430                }
4431            }
4432        });
4433    }
4434
4435    @Override
4436    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4437            final int storageFlags, final IntentSender pi) {
4438        mContext.enforceCallingOrSelfPermission(
4439                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4440        mHandler.post(() -> {
4441            boolean success = false;
4442            try {
4443                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4444                success = true;
4445            } catch (IOException e) {
4446                Slog.w(TAG, e);
4447            }
4448            if (pi != null) {
4449                try {
4450                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4451                } catch (SendIntentException e) {
4452                    Slog.w(TAG, e);
4453                }
4454            }
4455        });
4456    }
4457
4458    /**
4459     * Blocking call to clear various types of cached data across the system
4460     * until the requested bytes are available.
4461     */
4462    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4463        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4464        final File file = storage.findPathForUuid(volumeUuid);
4465        if (file.getUsableSpace() >= bytes) return;
4466
4467        if (ENABLE_FREE_CACHE_V2) {
4468            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4469                    volumeUuid);
4470            final boolean aggressive = (storageFlags
4471                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4472            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4473
4474            // 1. Pre-flight to determine if we have any chance to succeed
4475            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4476            if (internalVolume && (aggressive || SystemProperties
4477                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4478                deletePreloadsFileCache();
4479                if (file.getUsableSpace() >= bytes) return;
4480            }
4481
4482            // 3. Consider parsed APK data (aggressive only)
4483            if (internalVolume && aggressive) {
4484                FileUtils.deleteContents(mCacheDir);
4485                if (file.getUsableSpace() >= bytes) return;
4486            }
4487
4488            // 4. Consider cached app data (above quotas)
4489            try {
4490                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4491                        Installer.FLAG_FREE_CACHE_V2);
4492            } catch (InstallerException ignored) {
4493            }
4494            if (file.getUsableSpace() >= bytes) return;
4495
4496            // 5. Consider shared libraries with refcount=0 and age>min cache period
4497            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4498                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4499                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4500                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4501                return;
4502            }
4503
4504            // 6. Consider dexopt output (aggressive only)
4505            // TODO: Implement
4506
4507            // 7. Consider installed instant apps unused longer than min cache period
4508            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4509                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4510                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4511                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4512                return;
4513            }
4514
4515            // 8. Consider cached app data (below quotas)
4516            try {
4517                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4518                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4519            } catch (InstallerException ignored) {
4520            }
4521            if (file.getUsableSpace() >= bytes) return;
4522
4523            // 9. Consider DropBox entries
4524            // TODO: Implement
4525
4526            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4527            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4528                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4529                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4530                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4531                return;
4532            }
4533        } else {
4534            try {
4535                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4536            } catch (InstallerException ignored) {
4537            }
4538            if (file.getUsableSpace() >= bytes) return;
4539        }
4540
4541        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4542    }
4543
4544    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4545            throws IOException {
4546        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4547        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4548
4549        List<VersionedPackage> packagesToDelete = null;
4550        final long now = System.currentTimeMillis();
4551
4552        synchronized (mPackages) {
4553            final int[] allUsers = sUserManager.getUserIds();
4554            final int libCount = mSharedLibraries.size();
4555            for (int i = 0; i < libCount; i++) {
4556                final LongSparseArray<SharedLibraryEntry> versionedLib
4557                        = mSharedLibraries.valueAt(i);
4558                if (versionedLib == null) {
4559                    continue;
4560                }
4561                final int versionCount = versionedLib.size();
4562                for (int j = 0; j < versionCount; j++) {
4563                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4564                    // Skip packages that are not static shared libs.
4565                    if (!libInfo.isStatic()) {
4566                        break;
4567                    }
4568                    // Important: We skip static shared libs used for some user since
4569                    // in such a case we need to keep the APK on the device. The check for
4570                    // a lib being used for any user is performed by the uninstall call.
4571                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4572                    // Resolve the package name - we use synthetic package names internally
4573                    final String internalPackageName = resolveInternalPackageNameLPr(
4574                            declaringPackage.getPackageName(),
4575                            declaringPackage.getLongVersionCode());
4576                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4577                    // Skip unused static shared libs cached less than the min period
4578                    // to prevent pruning a lib needed by a subsequently installed package.
4579                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4580                        continue;
4581                    }
4582                    if (packagesToDelete == null) {
4583                        packagesToDelete = new ArrayList<>();
4584                    }
4585                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4586                            declaringPackage.getLongVersionCode()));
4587                }
4588            }
4589        }
4590
4591        if (packagesToDelete != null) {
4592            final int packageCount = packagesToDelete.size();
4593            for (int i = 0; i < packageCount; i++) {
4594                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4595                // Delete the package synchronously (will fail of the lib used for any user).
4596                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4597                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4598                                == PackageManager.DELETE_SUCCEEDED) {
4599                    if (volume.getUsableSpace() >= neededSpace) {
4600                        return true;
4601                    }
4602                }
4603            }
4604        }
4605
4606        return false;
4607    }
4608
4609    /**
4610     * Update given flags based on encryption status of current user.
4611     */
4612    private int updateFlags(int flags, int userId) {
4613        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4614                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4615            // Caller expressed an explicit opinion about what encryption
4616            // aware/unaware components they want to see, so fall through and
4617            // give them what they want
4618        } else {
4619            // Caller expressed no opinion, so match based on user state
4620            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4621                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4622            } else {
4623                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4624            }
4625        }
4626        return flags;
4627    }
4628
4629    private UserManagerInternal getUserManagerInternal() {
4630        if (mUserManagerInternal == null) {
4631            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4632        }
4633        return mUserManagerInternal;
4634    }
4635
4636    private ActivityManagerInternal getActivityManagerInternal() {
4637        if (mActivityManagerInternal == null) {
4638            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4639        }
4640        return mActivityManagerInternal;
4641    }
4642
4643
4644    private DeviceIdleController.LocalService getDeviceIdleController() {
4645        if (mDeviceIdleController == null) {
4646            mDeviceIdleController =
4647                    LocalServices.getService(DeviceIdleController.LocalService.class);
4648        }
4649        return mDeviceIdleController;
4650    }
4651
4652    /**
4653     * Update given flags when being used to request {@link PackageInfo}.
4654     */
4655    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4656        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4657        boolean triaged = true;
4658        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4659                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4660            // Caller is asking for component details, so they'd better be
4661            // asking for specific encryption matching behavior, or be triaged
4662            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4663                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4664                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4665                triaged = false;
4666            }
4667        }
4668        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4669                | PackageManager.MATCH_SYSTEM_ONLY
4670                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4671            triaged = false;
4672        }
4673        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4674            mPermissionManager.enforceCrossUserPermission(
4675                    Binder.getCallingUid(), userId, false, false,
4676                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4677                    + Debug.getCallers(5));
4678        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4679                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4680            // If the caller wants all packages and has a restricted profile associated with it,
4681            // then match all users. This is to make sure that launchers that need to access work
4682            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4683            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4684            flags |= PackageManager.MATCH_ANY_USER;
4685        }
4686        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4687            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4688                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4689        }
4690        return updateFlags(flags, userId);
4691    }
4692
4693    /**
4694     * Update given flags when being used to request {@link ApplicationInfo}.
4695     */
4696    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4697        return updateFlagsForPackage(flags, userId, cookie);
4698    }
4699
4700    /**
4701     * Update given flags when being used to request {@link ComponentInfo}.
4702     */
4703    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4704        if (cookie instanceof Intent) {
4705            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4706                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4707            }
4708        }
4709
4710        boolean triaged = true;
4711        // Caller is asking for component details, so they'd better be
4712        // asking for specific encryption matching behavior, or be triaged
4713        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4714                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4715                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4716            triaged = false;
4717        }
4718        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4719            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4720                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4721        }
4722
4723        return updateFlags(flags, userId);
4724    }
4725
4726    /**
4727     * Update given intent when being used to request {@link ResolveInfo}.
4728     */
4729    private Intent updateIntentForResolve(Intent intent) {
4730        if (intent.getSelector() != null) {
4731            intent = intent.getSelector();
4732        }
4733        if (DEBUG_PREFERRED) {
4734            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4735        }
4736        return intent;
4737    }
4738
4739    /**
4740     * Update given flags when being used to request {@link ResolveInfo}.
4741     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4742     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4743     * flag set. However, this flag is only honoured in three circumstances:
4744     * <ul>
4745     * <li>when called from a system process</li>
4746     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4747     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4748     * action and a {@code android.intent.category.BROWSABLE} category</li>
4749     * </ul>
4750     */
4751    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4752        return updateFlagsForResolve(flags, userId, intent, callingUid,
4753                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4754    }
4755    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4756            boolean wantInstantApps) {
4757        return updateFlagsForResolve(flags, userId, intent, callingUid,
4758                wantInstantApps, false /*onlyExposedExplicitly*/);
4759    }
4760    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4761            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4762        // Safe mode means we shouldn't match any third-party components
4763        if (mSafeMode) {
4764            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4765        }
4766        if (getInstantAppPackageName(callingUid) != null) {
4767            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4768            if (onlyExposedExplicitly) {
4769                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4770            }
4771            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4772            flags |= PackageManager.MATCH_INSTANT;
4773        } else {
4774            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4775            final boolean allowMatchInstant = wantInstantApps
4776                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4777            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4778                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4779            if (!allowMatchInstant) {
4780                flags &= ~PackageManager.MATCH_INSTANT;
4781            }
4782        }
4783        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4784    }
4785
4786    @Override
4787    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4788        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4789    }
4790
4791    /**
4792     * Important: The provided filterCallingUid is used exclusively to filter out activities
4793     * that can be seen based on user state. It's typically the original caller uid prior
4794     * to clearing. Because it can only be provided by trusted code, it's value can be
4795     * trusted and will be used as-is; unlike userId which will be validated by this method.
4796     */
4797    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4798            int filterCallingUid, int userId) {
4799        if (!sUserManager.exists(userId)) return null;
4800        flags = updateFlagsForComponent(flags, userId, component);
4801
4802        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4803            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4804                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4805        }
4806
4807        synchronized (mPackages) {
4808            PackageParser.Activity a = mActivities.mActivities.get(component);
4809
4810            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4811            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4812                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4813                if (ps == null) return null;
4814                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4815                    return null;
4816                }
4817                return PackageParser.generateActivityInfo(
4818                        a, flags, ps.readUserState(userId), userId);
4819            }
4820            if (mResolveComponentName.equals(component)) {
4821                return PackageParser.generateActivityInfo(
4822                        mResolveActivity, flags, new PackageUserState(), userId);
4823            }
4824        }
4825        return null;
4826    }
4827
4828    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4829        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4830            return false;
4831        }
4832        final long token = Binder.clearCallingIdentity();
4833        try {
4834            final int callingUserId = UserHandle.getUserId(callingUid);
4835            if (ActivityManager.getCurrentUser() != callingUserId) {
4836                return false;
4837            }
4838            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4839        } finally {
4840            Binder.restoreCallingIdentity(token);
4841        }
4842    }
4843
4844    @Override
4845    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4846            String resolvedType) {
4847        synchronized (mPackages) {
4848            if (component.equals(mResolveComponentName)) {
4849                // The resolver supports EVERYTHING!
4850                return true;
4851            }
4852            final int callingUid = Binder.getCallingUid();
4853            final int callingUserId = UserHandle.getUserId(callingUid);
4854            PackageParser.Activity a = mActivities.mActivities.get(component);
4855            if (a == null) {
4856                return false;
4857            }
4858            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4859            if (ps == null) {
4860                return false;
4861            }
4862            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4863                return false;
4864            }
4865            for (int i=0; i<a.intents.size(); i++) {
4866                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4867                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4868                    return true;
4869                }
4870            }
4871            return false;
4872        }
4873    }
4874
4875    @Override
4876    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4877        if (!sUserManager.exists(userId)) return null;
4878        final int callingUid = Binder.getCallingUid();
4879        flags = updateFlagsForComponent(flags, userId, component);
4880        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4881                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4882        synchronized (mPackages) {
4883            PackageParser.Activity a = mReceivers.mActivities.get(component);
4884            if (DEBUG_PACKAGE_INFO) Log.v(
4885                TAG, "getReceiverInfo " + component + ": " + a);
4886            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4887                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4888                if (ps == null) return null;
4889                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4890                    return null;
4891                }
4892                return PackageParser.generateActivityInfo(
4893                        a, flags, ps.readUserState(userId), userId);
4894            }
4895        }
4896        return null;
4897    }
4898
4899    @Override
4900    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4901            int flags, int userId) {
4902        if (!sUserManager.exists(userId)) return null;
4903        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4904        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4905            return null;
4906        }
4907
4908        flags = updateFlagsForPackage(flags, userId, null);
4909
4910        final boolean canSeeStaticLibraries =
4911                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4912                        == PERMISSION_GRANTED
4913                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4914                        == PERMISSION_GRANTED
4915                || canRequestPackageInstallsInternal(packageName,
4916                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4917                        false  /* throwIfPermNotDeclared*/)
4918                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4919                        == PERMISSION_GRANTED;
4920
4921        synchronized (mPackages) {
4922            List<SharedLibraryInfo> result = null;
4923
4924            final int libCount = mSharedLibraries.size();
4925            for (int i = 0; i < libCount; i++) {
4926                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4927                if (versionedLib == null) {
4928                    continue;
4929                }
4930
4931                final int versionCount = versionedLib.size();
4932                for (int j = 0; j < versionCount; j++) {
4933                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4934                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4935                        break;
4936                    }
4937                    final long identity = Binder.clearCallingIdentity();
4938                    try {
4939                        PackageInfo packageInfo = getPackageInfoVersioned(
4940                                libInfo.getDeclaringPackage(), flags
4941                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4942                        if (packageInfo == null) {
4943                            continue;
4944                        }
4945                    } finally {
4946                        Binder.restoreCallingIdentity(identity);
4947                    }
4948
4949                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4950                            libInfo.getLongVersion(), libInfo.getType(),
4951                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4952                            flags, userId));
4953
4954                    if (result == null) {
4955                        result = new ArrayList<>();
4956                    }
4957                    result.add(resLibInfo);
4958                }
4959            }
4960
4961            return result != null ? new ParceledListSlice<>(result) : null;
4962        }
4963    }
4964
4965    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4966            SharedLibraryInfo libInfo, int flags, int userId) {
4967        List<VersionedPackage> versionedPackages = null;
4968        final int packageCount = mSettings.mPackages.size();
4969        for (int i = 0; i < packageCount; i++) {
4970            PackageSetting ps = mSettings.mPackages.valueAt(i);
4971
4972            if (ps == null) {
4973                continue;
4974            }
4975
4976            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4977                continue;
4978            }
4979
4980            final String libName = libInfo.getName();
4981            if (libInfo.isStatic()) {
4982                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4983                if (libIdx < 0) {
4984                    continue;
4985                }
4986                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4987                    continue;
4988                }
4989                if (versionedPackages == null) {
4990                    versionedPackages = new ArrayList<>();
4991                }
4992                // If the dependent is a static shared lib, use the public package name
4993                String dependentPackageName = ps.name;
4994                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4995                    dependentPackageName = ps.pkg.manifestPackageName;
4996                }
4997                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4998            } else if (ps.pkg != null) {
4999                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5000                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5001                    if (versionedPackages == null) {
5002                        versionedPackages = new ArrayList<>();
5003                    }
5004                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5005                }
5006            }
5007        }
5008
5009        return versionedPackages;
5010    }
5011
5012    @Override
5013    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5014        if (!sUserManager.exists(userId)) return null;
5015        final int callingUid = Binder.getCallingUid();
5016        flags = updateFlagsForComponent(flags, userId, component);
5017        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5018                false /* requireFullPermission */, false /* checkShell */, "get service info");
5019        synchronized (mPackages) {
5020            PackageParser.Service s = mServices.mServices.get(component);
5021            if (DEBUG_PACKAGE_INFO) Log.v(
5022                TAG, "getServiceInfo " + component + ": " + s);
5023            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5024                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5025                if (ps == null) return null;
5026                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5027                    return null;
5028                }
5029                return PackageParser.generateServiceInfo(
5030                        s, flags, ps.readUserState(userId), userId);
5031            }
5032        }
5033        return null;
5034    }
5035
5036    @Override
5037    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5038        if (!sUserManager.exists(userId)) return null;
5039        final int callingUid = Binder.getCallingUid();
5040        flags = updateFlagsForComponent(flags, userId, component);
5041        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5042                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5043        synchronized (mPackages) {
5044            PackageParser.Provider p = mProviders.mProviders.get(component);
5045            if (DEBUG_PACKAGE_INFO) Log.v(
5046                TAG, "getProviderInfo " + component + ": " + p);
5047            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5048                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5049                if (ps == null) return null;
5050                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5051                    return null;
5052                }
5053                return PackageParser.generateProviderInfo(
5054                        p, flags, ps.readUserState(userId), userId);
5055            }
5056        }
5057        return null;
5058    }
5059
5060    @Override
5061    public String[] getSystemSharedLibraryNames() {
5062        // allow instant applications
5063        synchronized (mPackages) {
5064            Set<String> libs = null;
5065            final int libCount = mSharedLibraries.size();
5066            for (int i = 0; i < libCount; i++) {
5067                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5068                if (versionedLib == null) {
5069                    continue;
5070                }
5071                final int versionCount = versionedLib.size();
5072                for (int j = 0; j < versionCount; j++) {
5073                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5074                    if (!libEntry.info.isStatic()) {
5075                        if (libs == null) {
5076                            libs = new ArraySet<>();
5077                        }
5078                        libs.add(libEntry.info.getName());
5079                        break;
5080                    }
5081                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5082                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5083                            UserHandle.getUserId(Binder.getCallingUid()),
5084                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5085                        if (libs == null) {
5086                            libs = new ArraySet<>();
5087                        }
5088                        libs.add(libEntry.info.getName());
5089                        break;
5090                    }
5091                }
5092            }
5093
5094            if (libs != null) {
5095                String[] libsArray = new String[libs.size()];
5096                libs.toArray(libsArray);
5097                return libsArray;
5098            }
5099
5100            return null;
5101        }
5102    }
5103
5104    @Override
5105    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5106        // allow instant applications
5107        synchronized (mPackages) {
5108            return mServicesSystemSharedLibraryPackageName;
5109        }
5110    }
5111
5112    @Override
5113    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5114        // allow instant applications
5115        synchronized (mPackages) {
5116            return mSharedSystemSharedLibraryPackageName;
5117        }
5118    }
5119
5120    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5121        for (int i = userList.length - 1; i >= 0; --i) {
5122            final int userId = userList[i];
5123            // don't add instant app to the list of updates
5124            if (pkgSetting.getInstantApp(userId)) {
5125                continue;
5126            }
5127            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5128            if (changedPackages == null) {
5129                changedPackages = new SparseArray<>();
5130                mChangedPackages.put(userId, changedPackages);
5131            }
5132            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5133            if (sequenceNumbers == null) {
5134                sequenceNumbers = new HashMap<>();
5135                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5136            }
5137            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5138            if (sequenceNumber != null) {
5139                changedPackages.remove(sequenceNumber);
5140            }
5141            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5142            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5143        }
5144        mChangedPackagesSequenceNumber++;
5145    }
5146
5147    @Override
5148    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5150            return null;
5151        }
5152        synchronized (mPackages) {
5153            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5154                return null;
5155            }
5156            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5157            if (changedPackages == null) {
5158                return null;
5159            }
5160            final List<String> packageNames =
5161                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5162            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5163                final String packageName = changedPackages.get(i);
5164                if (packageName != null) {
5165                    packageNames.add(packageName);
5166                }
5167            }
5168            return packageNames.isEmpty()
5169                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5170        }
5171    }
5172
5173    @Override
5174    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5175        // allow instant applications
5176        ArrayList<FeatureInfo> res;
5177        synchronized (mAvailableFeatures) {
5178            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5179            res.addAll(mAvailableFeatures.values());
5180        }
5181        final FeatureInfo fi = new FeatureInfo();
5182        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5183                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5184        res.add(fi);
5185
5186        return new ParceledListSlice<>(res);
5187    }
5188
5189    @Override
5190    public boolean hasSystemFeature(String name, int version) {
5191        // allow instant applications
5192        synchronized (mAvailableFeatures) {
5193            final FeatureInfo feat = mAvailableFeatures.get(name);
5194            if (feat == null) {
5195                return false;
5196            } else {
5197                return feat.version >= version;
5198            }
5199        }
5200    }
5201
5202    @Override
5203    public int checkPermission(String permName, String pkgName, int userId) {
5204        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5205    }
5206
5207    @Override
5208    public int checkUidPermission(String permName, int uid) {
5209        synchronized (mPackages) {
5210            final String[] packageNames = getPackagesForUid(uid);
5211            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5212                    ? mPackages.get(packageNames[0])
5213                    : null;
5214            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5215        }
5216    }
5217
5218    @Override
5219    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5220        if (UserHandle.getCallingUserId() != userId) {
5221            mContext.enforceCallingPermission(
5222                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5223                    "isPermissionRevokedByPolicy for user " + userId);
5224        }
5225
5226        if (checkPermission(permission, packageName, userId)
5227                == PackageManager.PERMISSION_GRANTED) {
5228            return false;
5229        }
5230
5231        final int callingUid = Binder.getCallingUid();
5232        if (getInstantAppPackageName(callingUid) != null) {
5233            if (!isCallerSameApp(packageName, callingUid)) {
5234                return false;
5235            }
5236        } else {
5237            if (isInstantApp(packageName, userId)) {
5238                return false;
5239            }
5240        }
5241
5242        final long identity = Binder.clearCallingIdentity();
5243        try {
5244            final int flags = getPermissionFlags(permission, packageName, userId);
5245            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5246        } finally {
5247            Binder.restoreCallingIdentity(identity);
5248        }
5249    }
5250
5251    @Override
5252    public String getPermissionControllerPackageName() {
5253        synchronized (mPackages) {
5254            return mRequiredInstallerPackage;
5255        }
5256    }
5257
5258    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5259        return mPermissionManager.addDynamicPermission(
5260                info, async, getCallingUid(), new PermissionCallback() {
5261                    @Override
5262                    public void onPermissionChanged() {
5263                        if (!async) {
5264                            mSettings.writeLPr();
5265                        } else {
5266                            scheduleWriteSettingsLocked();
5267                        }
5268                    }
5269                });
5270    }
5271
5272    @Override
5273    public boolean addPermission(PermissionInfo info) {
5274        synchronized (mPackages) {
5275            return addDynamicPermission(info, false);
5276        }
5277    }
5278
5279    @Override
5280    public boolean addPermissionAsync(PermissionInfo info) {
5281        synchronized (mPackages) {
5282            return addDynamicPermission(info, true);
5283        }
5284    }
5285
5286    @Override
5287    public void removePermission(String permName) {
5288        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5289    }
5290
5291    @Override
5292    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5293        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5294                getCallingUid(), userId, mPermissionCallback);
5295    }
5296
5297    @Override
5298    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5299        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5300                getCallingUid(), userId, mPermissionCallback);
5301    }
5302
5303    @Override
5304    public void resetRuntimePermissions() {
5305        mContext.enforceCallingOrSelfPermission(
5306                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5307                "revokeRuntimePermission");
5308
5309        int callingUid = Binder.getCallingUid();
5310        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5311            mContext.enforceCallingOrSelfPermission(
5312                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5313                    "resetRuntimePermissions");
5314        }
5315
5316        synchronized (mPackages) {
5317            mPermissionManager.updateAllPermissions(
5318                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5319                    mPermissionCallback);
5320            for (int userId : UserManagerService.getInstance().getUserIds()) {
5321                final int packageCount = mPackages.size();
5322                for (int i = 0; i < packageCount; i++) {
5323                    PackageParser.Package pkg = mPackages.valueAt(i);
5324                    if (!(pkg.mExtras instanceof PackageSetting)) {
5325                        continue;
5326                    }
5327                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5328                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5329                }
5330            }
5331        }
5332    }
5333
5334    @Override
5335    public int getPermissionFlags(String permName, String packageName, int userId) {
5336        return mPermissionManager.getPermissionFlags(
5337                permName, packageName, getCallingUid(), userId);
5338    }
5339
5340    @Override
5341    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5342            int flagValues, int userId) {
5343        mPermissionManager.updatePermissionFlags(
5344                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5345                mPermissionCallback);
5346    }
5347
5348    /**
5349     * Update the permission flags for all packages and runtime permissions of a user in order
5350     * to allow device or profile owner to remove POLICY_FIXED.
5351     */
5352    @Override
5353    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5354        synchronized (mPackages) {
5355            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5356                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5357                    mPermissionCallback);
5358            if (changed) {
5359                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5360            }
5361        }
5362    }
5363
5364    @Override
5365    public boolean shouldShowRequestPermissionRationale(String permissionName,
5366            String packageName, int userId) {
5367        if (UserHandle.getCallingUserId() != userId) {
5368            mContext.enforceCallingPermission(
5369                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5370                    "canShowRequestPermissionRationale for user " + userId);
5371        }
5372
5373        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5374        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5375            return false;
5376        }
5377
5378        if (checkPermission(permissionName, packageName, userId)
5379                == PackageManager.PERMISSION_GRANTED) {
5380            return false;
5381        }
5382
5383        final int flags;
5384
5385        final long identity = Binder.clearCallingIdentity();
5386        try {
5387            flags = getPermissionFlags(permissionName,
5388                    packageName, userId);
5389        } finally {
5390            Binder.restoreCallingIdentity(identity);
5391        }
5392
5393        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5394                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5395                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5396
5397        if ((flags & fixedFlags) != 0) {
5398            return false;
5399        }
5400
5401        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5402    }
5403
5404    @Override
5405    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5406        mContext.enforceCallingOrSelfPermission(
5407                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5408                "addOnPermissionsChangeListener");
5409
5410        synchronized (mPackages) {
5411            mOnPermissionChangeListeners.addListenerLocked(listener);
5412        }
5413    }
5414
5415    @Override
5416    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5417        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5418            throw new SecurityException("Instant applications don't have access to this method");
5419        }
5420        synchronized (mPackages) {
5421            mOnPermissionChangeListeners.removeListenerLocked(listener);
5422        }
5423    }
5424
5425    @Override
5426    public boolean isProtectedBroadcast(String actionName) {
5427        // allow instant applications
5428        synchronized (mProtectedBroadcasts) {
5429            if (mProtectedBroadcasts.contains(actionName)) {
5430                return true;
5431            } else if (actionName != null) {
5432                // TODO: remove these terrible hacks
5433                if (actionName.startsWith("android.net.netmon.lingerExpired")
5434                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5435                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5436                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5437                    return true;
5438                }
5439            }
5440        }
5441        return false;
5442    }
5443
5444    @Override
5445    public int checkSignatures(String pkg1, String pkg2) {
5446        synchronized (mPackages) {
5447            final PackageParser.Package p1 = mPackages.get(pkg1);
5448            final PackageParser.Package p2 = mPackages.get(pkg2);
5449            if (p1 == null || p1.mExtras == null
5450                    || p2 == null || p2.mExtras == null) {
5451                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5452            }
5453            final int callingUid = Binder.getCallingUid();
5454            final int callingUserId = UserHandle.getUserId(callingUid);
5455            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5456            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5457            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5458                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5459                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5460            }
5461            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5462        }
5463    }
5464
5465    @Override
5466    public int checkUidSignatures(int uid1, int uid2) {
5467        final int callingUid = Binder.getCallingUid();
5468        final int callingUserId = UserHandle.getUserId(callingUid);
5469        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5470        // Map to base uids.
5471        uid1 = UserHandle.getAppId(uid1);
5472        uid2 = UserHandle.getAppId(uid2);
5473        // reader
5474        synchronized (mPackages) {
5475            Signature[] s1;
5476            Signature[] s2;
5477            Object obj = mSettings.getUserIdLPr(uid1);
5478            if (obj != null) {
5479                if (obj instanceof SharedUserSetting) {
5480                    if (isCallerInstantApp) {
5481                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5482                    }
5483                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5484                } else if (obj instanceof PackageSetting) {
5485                    final PackageSetting ps = (PackageSetting) obj;
5486                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5487                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5488                    }
5489                    s1 = ps.signatures.mSigningDetails.signatures;
5490                } else {
5491                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5492                }
5493            } else {
5494                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5495            }
5496            obj = mSettings.getUserIdLPr(uid2);
5497            if (obj != null) {
5498                if (obj instanceof SharedUserSetting) {
5499                    if (isCallerInstantApp) {
5500                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5501                    }
5502                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5503                } else if (obj instanceof PackageSetting) {
5504                    final PackageSetting ps = (PackageSetting) obj;
5505                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5506                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5507                    }
5508                    s2 = ps.signatures.mSigningDetails.signatures;
5509                } else {
5510                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5511                }
5512            } else {
5513                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5514            }
5515            return compareSignatures(s1, s2);
5516        }
5517    }
5518
5519    @Override
5520    public boolean hasSigningCertificate(
5521            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5522
5523        synchronized (mPackages) {
5524            final PackageParser.Package p = mPackages.get(packageName);
5525            if (p == null || p.mExtras == null) {
5526                return false;
5527            }
5528            final int callingUid = Binder.getCallingUid();
5529            final int callingUserId = UserHandle.getUserId(callingUid);
5530            final PackageSetting ps = (PackageSetting) p.mExtras;
5531            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5532                return false;
5533            }
5534            switch (type) {
5535                case CERT_INPUT_RAW_X509:
5536                    return p.mSigningDetails.hasCertificate(certificate);
5537                case CERT_INPUT_SHA256:
5538                    return p.mSigningDetails.hasSha256Certificate(certificate);
5539                default:
5540                    return false;
5541            }
5542        }
5543    }
5544
5545    @Override
5546    public boolean hasUidSigningCertificate(
5547            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5548        final int callingUid = Binder.getCallingUid();
5549        final int callingUserId = UserHandle.getUserId(callingUid);
5550        // Map to base uids.
5551        uid = UserHandle.getAppId(uid);
5552        // reader
5553        synchronized (mPackages) {
5554            final PackageParser.SigningDetails signingDetails;
5555            final Object obj = mSettings.getUserIdLPr(uid);
5556            if (obj != null) {
5557                if (obj instanceof SharedUserSetting) {
5558                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5559                    if (isCallerInstantApp) {
5560                        return false;
5561                    }
5562                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5563                } else if (obj instanceof PackageSetting) {
5564                    final PackageSetting ps = (PackageSetting) obj;
5565                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5566                        return false;
5567                    }
5568                    signingDetails = ps.signatures.mSigningDetails;
5569                } else {
5570                    return false;
5571                }
5572            } else {
5573                return false;
5574            }
5575            switch (type) {
5576                case CERT_INPUT_RAW_X509:
5577                    return signingDetails.hasCertificate(certificate);
5578                case CERT_INPUT_SHA256:
5579                    return signingDetails.hasSha256Certificate(certificate);
5580                default:
5581                    return false;
5582            }
5583        }
5584    }
5585
5586    /**
5587     * This method should typically only be used when granting or revoking
5588     * permissions, since the app may immediately restart after this call.
5589     * <p>
5590     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5591     * guard your work against the app being relaunched.
5592     */
5593    private void killUid(int appId, int userId, String reason) {
5594        final long identity = Binder.clearCallingIdentity();
5595        try {
5596            IActivityManager am = ActivityManager.getService();
5597            if (am != null) {
5598                try {
5599                    am.killUid(appId, userId, reason);
5600                } catch (RemoteException e) {
5601                    /* ignore - same process */
5602                }
5603            }
5604        } finally {
5605            Binder.restoreCallingIdentity(identity);
5606        }
5607    }
5608
5609    /**
5610     * If the database version for this type of package (internal storage or
5611     * external storage) is less than the version where package signatures
5612     * were updated, return true.
5613     */
5614    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5615        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5616        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5617    }
5618
5619    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5620        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5621        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5622    }
5623
5624    @Override
5625    public List<String> getAllPackages() {
5626        final int callingUid = Binder.getCallingUid();
5627        final int callingUserId = UserHandle.getUserId(callingUid);
5628        synchronized (mPackages) {
5629            if (canViewInstantApps(callingUid, callingUserId)) {
5630                return new ArrayList<String>(mPackages.keySet());
5631            }
5632            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5633            final List<String> result = new ArrayList<>();
5634            if (instantAppPkgName != null) {
5635                // caller is an instant application; filter unexposed applications
5636                for (PackageParser.Package pkg : mPackages.values()) {
5637                    if (!pkg.visibleToInstantApps) {
5638                        continue;
5639                    }
5640                    result.add(pkg.packageName);
5641                }
5642            } else {
5643                // caller is a normal application; filter instant applications
5644                for (PackageParser.Package pkg : mPackages.values()) {
5645                    final PackageSetting ps =
5646                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5647                    if (ps != null
5648                            && ps.getInstantApp(callingUserId)
5649                            && !mInstantAppRegistry.isInstantAccessGranted(
5650                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5651                        continue;
5652                    }
5653                    result.add(pkg.packageName);
5654                }
5655            }
5656            return result;
5657        }
5658    }
5659
5660    @Override
5661    public String[] getPackagesForUid(int uid) {
5662        final int callingUid = Binder.getCallingUid();
5663        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5664        final int userId = UserHandle.getUserId(uid);
5665        uid = UserHandle.getAppId(uid);
5666        // reader
5667        synchronized (mPackages) {
5668            Object obj = mSettings.getUserIdLPr(uid);
5669            if (obj instanceof SharedUserSetting) {
5670                if (isCallerInstantApp) {
5671                    return null;
5672                }
5673                final SharedUserSetting sus = (SharedUserSetting) obj;
5674                final int N = sus.packages.size();
5675                String[] res = new String[N];
5676                final Iterator<PackageSetting> it = sus.packages.iterator();
5677                int i = 0;
5678                while (it.hasNext()) {
5679                    PackageSetting ps = it.next();
5680                    if (ps.getInstalled(userId)) {
5681                        res[i++] = ps.name;
5682                    } else {
5683                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5684                    }
5685                }
5686                return res;
5687            } else if (obj instanceof PackageSetting) {
5688                final PackageSetting ps = (PackageSetting) obj;
5689                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5690                    return new String[]{ps.name};
5691                }
5692            }
5693        }
5694        return null;
5695    }
5696
5697    @Override
5698    public String getNameForUid(int uid) {
5699        final int callingUid = Binder.getCallingUid();
5700        if (getInstantAppPackageName(callingUid) != null) {
5701            return null;
5702        }
5703        synchronized (mPackages) {
5704            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5705            if (obj instanceof SharedUserSetting) {
5706                final SharedUserSetting sus = (SharedUserSetting) obj;
5707                return sus.name + ":" + sus.userId;
5708            } else if (obj instanceof PackageSetting) {
5709                final PackageSetting ps = (PackageSetting) obj;
5710                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5711                    return null;
5712                }
5713                return ps.name;
5714            }
5715            return null;
5716        }
5717    }
5718
5719    @Override
5720    public String[] getNamesForUids(int[] uids) {
5721        if (uids == null || uids.length == 0) {
5722            return null;
5723        }
5724        final int callingUid = Binder.getCallingUid();
5725        if (getInstantAppPackageName(callingUid) != null) {
5726            return null;
5727        }
5728        final String[] names = new String[uids.length];
5729        synchronized (mPackages) {
5730            for (int i = uids.length - 1; i >= 0; i--) {
5731                final int uid = uids[i];
5732                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5733                if (obj instanceof SharedUserSetting) {
5734                    final SharedUserSetting sus = (SharedUserSetting) obj;
5735                    names[i] = "shared:" + sus.name;
5736                } else if (obj instanceof PackageSetting) {
5737                    final PackageSetting ps = (PackageSetting) obj;
5738                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5739                        names[i] = null;
5740                    } else {
5741                        names[i] = ps.name;
5742                    }
5743                } else {
5744                    names[i] = null;
5745                }
5746            }
5747        }
5748        return names;
5749    }
5750
5751    @Override
5752    public int getUidForSharedUser(String sharedUserName) {
5753        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5754            return -1;
5755        }
5756        if (sharedUserName == null) {
5757            return -1;
5758        }
5759        // reader
5760        synchronized (mPackages) {
5761            SharedUserSetting suid;
5762            try {
5763                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5764                if (suid != null) {
5765                    return suid.userId;
5766                }
5767            } catch (PackageManagerException ignore) {
5768                // can't happen, but, still need to catch it
5769            }
5770            return -1;
5771        }
5772    }
5773
5774    @Override
5775    public int getFlagsForUid(int uid) {
5776        final int callingUid = Binder.getCallingUid();
5777        if (getInstantAppPackageName(callingUid) != null) {
5778            return 0;
5779        }
5780        synchronized (mPackages) {
5781            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5782            if (obj instanceof SharedUserSetting) {
5783                final SharedUserSetting sus = (SharedUserSetting) obj;
5784                return sus.pkgFlags;
5785            } else if (obj instanceof PackageSetting) {
5786                final PackageSetting ps = (PackageSetting) obj;
5787                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5788                    return 0;
5789                }
5790                return ps.pkgFlags;
5791            }
5792        }
5793        return 0;
5794    }
5795
5796    @Override
5797    public int getPrivateFlagsForUid(int uid) {
5798        final int callingUid = Binder.getCallingUid();
5799        if (getInstantAppPackageName(callingUid) != null) {
5800            return 0;
5801        }
5802        synchronized (mPackages) {
5803            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5804            if (obj instanceof SharedUserSetting) {
5805                final SharedUserSetting sus = (SharedUserSetting) obj;
5806                return sus.pkgPrivateFlags;
5807            } else if (obj instanceof PackageSetting) {
5808                final PackageSetting ps = (PackageSetting) obj;
5809                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5810                    return 0;
5811                }
5812                return ps.pkgPrivateFlags;
5813            }
5814        }
5815        return 0;
5816    }
5817
5818    @Override
5819    public boolean isUidPrivileged(int uid) {
5820        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5821            return false;
5822        }
5823        uid = UserHandle.getAppId(uid);
5824        // reader
5825        synchronized (mPackages) {
5826            Object obj = mSettings.getUserIdLPr(uid);
5827            if (obj instanceof SharedUserSetting) {
5828                final SharedUserSetting sus = (SharedUserSetting) obj;
5829                final Iterator<PackageSetting> it = sus.packages.iterator();
5830                while (it.hasNext()) {
5831                    if (it.next().isPrivileged()) {
5832                        return true;
5833                    }
5834                }
5835            } else if (obj instanceof PackageSetting) {
5836                final PackageSetting ps = (PackageSetting) obj;
5837                return ps.isPrivileged();
5838            }
5839        }
5840        return false;
5841    }
5842
5843    @Override
5844    public String[] getAppOpPermissionPackages(String permName) {
5845        return mPermissionManager.getAppOpPermissionPackages(permName);
5846    }
5847
5848    @Override
5849    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5850            int flags, int userId) {
5851        return resolveIntentInternal(
5852                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5853    }
5854
5855    /**
5856     * Normally instant apps can only be resolved when they're visible to the caller.
5857     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5858     * since we need to allow the system to start any installed application.
5859     */
5860    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5861            int flags, int userId, boolean resolveForStart) {
5862        try {
5863            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5864
5865            if (!sUserManager.exists(userId)) return null;
5866            final int callingUid = Binder.getCallingUid();
5867            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5868            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5869                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5870
5871            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5872            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5873                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5874            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5875
5876            final ResolveInfo bestChoice =
5877                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5878            return bestChoice;
5879        } finally {
5880            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5881        }
5882    }
5883
5884    @Override
5885    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5886        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5887            throw new SecurityException(
5888                    "findPersistentPreferredActivity can only be run by the system");
5889        }
5890        if (!sUserManager.exists(userId)) {
5891            return null;
5892        }
5893        final int callingUid = Binder.getCallingUid();
5894        intent = updateIntentForResolve(intent);
5895        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5896        final int flags = updateFlagsForResolve(
5897                0, userId, intent, callingUid, false /*includeInstantApps*/);
5898        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5899                userId);
5900        synchronized (mPackages) {
5901            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5902                    userId);
5903        }
5904    }
5905
5906    @Override
5907    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5908            IntentFilter filter, int match, ComponentName activity) {
5909        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5910            return;
5911        }
5912        final int userId = UserHandle.getCallingUserId();
5913        if (DEBUG_PREFERRED) {
5914            Log.v(TAG, "setLastChosenActivity intent=" + intent
5915                + " resolvedType=" + resolvedType
5916                + " flags=" + flags
5917                + " filter=" + filter
5918                + " match=" + match
5919                + " activity=" + activity);
5920            filter.dump(new PrintStreamPrinter(System.out), "    ");
5921        }
5922        intent.setComponent(null);
5923        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5924                userId);
5925        // Find any earlier preferred or last chosen entries and nuke them
5926        findPreferredActivity(intent, resolvedType,
5927                flags, query, 0, false, true, false, userId);
5928        // Add the new activity as the last chosen for this filter
5929        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5930                "Setting last chosen");
5931    }
5932
5933    @Override
5934    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5936            return null;
5937        }
5938        final int userId = UserHandle.getCallingUserId();
5939        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5940        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5941                userId);
5942        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5943                false, false, false, userId);
5944    }
5945
5946    /**
5947     * Returns whether or not instant apps have been disabled remotely.
5948     */
5949    private boolean areWebInstantAppsDisabled() {
5950        return mWebInstantAppsDisabled;
5951    }
5952
5953    private boolean isInstantAppResolutionAllowed(
5954            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5955            boolean skipPackageCheck) {
5956        if (mInstantAppResolverConnection == null) {
5957            return false;
5958        }
5959        if (mInstantAppInstallerActivity == null) {
5960            return false;
5961        }
5962        if (intent.getComponent() != null) {
5963            return false;
5964        }
5965        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5966            return false;
5967        }
5968        if (!skipPackageCheck && intent.getPackage() != null) {
5969            return false;
5970        }
5971        if (!intent.isWebIntent()) {
5972            // for non web intents, we should not resolve externally if an app already exists to
5973            // handle it or if the caller didn't explicitly request it.
5974            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5975                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5976                return false;
5977            }
5978        } else {
5979            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5980                return false;
5981            } else if (areWebInstantAppsDisabled()) {
5982                return false;
5983            }
5984        }
5985        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5986        // Or if there's already an ephemeral app installed that handles the action
5987        synchronized (mPackages) {
5988            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5989            for (int n = 0; n < count; n++) {
5990                final ResolveInfo info = resolvedActivities.get(n);
5991                final String packageName = info.activityInfo.packageName;
5992                final PackageSetting ps = mSettings.mPackages.get(packageName);
5993                if (ps != null) {
5994                    // only check domain verification status if the app is not a browser
5995                    if (!info.handleAllWebDataURI) {
5996                        // Try to get the status from User settings first
5997                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5998                        final int status = (int) (packedStatus >> 32);
5999                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6000                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6001                            if (DEBUG_INSTANT) {
6002                                Slog.v(TAG, "DENY instant app;"
6003                                    + " pkg: " + packageName + ", status: " + status);
6004                            }
6005                            return false;
6006                        }
6007                    }
6008                    if (ps.getInstantApp(userId)) {
6009                        if (DEBUG_INSTANT) {
6010                            Slog.v(TAG, "DENY instant app installed;"
6011                                    + " pkg: " + packageName);
6012                        }
6013                        return false;
6014                    }
6015                }
6016            }
6017        }
6018        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6019        return true;
6020    }
6021
6022    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6023            Intent origIntent, String resolvedType, String callingPackage,
6024            Bundle verificationBundle, int userId) {
6025        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6026                new InstantAppRequest(responseObj, origIntent, resolvedType,
6027                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6028        mHandler.sendMessage(msg);
6029    }
6030
6031    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6032            int flags, List<ResolveInfo> query, int userId) {
6033        if (query != null) {
6034            final int N = query.size();
6035            if (N == 1) {
6036                return query.get(0);
6037            } else if (N > 1) {
6038                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6039                // If there is more than one activity with the same priority,
6040                // then let the user decide between them.
6041                ResolveInfo r0 = query.get(0);
6042                ResolveInfo r1 = query.get(1);
6043                if (DEBUG_INTENT_MATCHING || debug) {
6044                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6045                            + r1.activityInfo.name + "=" + r1.priority);
6046                }
6047                // If the first activity has a higher priority, or a different
6048                // default, then it is always desirable to pick it.
6049                if (r0.priority != r1.priority
6050                        || r0.preferredOrder != r1.preferredOrder
6051                        || r0.isDefault != r1.isDefault) {
6052                    return query.get(0);
6053                }
6054                // If we have saved a preference for a preferred activity for
6055                // this Intent, use that.
6056                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6057                        flags, query, r0.priority, true, false, debug, userId);
6058                if (ri != null) {
6059                    return ri;
6060                }
6061                // If we have an ephemeral app, use it
6062                for (int i = 0; i < N; i++) {
6063                    ri = query.get(i);
6064                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6065                        final String packageName = ri.activityInfo.packageName;
6066                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6067                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6068                        final int status = (int)(packedStatus >> 32);
6069                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6070                            return ri;
6071                        }
6072                    }
6073                }
6074                ri = new ResolveInfo(mResolveInfo);
6075                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6076                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6077                // If all of the options come from the same package, show the application's
6078                // label and icon instead of the generic resolver's.
6079                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6080                // and then throw away the ResolveInfo itself, meaning that the caller loses
6081                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6082                // a fallback for this case; we only set the target package's resources on
6083                // the ResolveInfo, not the ActivityInfo.
6084                final String intentPackage = intent.getPackage();
6085                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6086                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6087                    ri.resolvePackageName = intentPackage;
6088                    if (userNeedsBadging(userId)) {
6089                        ri.noResourceId = true;
6090                    } else {
6091                        ri.icon = appi.icon;
6092                    }
6093                    ri.iconResourceId = appi.icon;
6094                    ri.labelRes = appi.labelRes;
6095                }
6096                ri.activityInfo.applicationInfo = new ApplicationInfo(
6097                        ri.activityInfo.applicationInfo);
6098                if (userId != 0) {
6099                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6100                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6101                }
6102                // Make sure that the resolver is displayable in car mode
6103                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6104                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6105                return ri;
6106            }
6107        }
6108        return null;
6109    }
6110
6111    /**
6112     * Return true if the given list is not empty and all of its contents have
6113     * an activityInfo with the given package name.
6114     */
6115    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6116        if (ArrayUtils.isEmpty(list)) {
6117            return false;
6118        }
6119        for (int i = 0, N = list.size(); i < N; i++) {
6120            final ResolveInfo ri = list.get(i);
6121            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6122            if (ai == null || !packageName.equals(ai.packageName)) {
6123                return false;
6124            }
6125        }
6126        return true;
6127    }
6128
6129    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6130            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6131        final int N = query.size();
6132        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6133                .get(userId);
6134        // Get the list of persistent preferred activities that handle the intent
6135        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6136        List<PersistentPreferredActivity> pprefs = ppir != null
6137                ? ppir.queryIntent(intent, resolvedType,
6138                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6139                        userId)
6140                : null;
6141        if (pprefs != null && pprefs.size() > 0) {
6142            final int M = pprefs.size();
6143            for (int i=0; i<M; i++) {
6144                final PersistentPreferredActivity ppa = pprefs.get(i);
6145                if (DEBUG_PREFERRED || debug) {
6146                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6147                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6148                            + "\n  component=" + ppa.mComponent);
6149                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6150                }
6151                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6152                        flags | MATCH_DISABLED_COMPONENTS, userId);
6153                if (DEBUG_PREFERRED || debug) {
6154                    Slog.v(TAG, "Found persistent preferred activity:");
6155                    if (ai != null) {
6156                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6157                    } else {
6158                        Slog.v(TAG, "  null");
6159                    }
6160                }
6161                if (ai == null) {
6162                    // This previously registered persistent preferred activity
6163                    // component is no longer known. Ignore it and do NOT remove it.
6164                    continue;
6165                }
6166                for (int j=0; j<N; j++) {
6167                    final ResolveInfo ri = query.get(j);
6168                    if (!ri.activityInfo.applicationInfo.packageName
6169                            .equals(ai.applicationInfo.packageName)) {
6170                        continue;
6171                    }
6172                    if (!ri.activityInfo.name.equals(ai.name)) {
6173                        continue;
6174                    }
6175                    //  Found a persistent preference that can handle the intent.
6176                    if (DEBUG_PREFERRED || debug) {
6177                        Slog.v(TAG, "Returning persistent preferred activity: " +
6178                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6179                    }
6180                    return ri;
6181                }
6182            }
6183        }
6184        return null;
6185    }
6186
6187    // TODO: handle preferred activities missing while user has amnesia
6188    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6189            List<ResolveInfo> query, int priority, boolean always,
6190            boolean removeMatches, boolean debug, int userId) {
6191        if (!sUserManager.exists(userId)) return null;
6192        final int callingUid = Binder.getCallingUid();
6193        flags = updateFlagsForResolve(
6194                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6195        intent = updateIntentForResolve(intent);
6196        // writer
6197        synchronized (mPackages) {
6198            // Try to find a matching persistent preferred activity.
6199            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6200                    debug, userId);
6201
6202            // If a persistent preferred activity matched, use it.
6203            if (pri != null) {
6204                return pri;
6205            }
6206
6207            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6208            // Get the list of preferred activities that handle the intent
6209            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6210            List<PreferredActivity> prefs = pir != null
6211                    ? pir.queryIntent(intent, resolvedType,
6212                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6213                            userId)
6214                    : null;
6215            if (prefs != null && prefs.size() > 0) {
6216                boolean changed = false;
6217                try {
6218                    // First figure out how good the original match set is.
6219                    // We will only allow preferred activities that came
6220                    // from the same match quality.
6221                    int match = 0;
6222
6223                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6224
6225                    final int N = query.size();
6226                    for (int j=0; j<N; j++) {
6227                        final ResolveInfo ri = query.get(j);
6228                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6229                                + ": 0x" + Integer.toHexString(match));
6230                        if (ri.match > match) {
6231                            match = ri.match;
6232                        }
6233                    }
6234
6235                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6236                            + Integer.toHexString(match));
6237
6238                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6239                    final int M = prefs.size();
6240                    for (int i=0; i<M; i++) {
6241                        final PreferredActivity pa = prefs.get(i);
6242                        if (DEBUG_PREFERRED || debug) {
6243                            Slog.v(TAG, "Checking PreferredActivity ds="
6244                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6245                                    + "\n  component=" + pa.mPref.mComponent);
6246                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6247                        }
6248                        if (pa.mPref.mMatch != match) {
6249                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6250                                    + Integer.toHexString(pa.mPref.mMatch));
6251                            continue;
6252                        }
6253                        // If it's not an "always" type preferred activity and that's what we're
6254                        // looking for, skip it.
6255                        if (always && !pa.mPref.mAlways) {
6256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6257                            continue;
6258                        }
6259                        final ActivityInfo ai = getActivityInfo(
6260                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6261                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6262                                userId);
6263                        if (DEBUG_PREFERRED || debug) {
6264                            Slog.v(TAG, "Found preferred activity:");
6265                            if (ai != null) {
6266                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6267                            } else {
6268                                Slog.v(TAG, "  null");
6269                            }
6270                        }
6271                        if (ai == null) {
6272                            // This previously registered preferred activity
6273                            // component is no longer known.  Most likely an update
6274                            // to the app was installed and in the new version this
6275                            // component no longer exists.  Clean it up by removing
6276                            // it from the preferred activities list, and skip it.
6277                            Slog.w(TAG, "Removing dangling preferred activity: "
6278                                    + pa.mPref.mComponent);
6279                            pir.removeFilter(pa);
6280                            changed = true;
6281                            continue;
6282                        }
6283                        for (int j=0; j<N; j++) {
6284                            final ResolveInfo ri = query.get(j);
6285                            if (!ri.activityInfo.applicationInfo.packageName
6286                                    .equals(ai.applicationInfo.packageName)) {
6287                                continue;
6288                            }
6289                            if (!ri.activityInfo.name.equals(ai.name)) {
6290                                continue;
6291                            }
6292
6293                            if (removeMatches) {
6294                                pir.removeFilter(pa);
6295                                changed = true;
6296                                if (DEBUG_PREFERRED) {
6297                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6298                                }
6299                                break;
6300                            }
6301
6302                            // Okay we found a previously set preferred or last chosen app.
6303                            // If the result set is different from when this
6304                            // was created, and is not a subset of the preferred set, we need to
6305                            // clear it and re-ask the user their preference, if we're looking for
6306                            // an "always" type entry.
6307                            if (always && !pa.mPref.sameSet(query)) {
6308                                if (pa.mPref.isSuperset(query)) {
6309                                    // some components of the set are no longer present in
6310                                    // the query, but the preferred activity can still be reused
6311                                    if (DEBUG_PREFERRED) {
6312                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6313                                                + " still valid as only non-preferred components"
6314                                                + " were removed for " + intent + " type "
6315                                                + resolvedType);
6316                                    }
6317                                    // remove obsolete components and re-add the up-to-date filter
6318                                    PreferredActivity freshPa = new PreferredActivity(pa,
6319                                            pa.mPref.mMatch,
6320                                            pa.mPref.discardObsoleteComponents(query),
6321                                            pa.mPref.mComponent,
6322                                            pa.mPref.mAlways);
6323                                    pir.removeFilter(pa);
6324                                    pir.addFilter(freshPa);
6325                                    changed = true;
6326                                } else {
6327                                    Slog.i(TAG,
6328                                            "Result set changed, dropping preferred activity for "
6329                                                    + intent + " type " + resolvedType);
6330                                    if (DEBUG_PREFERRED) {
6331                                        Slog.v(TAG, "Removing preferred activity since set changed "
6332                                                + pa.mPref.mComponent);
6333                                    }
6334                                    pir.removeFilter(pa);
6335                                    // Re-add the filter as a "last chosen" entry (!always)
6336                                    PreferredActivity lastChosen = new PreferredActivity(
6337                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6338                                    pir.addFilter(lastChosen);
6339                                    changed = true;
6340                                    return null;
6341                                }
6342                            }
6343
6344                            // Yay! Either the set matched or we're looking for the last chosen
6345                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6346                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6347                            return ri;
6348                        }
6349                    }
6350                } finally {
6351                    if (changed) {
6352                        if (DEBUG_PREFERRED) {
6353                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6354                        }
6355                        scheduleWritePackageRestrictionsLocked(userId);
6356                    }
6357                }
6358            }
6359        }
6360        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6361        return null;
6362    }
6363
6364    /*
6365     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6366     */
6367    @Override
6368    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6369            int targetUserId) {
6370        mContext.enforceCallingOrSelfPermission(
6371                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6372        List<CrossProfileIntentFilter> matches =
6373                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6374        if (matches != null) {
6375            int size = matches.size();
6376            for (int i = 0; i < size; i++) {
6377                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6378            }
6379        }
6380        if (intent.hasWebURI()) {
6381            // cross-profile app linking works only towards the parent.
6382            final int callingUid = Binder.getCallingUid();
6383            final UserInfo parent = getProfileParent(sourceUserId);
6384            synchronized(mPackages) {
6385                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6386                        false /*includeInstantApps*/);
6387                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6388                        intent, resolvedType, flags, sourceUserId, parent.id);
6389                return xpDomainInfo != null;
6390            }
6391        }
6392        return false;
6393    }
6394
6395    private UserInfo getProfileParent(int userId) {
6396        final long identity = Binder.clearCallingIdentity();
6397        try {
6398            return sUserManager.getProfileParent(userId);
6399        } finally {
6400            Binder.restoreCallingIdentity(identity);
6401        }
6402    }
6403
6404    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6405            String resolvedType, int userId) {
6406        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6407        if (resolver != null) {
6408            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6409        }
6410        return null;
6411    }
6412
6413    @Override
6414    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6415            String resolvedType, int flags, int userId) {
6416        try {
6417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6418
6419            return new ParceledListSlice<>(
6420                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6421        } finally {
6422            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6423        }
6424    }
6425
6426    /**
6427     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6428     * instant, returns {@code null}.
6429     */
6430    private String getInstantAppPackageName(int callingUid) {
6431        synchronized (mPackages) {
6432            // If the caller is an isolated app use the owner's uid for the lookup.
6433            if (Process.isIsolated(callingUid)) {
6434                callingUid = mIsolatedOwners.get(callingUid);
6435            }
6436            final int appId = UserHandle.getAppId(callingUid);
6437            final Object obj = mSettings.getUserIdLPr(appId);
6438            if (obj instanceof PackageSetting) {
6439                final PackageSetting ps = (PackageSetting) obj;
6440                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6441                return isInstantApp ? ps.pkg.packageName : null;
6442            }
6443        }
6444        return null;
6445    }
6446
6447    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6448            String resolvedType, int flags, int userId) {
6449        return queryIntentActivitiesInternal(
6450                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6451                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6452    }
6453
6454    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6455            String resolvedType, int flags, int filterCallingUid, int userId,
6456            boolean resolveForStart, boolean allowDynamicSplits) {
6457        if (!sUserManager.exists(userId)) return Collections.emptyList();
6458        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6459        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6460                false /* requireFullPermission */, false /* checkShell */,
6461                "query intent activities");
6462        final String pkgName = intent.getPackage();
6463        ComponentName comp = intent.getComponent();
6464        if (comp == null) {
6465            if (intent.getSelector() != null) {
6466                intent = intent.getSelector();
6467                comp = intent.getComponent();
6468            }
6469        }
6470
6471        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6472                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6473        if (comp != null) {
6474            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6475            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6476            if (ai != null) {
6477                // When specifying an explicit component, we prevent the activity from being
6478                // used when either 1) the calling package is normal and the activity is within
6479                // an ephemeral application or 2) the calling package is ephemeral and the
6480                // activity is not visible to ephemeral applications.
6481                final boolean matchInstantApp =
6482                        (flags & PackageManager.MATCH_INSTANT) != 0;
6483                final boolean matchVisibleToInstantAppOnly =
6484                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6485                final boolean matchExplicitlyVisibleOnly =
6486                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6487                final boolean isCallerInstantApp =
6488                        instantAppPkgName != null;
6489                final boolean isTargetSameInstantApp =
6490                        comp.getPackageName().equals(instantAppPkgName);
6491                final boolean isTargetInstantApp =
6492                        (ai.applicationInfo.privateFlags
6493                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6494                final boolean isTargetVisibleToInstantApp =
6495                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6496                final boolean isTargetExplicitlyVisibleToInstantApp =
6497                        isTargetVisibleToInstantApp
6498                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6499                final boolean isTargetHiddenFromInstantApp =
6500                        !isTargetVisibleToInstantApp
6501                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6502                final boolean blockResolution =
6503                        !isTargetSameInstantApp
6504                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6505                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6506                                        && isTargetHiddenFromInstantApp));
6507                if (!blockResolution) {
6508                    final ResolveInfo ri = new ResolveInfo();
6509                    ri.activityInfo = ai;
6510                    list.add(ri);
6511                }
6512            }
6513            return applyPostResolutionFilter(
6514                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6515        }
6516
6517        // reader
6518        boolean sortResult = false;
6519        boolean addInstant = false;
6520        List<ResolveInfo> result;
6521        synchronized (mPackages) {
6522            if (pkgName == null) {
6523                List<CrossProfileIntentFilter> matchingFilters =
6524                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6525                // Check for results that need to skip the current profile.
6526                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6527                        resolvedType, flags, userId);
6528                if (xpResolveInfo != null) {
6529                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6530                    xpResult.add(xpResolveInfo);
6531                    return applyPostResolutionFilter(
6532                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6533                            allowDynamicSplits, filterCallingUid, userId, intent);
6534                }
6535
6536                // Check for results in the current profile.
6537                result = filterIfNotSystemUser(mActivities.queryIntent(
6538                        intent, resolvedType, flags, userId), userId);
6539                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6540                        false /*skipPackageCheck*/);
6541                // Check for cross profile results.
6542                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6543                xpResolveInfo = queryCrossProfileIntents(
6544                        matchingFilters, intent, resolvedType, flags, userId,
6545                        hasNonNegativePriorityResult);
6546                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6547                    boolean isVisibleToUser = filterIfNotSystemUser(
6548                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6549                    if (isVisibleToUser) {
6550                        result.add(xpResolveInfo);
6551                        sortResult = true;
6552                    }
6553                }
6554                if (intent.hasWebURI()) {
6555                    CrossProfileDomainInfo xpDomainInfo = null;
6556                    final UserInfo parent = getProfileParent(userId);
6557                    if (parent != null) {
6558                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6559                                flags, userId, parent.id);
6560                    }
6561                    if (xpDomainInfo != null) {
6562                        if (xpResolveInfo != null) {
6563                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6564                            // in the result.
6565                            result.remove(xpResolveInfo);
6566                        }
6567                        if (result.size() == 0 && !addInstant) {
6568                            // No result in current profile, but found candidate in parent user.
6569                            // And we are not going to add emphemeral app, so we can return the
6570                            // result straight away.
6571                            result.add(xpDomainInfo.resolveInfo);
6572                            return applyPostResolutionFilter(result, instantAppPkgName,
6573                                    allowDynamicSplits, filterCallingUid, userId, intent);
6574                        }
6575                    } else if (result.size() <= 1 && !addInstant) {
6576                        // No result in parent user and <= 1 result in current profile, and we
6577                        // are not going to add emphemeral app, so we can return the result without
6578                        // further processing.
6579                        return applyPostResolutionFilter(result, instantAppPkgName,
6580                                allowDynamicSplits, filterCallingUid, userId, intent);
6581                    }
6582                    // We have more than one candidate (combining results from current and parent
6583                    // profile), so we need filtering and sorting.
6584                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6585                            intent, flags, result, xpDomainInfo, userId);
6586                    sortResult = true;
6587                }
6588            } else {
6589                final PackageParser.Package pkg = mPackages.get(pkgName);
6590                result = null;
6591                if (pkg != null) {
6592                    result = filterIfNotSystemUser(
6593                            mActivities.queryIntentForPackage(
6594                                    intent, resolvedType, flags, pkg.activities, userId),
6595                            userId);
6596                }
6597                if (result == null || result.size() == 0) {
6598                    // the caller wants to resolve for a particular package; however, there
6599                    // were no installed results, so, try to find an ephemeral result
6600                    addInstant = isInstantAppResolutionAllowed(
6601                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6602                    if (result == null) {
6603                        result = new ArrayList<>();
6604                    }
6605                }
6606            }
6607        }
6608        if (addInstant) {
6609            result = maybeAddInstantAppInstaller(
6610                    result, intent, resolvedType, flags, userId, resolveForStart);
6611        }
6612        if (sortResult) {
6613            Collections.sort(result, mResolvePrioritySorter);
6614        }
6615        return applyPostResolutionFilter(
6616                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6617    }
6618
6619    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6620            String resolvedType, int flags, int userId, boolean resolveForStart) {
6621        // first, check to see if we've got an instant app already installed
6622        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6623        ResolveInfo localInstantApp = null;
6624        boolean blockResolution = false;
6625        if (!alreadyResolvedLocally) {
6626            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6627                    flags
6628                        | PackageManager.GET_RESOLVED_FILTER
6629                        | PackageManager.MATCH_INSTANT
6630                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6631                    userId);
6632            for (int i = instantApps.size() - 1; i >= 0; --i) {
6633                final ResolveInfo info = instantApps.get(i);
6634                final String packageName = info.activityInfo.packageName;
6635                final PackageSetting ps = mSettings.mPackages.get(packageName);
6636                if (ps.getInstantApp(userId)) {
6637                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6638                    final int status = (int)(packedStatus >> 32);
6639                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6640                        // there's a local instant application installed, but, the user has
6641                        // chosen to never use it; skip resolution and don't acknowledge
6642                        // an instant application is even available
6643                        if (DEBUG_INSTANT) {
6644                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6645                        }
6646                        blockResolution = true;
6647                        break;
6648                    } else {
6649                        // we have a locally installed instant application; skip resolution
6650                        // but acknowledge there's an instant application available
6651                        if (DEBUG_INSTANT) {
6652                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6653                        }
6654                        localInstantApp = info;
6655                        break;
6656                    }
6657                }
6658            }
6659        }
6660        // no app installed, let's see if one's available
6661        AuxiliaryResolveInfo auxiliaryResponse = null;
6662        if (!blockResolution) {
6663            if (localInstantApp == null) {
6664                // we don't have an instant app locally, resolve externally
6665                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6666                final InstantAppRequest requestObject = new InstantAppRequest(
6667                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6668                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6669                        resolveForStart);
6670                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6671                        mInstantAppResolverConnection, requestObject);
6672                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6673            } else {
6674                // we have an instant application locally, but, we can't admit that since
6675                // callers shouldn't be able to determine prior browsing. create a dummy
6676                // auxiliary response so the downstream code behaves as if there's an
6677                // instant application available externally. when it comes time to start
6678                // the instant application, we'll do the right thing.
6679                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6680                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6681                                        ai.packageName, ai.versionCode, null /* splitName */);
6682            }
6683        }
6684        if (intent.isWebIntent() && auxiliaryResponse == null) {
6685            return result;
6686        }
6687        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6688        if (ps == null) {
6689            return result;
6690        }
6691        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6692        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6693                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6694        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6695                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6696        // add a non-generic filter
6697        ephemeralInstaller.filter = new IntentFilter();
6698        if (intent.getAction() != null) {
6699            ephemeralInstaller.filter.addAction(intent.getAction());
6700        }
6701        if (intent.getData() != null && intent.getData().getPath() != null) {
6702            ephemeralInstaller.filter.addDataPath(
6703                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6704        }
6705        ephemeralInstaller.isInstantAppAvailable = true;
6706        // make sure this resolver is the default
6707        ephemeralInstaller.isDefault = true;
6708        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6709        if (DEBUG_INSTANT) {
6710            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6711        }
6712
6713        result.add(ephemeralInstaller);
6714        return result;
6715    }
6716
6717    private static class CrossProfileDomainInfo {
6718        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6719        ResolveInfo resolveInfo;
6720        /* Best domain verification status of the activities found in the other profile */
6721        int bestDomainVerificationStatus;
6722    }
6723
6724    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6725            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6726        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6727                sourceUserId)) {
6728            return null;
6729        }
6730        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6731                resolvedType, flags, parentUserId);
6732
6733        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6734            return null;
6735        }
6736        CrossProfileDomainInfo result = null;
6737        int size = resultTargetUser.size();
6738        for (int i = 0; i < size; i++) {
6739            ResolveInfo riTargetUser = resultTargetUser.get(i);
6740            // Intent filter verification is only for filters that specify a host. So don't return
6741            // those that handle all web uris.
6742            if (riTargetUser.handleAllWebDataURI) {
6743                continue;
6744            }
6745            String packageName = riTargetUser.activityInfo.packageName;
6746            PackageSetting ps = mSettings.mPackages.get(packageName);
6747            if (ps == null) {
6748                continue;
6749            }
6750            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6751            int status = (int)(verificationState >> 32);
6752            if (result == null) {
6753                result = new CrossProfileDomainInfo();
6754                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6755                        sourceUserId, parentUserId);
6756                result.bestDomainVerificationStatus = status;
6757            } else {
6758                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6759                        result.bestDomainVerificationStatus);
6760            }
6761        }
6762        // Don't consider matches with status NEVER across profiles.
6763        if (result != null && result.bestDomainVerificationStatus
6764                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6765            return null;
6766        }
6767        return result;
6768    }
6769
6770    /**
6771     * Verification statuses are ordered from the worse to the best, except for
6772     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6773     */
6774    private int bestDomainVerificationStatus(int status1, int status2) {
6775        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6776            return status2;
6777        }
6778        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6779            return status1;
6780        }
6781        return (int) MathUtils.max(status1, status2);
6782    }
6783
6784    private boolean isUserEnabled(int userId) {
6785        long callingId = Binder.clearCallingIdentity();
6786        try {
6787            UserInfo userInfo = sUserManager.getUserInfo(userId);
6788            return userInfo != null && userInfo.isEnabled();
6789        } finally {
6790            Binder.restoreCallingIdentity(callingId);
6791        }
6792    }
6793
6794    /**
6795     * Filter out activities with systemUserOnly flag set, when current user is not System.
6796     *
6797     * @return filtered list
6798     */
6799    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6800        if (userId == UserHandle.USER_SYSTEM) {
6801            return resolveInfos;
6802        }
6803        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6804            ResolveInfo info = resolveInfos.get(i);
6805            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6806                resolveInfos.remove(i);
6807            }
6808        }
6809        return resolveInfos;
6810    }
6811
6812    /**
6813     * Filters out ephemeral activities.
6814     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6815     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6816     *
6817     * @param resolveInfos The pre-filtered list of resolved activities
6818     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6819     *          is performed.
6820     * @param intent
6821     * @return A filtered list of resolved activities.
6822     */
6823    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6824            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6825            Intent intent) {
6826        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6827        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6828            final ResolveInfo info = resolveInfos.get(i);
6829            // remove locally resolved instant app web results when disabled
6830            if (info.isInstantAppAvailable && blockInstant) {
6831                resolveInfos.remove(i);
6832                continue;
6833            }
6834            // allow activities that are defined in the provided package
6835            if (allowDynamicSplits
6836                    && info.activityInfo != null
6837                    && info.activityInfo.splitName != null
6838                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6839                            info.activityInfo.splitName)) {
6840                if (mInstantAppInstallerActivity == null) {
6841                    if (DEBUG_INSTALL) {
6842                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6843                    }
6844                    resolveInfos.remove(i);
6845                    continue;
6846                }
6847                // requested activity is defined in a split that hasn't been installed yet.
6848                // add the installer to the resolve list
6849                if (DEBUG_INSTALL) {
6850                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6851                }
6852                final ResolveInfo installerInfo = new ResolveInfo(
6853                        mInstantAppInstallerInfo);
6854                final ComponentName installFailureActivity = findInstallFailureActivity(
6855                        info.activityInfo.packageName,  filterCallingUid, userId);
6856                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6857                        installFailureActivity,
6858                        info.activityInfo.packageName,
6859                        info.activityInfo.applicationInfo.versionCode,
6860                        info.activityInfo.splitName);
6861                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6862                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6863                // add a non-generic filter
6864                installerInfo.filter = new IntentFilter();
6865
6866                // This resolve info may appear in the chooser UI, so let us make it
6867                // look as the one it replaces as far as the user is concerned which
6868                // requires loading the correct label and icon for the resolve info.
6869                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6870                installerInfo.labelRes = info.resolveLabelResId();
6871                installerInfo.icon = info.resolveIconResId();
6872
6873                // propagate priority/preferred order/default
6874                installerInfo.priority = info.priority;
6875                installerInfo.preferredOrder = info.preferredOrder;
6876                installerInfo.isDefault = info.isDefault;
6877                installerInfo.isInstantAppAvailable = true;
6878                resolveInfos.set(i, installerInfo);
6879                continue;
6880            }
6881            // caller is a full app, don't need to apply any other filtering
6882            if (ephemeralPkgName == null) {
6883                continue;
6884            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6885                // caller is same app; don't need to apply any other filtering
6886                continue;
6887            }
6888            // allow activities that have been explicitly exposed to ephemeral apps
6889            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6890            if (!isEphemeralApp
6891                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6892                continue;
6893            }
6894            resolveInfos.remove(i);
6895        }
6896        return resolveInfos;
6897    }
6898
6899    /**
6900     * Returns the activity component that can handle install failures.
6901     * <p>By default, the instant application installer handles failures. However, an
6902     * application may want to handle failures on its own. Applications do this by
6903     * creating an activity with an intent filter that handles the action
6904     * {@link Intent#ACTION_INSTALL_FAILURE}.
6905     */
6906    private @Nullable ComponentName findInstallFailureActivity(
6907            String packageName, int filterCallingUid, int userId) {
6908        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6909        failureActivityIntent.setPackage(packageName);
6910        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6911        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6912                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6913                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6914        final int NR = result.size();
6915        if (NR > 0) {
6916            for (int i = 0; i < NR; i++) {
6917                final ResolveInfo info = result.get(i);
6918                if (info.activityInfo.splitName != null) {
6919                    continue;
6920                }
6921                return new ComponentName(packageName, info.activityInfo.name);
6922            }
6923        }
6924        return null;
6925    }
6926
6927    /**
6928     * @param resolveInfos list of resolve infos in descending priority order
6929     * @return if the list contains a resolve info with non-negative priority
6930     */
6931    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6932        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6933    }
6934
6935    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6936            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6937            int userId) {
6938        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6939
6940        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6941            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6942                    candidates.size());
6943        }
6944
6945        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6946        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6947        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6948        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6949        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6950        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6951
6952        synchronized (mPackages) {
6953            final int count = candidates.size();
6954            // First, try to use linked apps. Partition the candidates into four lists:
6955            // one for the final results, one for the "do not use ever", one for "undefined status"
6956            // and finally one for "browser app type".
6957            for (int n=0; n<count; n++) {
6958                ResolveInfo info = candidates.get(n);
6959                String packageName = info.activityInfo.packageName;
6960                PackageSetting ps = mSettings.mPackages.get(packageName);
6961                if (ps != null) {
6962                    // Add to the special match all list (Browser use case)
6963                    if (info.handleAllWebDataURI) {
6964                        matchAllList.add(info);
6965                        continue;
6966                    }
6967                    // Try to get the status from User settings first
6968                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6969                    int status = (int)(packedStatus >> 32);
6970                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6971                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6972                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6973                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6974                                    + " : linkgen=" + linkGeneration);
6975                        }
6976                        // Use link-enabled generation as preferredOrder, i.e.
6977                        // prefer newly-enabled over earlier-enabled.
6978                        info.preferredOrder = linkGeneration;
6979                        alwaysList.add(info);
6980                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6981                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6982                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6983                        }
6984                        neverList.add(info);
6985                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6986                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6987                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6988                        }
6989                        alwaysAskList.add(info);
6990                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6991                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6992                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6993                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6994                        }
6995                        undefinedList.add(info);
6996                    }
6997                }
6998            }
6999
7000            // We'll want to include browser possibilities in a few cases
7001            boolean includeBrowser = false;
7002
7003            // First try to add the "always" resolution(s) for the current user, if any
7004            if (alwaysList.size() > 0) {
7005                result.addAll(alwaysList);
7006            } else {
7007                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7008                result.addAll(undefinedList);
7009                // Maybe add one for the other profile.
7010                if (xpDomainInfo != null && (
7011                        xpDomainInfo.bestDomainVerificationStatus
7012                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7013                    result.add(xpDomainInfo.resolveInfo);
7014                }
7015                includeBrowser = true;
7016            }
7017
7018            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7019            // If there were 'always' entries their preferred order has been set, so we also
7020            // back that off to make the alternatives equivalent
7021            if (alwaysAskList.size() > 0) {
7022                for (ResolveInfo i : result) {
7023                    i.preferredOrder = 0;
7024                }
7025                result.addAll(alwaysAskList);
7026                includeBrowser = true;
7027            }
7028
7029            if (includeBrowser) {
7030                // Also add browsers (all of them or only the default one)
7031                if (DEBUG_DOMAIN_VERIFICATION) {
7032                    Slog.v(TAG, "   ...including browsers in candidate set");
7033                }
7034                if ((matchFlags & MATCH_ALL) != 0) {
7035                    result.addAll(matchAllList);
7036                } else {
7037                    // Browser/generic handling case.  If there's a default browser, go straight
7038                    // to that (but only if there is no other higher-priority match).
7039                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7040                    int maxMatchPrio = 0;
7041                    ResolveInfo defaultBrowserMatch = null;
7042                    final int numCandidates = matchAllList.size();
7043                    for (int n = 0; n < numCandidates; n++) {
7044                        ResolveInfo info = matchAllList.get(n);
7045                        // track the highest overall match priority...
7046                        if (info.priority > maxMatchPrio) {
7047                            maxMatchPrio = info.priority;
7048                        }
7049                        // ...and the highest-priority default browser match
7050                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7051                            if (defaultBrowserMatch == null
7052                                    || (defaultBrowserMatch.priority < info.priority)) {
7053                                if (debug) {
7054                                    Slog.v(TAG, "Considering default browser match " + info);
7055                                }
7056                                defaultBrowserMatch = info;
7057                            }
7058                        }
7059                    }
7060                    if (defaultBrowserMatch != null
7061                            && defaultBrowserMatch.priority >= maxMatchPrio
7062                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7063                    {
7064                        if (debug) {
7065                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7066                        }
7067                        result.add(defaultBrowserMatch);
7068                    } else {
7069                        result.addAll(matchAllList);
7070                    }
7071                }
7072
7073                // If there is nothing selected, add all candidates and remove the ones that the user
7074                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7075                if (result.size() == 0) {
7076                    result.addAll(candidates);
7077                    result.removeAll(neverList);
7078                }
7079            }
7080        }
7081        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7082            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7083                    result.size());
7084            for (ResolveInfo info : result) {
7085                Slog.v(TAG, "  + " + info.activityInfo);
7086            }
7087        }
7088        return result;
7089    }
7090
7091    // Returns a packed value as a long:
7092    //
7093    // high 'int'-sized word: link status: undefined/ask/never/always.
7094    // low 'int'-sized word: relative priority among 'always' results.
7095    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7096        long result = ps.getDomainVerificationStatusForUser(userId);
7097        // if none available, get the master status
7098        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7099            if (ps.getIntentFilterVerificationInfo() != null) {
7100                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7101            }
7102        }
7103        return result;
7104    }
7105
7106    private ResolveInfo querySkipCurrentProfileIntents(
7107            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7108            int flags, int sourceUserId) {
7109        if (matchingFilters != null) {
7110            int size = matchingFilters.size();
7111            for (int i = 0; i < size; i ++) {
7112                CrossProfileIntentFilter filter = matchingFilters.get(i);
7113                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7114                    // Checking if there are activities in the target user that can handle the
7115                    // intent.
7116                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7117                            resolvedType, flags, sourceUserId);
7118                    if (resolveInfo != null) {
7119                        return resolveInfo;
7120                    }
7121                }
7122            }
7123        }
7124        return null;
7125    }
7126
7127    // Return matching ResolveInfo in target user if any.
7128    private ResolveInfo queryCrossProfileIntents(
7129            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7130            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7131        if (matchingFilters != null) {
7132            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7133            // match the same intent. For performance reasons, it is better not to
7134            // run queryIntent twice for the same userId
7135            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7136            int size = matchingFilters.size();
7137            for (int i = 0; i < size; i++) {
7138                CrossProfileIntentFilter filter = matchingFilters.get(i);
7139                int targetUserId = filter.getTargetUserId();
7140                boolean skipCurrentProfile =
7141                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7142                boolean skipCurrentProfileIfNoMatchFound =
7143                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7144                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7145                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7146                    // Checking if there are activities in the target user that can handle the
7147                    // intent.
7148                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7149                            resolvedType, flags, sourceUserId);
7150                    if (resolveInfo != null) return resolveInfo;
7151                    alreadyTriedUserIds.put(targetUserId, true);
7152                }
7153            }
7154        }
7155        return null;
7156    }
7157
7158    /**
7159     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7160     * will forward the intent to the filter's target user.
7161     * Otherwise, returns null.
7162     */
7163    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7164            String resolvedType, int flags, int sourceUserId) {
7165        int targetUserId = filter.getTargetUserId();
7166        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7167                resolvedType, flags, targetUserId);
7168        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7169            // If all the matches in the target profile are suspended, return null.
7170            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7171                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7172                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7173                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7174                            targetUserId);
7175                }
7176            }
7177        }
7178        return null;
7179    }
7180
7181    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7182            int sourceUserId, int targetUserId) {
7183        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7184        long ident = Binder.clearCallingIdentity();
7185        boolean targetIsProfile;
7186        try {
7187            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7188        } finally {
7189            Binder.restoreCallingIdentity(ident);
7190        }
7191        String className;
7192        if (targetIsProfile) {
7193            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7194        } else {
7195            className = FORWARD_INTENT_TO_PARENT;
7196        }
7197        ComponentName forwardingActivityComponentName = new ComponentName(
7198                mAndroidApplication.packageName, className);
7199        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7200                sourceUserId);
7201        if (!targetIsProfile) {
7202            forwardingActivityInfo.showUserIcon = targetUserId;
7203            forwardingResolveInfo.noResourceId = true;
7204        }
7205        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7206        forwardingResolveInfo.priority = 0;
7207        forwardingResolveInfo.preferredOrder = 0;
7208        forwardingResolveInfo.match = 0;
7209        forwardingResolveInfo.isDefault = true;
7210        forwardingResolveInfo.filter = filter;
7211        forwardingResolveInfo.targetUserId = targetUserId;
7212        return forwardingResolveInfo;
7213    }
7214
7215    @Override
7216    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7217            Intent[] specifics, String[] specificTypes, Intent intent,
7218            String resolvedType, int flags, int userId) {
7219        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7220                specificTypes, intent, resolvedType, flags, userId));
7221    }
7222
7223    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7224            Intent[] specifics, String[] specificTypes, Intent intent,
7225            String resolvedType, int flags, int userId) {
7226        if (!sUserManager.exists(userId)) return Collections.emptyList();
7227        final int callingUid = Binder.getCallingUid();
7228        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7229                false /*includeInstantApps*/);
7230        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7231                false /*requireFullPermission*/, false /*checkShell*/,
7232                "query intent activity options");
7233        final String resultsAction = intent.getAction();
7234
7235        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7236                | PackageManager.GET_RESOLVED_FILTER, userId);
7237
7238        if (DEBUG_INTENT_MATCHING) {
7239            Log.v(TAG, "Query " + intent + ": " + results);
7240        }
7241
7242        int specificsPos = 0;
7243        int N;
7244
7245        // todo: note that the algorithm used here is O(N^2).  This
7246        // isn't a problem in our current environment, but if we start running
7247        // into situations where we have more than 5 or 10 matches then this
7248        // should probably be changed to something smarter...
7249
7250        // First we go through and resolve each of the specific items
7251        // that were supplied, taking care of removing any corresponding
7252        // duplicate items in the generic resolve list.
7253        if (specifics != null) {
7254            for (int i=0; i<specifics.length; i++) {
7255                final Intent sintent = specifics[i];
7256                if (sintent == null) {
7257                    continue;
7258                }
7259
7260                if (DEBUG_INTENT_MATCHING) {
7261                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7262                }
7263
7264                String action = sintent.getAction();
7265                if (resultsAction != null && resultsAction.equals(action)) {
7266                    // If this action was explicitly requested, then don't
7267                    // remove things that have it.
7268                    action = null;
7269                }
7270
7271                ResolveInfo ri = null;
7272                ActivityInfo ai = null;
7273
7274                ComponentName comp = sintent.getComponent();
7275                if (comp == null) {
7276                    ri = resolveIntent(
7277                        sintent,
7278                        specificTypes != null ? specificTypes[i] : null,
7279                            flags, userId);
7280                    if (ri == null) {
7281                        continue;
7282                    }
7283                    if (ri == mResolveInfo) {
7284                        // ACK!  Must do something better with this.
7285                    }
7286                    ai = ri.activityInfo;
7287                    comp = new ComponentName(ai.applicationInfo.packageName,
7288                            ai.name);
7289                } else {
7290                    ai = getActivityInfo(comp, flags, userId);
7291                    if (ai == null) {
7292                        continue;
7293                    }
7294                }
7295
7296                // Look for any generic query activities that are duplicates
7297                // of this specific one, and remove them from the results.
7298                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7299                N = results.size();
7300                int j;
7301                for (j=specificsPos; j<N; j++) {
7302                    ResolveInfo sri = results.get(j);
7303                    if ((sri.activityInfo.name.equals(comp.getClassName())
7304                            && sri.activityInfo.applicationInfo.packageName.equals(
7305                                    comp.getPackageName()))
7306                        || (action != null && sri.filter.matchAction(action))) {
7307                        results.remove(j);
7308                        if (DEBUG_INTENT_MATCHING) Log.v(
7309                            TAG, "Removing duplicate item from " + j
7310                            + " due to specific " + specificsPos);
7311                        if (ri == null) {
7312                            ri = sri;
7313                        }
7314                        j--;
7315                        N--;
7316                    }
7317                }
7318
7319                // Add this specific item to its proper place.
7320                if (ri == null) {
7321                    ri = new ResolveInfo();
7322                    ri.activityInfo = ai;
7323                }
7324                results.add(specificsPos, ri);
7325                ri.specificIndex = i;
7326                specificsPos++;
7327            }
7328        }
7329
7330        // Now we go through the remaining generic results and remove any
7331        // duplicate actions that are found here.
7332        N = results.size();
7333        for (int i=specificsPos; i<N-1; i++) {
7334            final ResolveInfo rii = results.get(i);
7335            if (rii.filter == null) {
7336                continue;
7337            }
7338
7339            // Iterate over all of the actions of this result's intent
7340            // filter...  typically this should be just one.
7341            final Iterator<String> it = rii.filter.actionsIterator();
7342            if (it == null) {
7343                continue;
7344            }
7345            while (it.hasNext()) {
7346                final String action = it.next();
7347                if (resultsAction != null && resultsAction.equals(action)) {
7348                    // If this action was explicitly requested, then don't
7349                    // remove things that have it.
7350                    continue;
7351                }
7352                for (int j=i+1; j<N; j++) {
7353                    final ResolveInfo rij = results.get(j);
7354                    if (rij.filter != null && rij.filter.hasAction(action)) {
7355                        results.remove(j);
7356                        if (DEBUG_INTENT_MATCHING) Log.v(
7357                            TAG, "Removing duplicate item from " + j
7358                            + " due to action " + action + " at " + i);
7359                        j--;
7360                        N--;
7361                    }
7362                }
7363            }
7364
7365            // If the caller didn't request filter information, drop it now
7366            // so we don't have to marshall/unmarshall it.
7367            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7368                rii.filter = null;
7369            }
7370        }
7371
7372        // Filter out the caller activity if so requested.
7373        if (caller != null) {
7374            N = results.size();
7375            for (int i=0; i<N; i++) {
7376                ActivityInfo ainfo = results.get(i).activityInfo;
7377                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7378                        && caller.getClassName().equals(ainfo.name)) {
7379                    results.remove(i);
7380                    break;
7381                }
7382            }
7383        }
7384
7385        // If the caller didn't request filter information,
7386        // drop them now so we don't have to
7387        // marshall/unmarshall it.
7388        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7389            N = results.size();
7390            for (int i=0; i<N; i++) {
7391                results.get(i).filter = null;
7392            }
7393        }
7394
7395        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7396        return results;
7397    }
7398
7399    @Override
7400    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7401            String resolvedType, int flags, int userId) {
7402        return new ParceledListSlice<>(
7403                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7404                        false /*allowDynamicSplits*/));
7405    }
7406
7407    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7408            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7409        if (!sUserManager.exists(userId)) return Collections.emptyList();
7410        final int callingUid = Binder.getCallingUid();
7411        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7412                false /*requireFullPermission*/, false /*checkShell*/,
7413                "query intent receivers");
7414        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7415        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7416                false /*includeInstantApps*/);
7417        ComponentName comp = intent.getComponent();
7418        if (comp == null) {
7419            if (intent.getSelector() != null) {
7420                intent = intent.getSelector();
7421                comp = intent.getComponent();
7422            }
7423        }
7424        if (comp != null) {
7425            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7426            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7427            if (ai != null) {
7428                // When specifying an explicit component, we prevent the activity from being
7429                // used when either 1) the calling package is normal and the activity is within
7430                // an instant application or 2) the calling package is ephemeral and the
7431                // activity is not visible to instant applications.
7432                final boolean matchInstantApp =
7433                        (flags & PackageManager.MATCH_INSTANT) != 0;
7434                final boolean matchVisibleToInstantAppOnly =
7435                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7436                final boolean matchExplicitlyVisibleOnly =
7437                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7438                final boolean isCallerInstantApp =
7439                        instantAppPkgName != null;
7440                final boolean isTargetSameInstantApp =
7441                        comp.getPackageName().equals(instantAppPkgName);
7442                final boolean isTargetInstantApp =
7443                        (ai.applicationInfo.privateFlags
7444                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7445                final boolean isTargetVisibleToInstantApp =
7446                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7447                final boolean isTargetExplicitlyVisibleToInstantApp =
7448                        isTargetVisibleToInstantApp
7449                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7450                final boolean isTargetHiddenFromInstantApp =
7451                        !isTargetVisibleToInstantApp
7452                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7453                final boolean blockResolution =
7454                        !isTargetSameInstantApp
7455                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7456                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7457                                        && isTargetHiddenFromInstantApp));
7458                if (!blockResolution) {
7459                    ResolveInfo ri = new ResolveInfo();
7460                    ri.activityInfo = ai;
7461                    list.add(ri);
7462                }
7463            }
7464            return applyPostResolutionFilter(
7465                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7466        }
7467
7468        // reader
7469        synchronized (mPackages) {
7470            String pkgName = intent.getPackage();
7471            if (pkgName == null) {
7472                final List<ResolveInfo> result =
7473                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7474                return applyPostResolutionFilter(
7475                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7476            }
7477            final PackageParser.Package pkg = mPackages.get(pkgName);
7478            if (pkg != null) {
7479                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7480                        intent, resolvedType, flags, pkg.receivers, userId);
7481                return applyPostResolutionFilter(
7482                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7483            }
7484            return Collections.emptyList();
7485        }
7486    }
7487
7488    @Override
7489    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7490        final int callingUid = Binder.getCallingUid();
7491        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7492    }
7493
7494    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7495            int userId, int callingUid) {
7496        if (!sUserManager.exists(userId)) return null;
7497        flags = updateFlagsForResolve(
7498                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7499        List<ResolveInfo> query = queryIntentServicesInternal(
7500                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7501        if (query != null) {
7502            if (query.size() >= 1) {
7503                // If there is more than one service with the same priority,
7504                // just arbitrarily pick the first one.
7505                return query.get(0);
7506            }
7507        }
7508        return null;
7509    }
7510
7511    @Override
7512    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7513            String resolvedType, int flags, int userId) {
7514        final int callingUid = Binder.getCallingUid();
7515        return new ParceledListSlice<>(queryIntentServicesInternal(
7516                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7517    }
7518
7519    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7520            String resolvedType, int flags, int userId, int callingUid,
7521            boolean includeInstantApps) {
7522        if (!sUserManager.exists(userId)) return Collections.emptyList();
7523        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7524                false /*requireFullPermission*/, false /*checkShell*/,
7525                "query intent receivers");
7526        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7527        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7528        ComponentName comp = intent.getComponent();
7529        if (comp == null) {
7530            if (intent.getSelector() != null) {
7531                intent = intent.getSelector();
7532                comp = intent.getComponent();
7533            }
7534        }
7535        if (comp != null) {
7536            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7537            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7538            if (si != null) {
7539                // When specifying an explicit component, we prevent the service from being
7540                // used when either 1) the service is in an instant application and the
7541                // caller is not the same instant application or 2) the calling package is
7542                // ephemeral and the activity is not visible to ephemeral applications.
7543                final boolean matchInstantApp =
7544                        (flags & PackageManager.MATCH_INSTANT) != 0;
7545                final boolean matchVisibleToInstantAppOnly =
7546                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7547                final boolean isCallerInstantApp =
7548                        instantAppPkgName != null;
7549                final boolean isTargetSameInstantApp =
7550                        comp.getPackageName().equals(instantAppPkgName);
7551                final boolean isTargetInstantApp =
7552                        (si.applicationInfo.privateFlags
7553                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7554                final boolean isTargetHiddenFromInstantApp =
7555                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7556                final boolean blockResolution =
7557                        !isTargetSameInstantApp
7558                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7559                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7560                                        && isTargetHiddenFromInstantApp));
7561                if (!blockResolution) {
7562                    final ResolveInfo ri = new ResolveInfo();
7563                    ri.serviceInfo = si;
7564                    list.add(ri);
7565                }
7566            }
7567            return list;
7568        }
7569
7570        // reader
7571        synchronized (mPackages) {
7572            String pkgName = intent.getPackage();
7573            if (pkgName == null) {
7574                return applyPostServiceResolutionFilter(
7575                        mServices.queryIntent(intent, resolvedType, flags, userId),
7576                        instantAppPkgName);
7577            }
7578            final PackageParser.Package pkg = mPackages.get(pkgName);
7579            if (pkg != null) {
7580                return applyPostServiceResolutionFilter(
7581                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7582                                userId),
7583                        instantAppPkgName);
7584            }
7585            return Collections.emptyList();
7586        }
7587    }
7588
7589    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7590            String instantAppPkgName) {
7591        if (instantAppPkgName == null) {
7592            return resolveInfos;
7593        }
7594        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7595            final ResolveInfo info = resolveInfos.get(i);
7596            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7597            // allow services that are defined in the provided package
7598            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7599                if (info.serviceInfo.splitName != null
7600                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7601                                info.serviceInfo.splitName)) {
7602                    // requested service is defined in a split that hasn't been installed yet.
7603                    // add the installer to the resolve list
7604                    if (DEBUG_INSTANT) {
7605                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7606                    }
7607                    final ResolveInfo installerInfo = new ResolveInfo(
7608                            mInstantAppInstallerInfo);
7609                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7610                            null /* installFailureActivity */,
7611                            info.serviceInfo.packageName,
7612                            info.serviceInfo.applicationInfo.versionCode,
7613                            info.serviceInfo.splitName);
7614                    // make sure this resolver is the default
7615                    installerInfo.isDefault = true;
7616                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7617                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7618                    // add a non-generic filter
7619                    installerInfo.filter = new IntentFilter();
7620                    // load resources from the correct package
7621                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7622                    resolveInfos.set(i, installerInfo);
7623                }
7624                continue;
7625            }
7626            // allow services that have been explicitly exposed to ephemeral apps
7627            if (!isEphemeralApp
7628                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7629                continue;
7630            }
7631            resolveInfos.remove(i);
7632        }
7633        return resolveInfos;
7634    }
7635
7636    @Override
7637    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7638            String resolvedType, int flags, int userId) {
7639        return new ParceledListSlice<>(
7640                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7641    }
7642
7643    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7644            Intent intent, String resolvedType, int flags, int userId) {
7645        if (!sUserManager.exists(userId)) return Collections.emptyList();
7646        final int callingUid = Binder.getCallingUid();
7647        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7648        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7649                false /*includeInstantApps*/);
7650        ComponentName comp = intent.getComponent();
7651        if (comp == null) {
7652            if (intent.getSelector() != null) {
7653                intent = intent.getSelector();
7654                comp = intent.getComponent();
7655            }
7656        }
7657        if (comp != null) {
7658            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7659            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7660            if (pi != null) {
7661                // When specifying an explicit component, we prevent the provider from being
7662                // used when either 1) the provider is in an instant application and the
7663                // caller is not the same instant application or 2) the calling package is an
7664                // instant application and the provider is not visible to instant applications.
7665                final boolean matchInstantApp =
7666                        (flags & PackageManager.MATCH_INSTANT) != 0;
7667                final boolean matchVisibleToInstantAppOnly =
7668                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7669                final boolean isCallerInstantApp =
7670                        instantAppPkgName != null;
7671                final boolean isTargetSameInstantApp =
7672                        comp.getPackageName().equals(instantAppPkgName);
7673                final boolean isTargetInstantApp =
7674                        (pi.applicationInfo.privateFlags
7675                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7676                final boolean isTargetHiddenFromInstantApp =
7677                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7678                final boolean blockResolution =
7679                        !isTargetSameInstantApp
7680                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7681                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7682                                        && isTargetHiddenFromInstantApp));
7683                if (!blockResolution) {
7684                    final ResolveInfo ri = new ResolveInfo();
7685                    ri.providerInfo = pi;
7686                    list.add(ri);
7687                }
7688            }
7689            return list;
7690        }
7691
7692        // reader
7693        synchronized (mPackages) {
7694            String pkgName = intent.getPackage();
7695            if (pkgName == null) {
7696                return applyPostContentProviderResolutionFilter(
7697                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7698                        instantAppPkgName);
7699            }
7700            final PackageParser.Package pkg = mPackages.get(pkgName);
7701            if (pkg != null) {
7702                return applyPostContentProviderResolutionFilter(
7703                        mProviders.queryIntentForPackage(
7704                        intent, resolvedType, flags, pkg.providers, userId),
7705                        instantAppPkgName);
7706            }
7707            return Collections.emptyList();
7708        }
7709    }
7710
7711    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7712            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7713        if (instantAppPkgName == null) {
7714            return resolveInfos;
7715        }
7716        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7717            final ResolveInfo info = resolveInfos.get(i);
7718            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7719            // allow providers that are defined in the provided package
7720            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7721                if (info.providerInfo.splitName != null
7722                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7723                                info.providerInfo.splitName)) {
7724                    // requested provider is defined in a split that hasn't been installed yet.
7725                    // add the installer to the resolve list
7726                    if (DEBUG_INSTANT) {
7727                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7728                    }
7729                    final ResolveInfo installerInfo = new ResolveInfo(
7730                            mInstantAppInstallerInfo);
7731                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7732                            null /*failureActivity*/,
7733                            info.providerInfo.packageName,
7734                            info.providerInfo.applicationInfo.versionCode,
7735                            info.providerInfo.splitName);
7736                    // make sure this resolver is the default
7737                    installerInfo.isDefault = true;
7738                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7739                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7740                    // add a non-generic filter
7741                    installerInfo.filter = new IntentFilter();
7742                    // load resources from the correct package
7743                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7744                    resolveInfos.set(i, installerInfo);
7745                }
7746                continue;
7747            }
7748            // allow providers that have been explicitly exposed to instant applications
7749            if (!isEphemeralApp
7750                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7751                continue;
7752            }
7753            resolveInfos.remove(i);
7754        }
7755        return resolveInfos;
7756    }
7757
7758    @Override
7759    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7760        final int callingUid = Binder.getCallingUid();
7761        if (getInstantAppPackageName(callingUid) != null) {
7762            return ParceledListSlice.emptyList();
7763        }
7764        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7765        flags = updateFlagsForPackage(flags, userId, null);
7766        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7767        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7768                true /* requireFullPermission */, false /* checkShell */,
7769                "get installed packages");
7770
7771        // writer
7772        synchronized (mPackages) {
7773            ArrayList<PackageInfo> list;
7774            if (listUninstalled) {
7775                list = new ArrayList<>(mSettings.mPackages.size());
7776                for (PackageSetting ps : mSettings.mPackages.values()) {
7777                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7778                        continue;
7779                    }
7780                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7781                        continue;
7782                    }
7783                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7784                    if (pi != null) {
7785                        list.add(pi);
7786                    }
7787                }
7788            } else {
7789                list = new ArrayList<>(mPackages.size());
7790                for (PackageParser.Package p : mPackages.values()) {
7791                    final PackageSetting ps = (PackageSetting) p.mExtras;
7792                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7793                        continue;
7794                    }
7795                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7796                        continue;
7797                    }
7798                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7799                            p.mExtras, flags, userId);
7800                    if (pi != null) {
7801                        list.add(pi);
7802                    }
7803                }
7804            }
7805
7806            return new ParceledListSlice<>(list);
7807        }
7808    }
7809
7810    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7811            String[] permissions, boolean[] tmp, int flags, int userId) {
7812        int numMatch = 0;
7813        final PermissionsState permissionsState = ps.getPermissionsState();
7814        for (int i=0; i<permissions.length; i++) {
7815            final String permission = permissions[i];
7816            if (permissionsState.hasPermission(permission, userId)) {
7817                tmp[i] = true;
7818                numMatch++;
7819            } else {
7820                tmp[i] = false;
7821            }
7822        }
7823        if (numMatch == 0) {
7824            return;
7825        }
7826        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7827
7828        // The above might return null in cases of uninstalled apps or install-state
7829        // skew across users/profiles.
7830        if (pi != null) {
7831            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7832                if (numMatch == permissions.length) {
7833                    pi.requestedPermissions = permissions;
7834                } else {
7835                    pi.requestedPermissions = new String[numMatch];
7836                    numMatch = 0;
7837                    for (int i=0; i<permissions.length; i++) {
7838                        if (tmp[i]) {
7839                            pi.requestedPermissions[numMatch] = permissions[i];
7840                            numMatch++;
7841                        }
7842                    }
7843                }
7844            }
7845            list.add(pi);
7846        }
7847    }
7848
7849    @Override
7850    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7851            String[] permissions, int flags, int userId) {
7852        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7853        flags = updateFlagsForPackage(flags, userId, permissions);
7854        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7855                true /* requireFullPermission */, false /* checkShell */,
7856                "get packages holding permissions");
7857        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7858
7859        // writer
7860        synchronized (mPackages) {
7861            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7862            boolean[] tmpBools = new boolean[permissions.length];
7863            if (listUninstalled) {
7864                for (PackageSetting ps : mSettings.mPackages.values()) {
7865                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7866                            userId);
7867                }
7868            } else {
7869                for (PackageParser.Package pkg : mPackages.values()) {
7870                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7871                    if (ps != null) {
7872                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7873                                userId);
7874                    }
7875                }
7876            }
7877
7878            return new ParceledListSlice<PackageInfo>(list);
7879        }
7880    }
7881
7882    @Override
7883    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7884        final int callingUid = Binder.getCallingUid();
7885        if (getInstantAppPackageName(callingUid) != null) {
7886            return ParceledListSlice.emptyList();
7887        }
7888        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7889        flags = updateFlagsForApplication(flags, userId, null);
7890        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7891
7892        // writer
7893        synchronized (mPackages) {
7894            ArrayList<ApplicationInfo> list;
7895            if (listUninstalled) {
7896                list = new ArrayList<>(mSettings.mPackages.size());
7897                for (PackageSetting ps : mSettings.mPackages.values()) {
7898                    ApplicationInfo ai;
7899                    int effectiveFlags = flags;
7900                    if (ps.isSystem()) {
7901                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7902                    }
7903                    if (ps.pkg != null) {
7904                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7905                            continue;
7906                        }
7907                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7908                            continue;
7909                        }
7910                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7911                                ps.readUserState(userId), userId);
7912                        if (ai != null) {
7913                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7914                        }
7915                    } else {
7916                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7917                        // and already converts to externally visible package name
7918                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7919                                callingUid, effectiveFlags, userId);
7920                    }
7921                    if (ai != null) {
7922                        list.add(ai);
7923                    }
7924                }
7925            } else {
7926                list = new ArrayList<>(mPackages.size());
7927                for (PackageParser.Package p : mPackages.values()) {
7928                    if (p.mExtras != null) {
7929                        PackageSetting ps = (PackageSetting) p.mExtras;
7930                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7931                            continue;
7932                        }
7933                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7934                            continue;
7935                        }
7936                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7937                                ps.readUserState(userId), userId);
7938                        if (ai != null) {
7939                            ai.packageName = resolveExternalPackageNameLPr(p);
7940                            list.add(ai);
7941                        }
7942                    }
7943                }
7944            }
7945
7946            return new ParceledListSlice<>(list);
7947        }
7948    }
7949
7950    @Override
7951    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7952        if (HIDE_EPHEMERAL_APIS) {
7953            return null;
7954        }
7955        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7956            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7957                    "getEphemeralApplications");
7958        }
7959        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7960                true /* requireFullPermission */, false /* checkShell */,
7961                "getEphemeralApplications");
7962        synchronized (mPackages) {
7963            List<InstantAppInfo> instantApps = mInstantAppRegistry
7964                    .getInstantAppsLPr(userId);
7965            if (instantApps != null) {
7966                return new ParceledListSlice<>(instantApps);
7967            }
7968        }
7969        return null;
7970    }
7971
7972    @Override
7973    public boolean isInstantApp(String packageName, int userId) {
7974        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7975                true /* requireFullPermission */, false /* checkShell */,
7976                "isInstantApp");
7977        if (HIDE_EPHEMERAL_APIS) {
7978            return false;
7979        }
7980
7981        synchronized (mPackages) {
7982            int callingUid = Binder.getCallingUid();
7983            if (Process.isIsolated(callingUid)) {
7984                callingUid = mIsolatedOwners.get(callingUid);
7985            }
7986            final PackageSetting ps = mSettings.mPackages.get(packageName);
7987            PackageParser.Package pkg = mPackages.get(packageName);
7988            final boolean returnAllowed =
7989                    ps != null
7990                    && (isCallerSameApp(packageName, callingUid)
7991                            || canViewInstantApps(callingUid, userId)
7992                            || mInstantAppRegistry.isInstantAccessGranted(
7993                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7994            if (returnAllowed) {
7995                return ps.getInstantApp(userId);
7996            }
7997        }
7998        return false;
7999    }
8000
8001    @Override
8002    public byte[] getInstantAppCookie(String packageName, int userId) {
8003        if (HIDE_EPHEMERAL_APIS) {
8004            return null;
8005        }
8006
8007        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8008                true /* requireFullPermission */, false /* checkShell */,
8009                "getInstantAppCookie");
8010        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8011            return null;
8012        }
8013        synchronized (mPackages) {
8014            return mInstantAppRegistry.getInstantAppCookieLPw(
8015                    packageName, userId);
8016        }
8017    }
8018
8019    @Override
8020    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8021        if (HIDE_EPHEMERAL_APIS) {
8022            return true;
8023        }
8024
8025        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8026                true /* requireFullPermission */, true /* checkShell */,
8027                "setInstantAppCookie");
8028        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8029            return false;
8030        }
8031        synchronized (mPackages) {
8032            return mInstantAppRegistry.setInstantAppCookieLPw(
8033                    packageName, cookie, userId);
8034        }
8035    }
8036
8037    @Override
8038    public Bitmap getInstantAppIcon(String packageName, int userId) {
8039        if (HIDE_EPHEMERAL_APIS) {
8040            return null;
8041        }
8042
8043        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8044            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8045                    "getInstantAppIcon");
8046        }
8047        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8048                true /* requireFullPermission */, false /* checkShell */,
8049                "getInstantAppIcon");
8050
8051        synchronized (mPackages) {
8052            return mInstantAppRegistry.getInstantAppIconLPw(
8053                    packageName, userId);
8054        }
8055    }
8056
8057    private boolean isCallerSameApp(String packageName, int uid) {
8058        PackageParser.Package pkg = mPackages.get(packageName);
8059        return pkg != null
8060                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8061    }
8062
8063    @Override
8064    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8065        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8066            return ParceledListSlice.emptyList();
8067        }
8068        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8069    }
8070
8071    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8072        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8073
8074        // reader
8075        synchronized (mPackages) {
8076            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8077            final int userId = UserHandle.getCallingUserId();
8078            while (i.hasNext()) {
8079                final PackageParser.Package p = i.next();
8080                if (p.applicationInfo == null) continue;
8081
8082                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8083                        && !p.applicationInfo.isDirectBootAware();
8084                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8085                        && p.applicationInfo.isDirectBootAware();
8086
8087                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8088                        && (!mSafeMode || isSystemApp(p))
8089                        && (matchesUnaware || matchesAware)) {
8090                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8091                    if (ps != null) {
8092                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8093                                ps.readUserState(userId), userId);
8094                        if (ai != null) {
8095                            finalList.add(ai);
8096                        }
8097                    }
8098                }
8099            }
8100        }
8101
8102        return finalList;
8103    }
8104
8105    @Override
8106    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8107        return resolveContentProviderInternal(name, flags, userId);
8108    }
8109
8110    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8111        if (!sUserManager.exists(userId)) return null;
8112        flags = updateFlagsForComponent(flags, userId, name);
8113        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8114        // reader
8115        synchronized (mPackages) {
8116            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8117            PackageSetting ps = provider != null
8118                    ? mSettings.mPackages.get(provider.owner.packageName)
8119                    : null;
8120            if (ps != null) {
8121                final boolean isInstantApp = ps.getInstantApp(userId);
8122                // normal application; filter out instant application provider
8123                if (instantAppPkgName == null && isInstantApp) {
8124                    return null;
8125                }
8126                // instant application; filter out other instant applications
8127                if (instantAppPkgName != null
8128                        && isInstantApp
8129                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8130                    return null;
8131                }
8132                // instant application; filter out non-exposed provider
8133                if (instantAppPkgName != null
8134                        && !isInstantApp
8135                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8136                    return null;
8137                }
8138                // provider not enabled
8139                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8140                    return null;
8141                }
8142                return PackageParser.generateProviderInfo(
8143                        provider, flags, ps.readUserState(userId), userId);
8144            }
8145            return null;
8146        }
8147    }
8148
8149    /**
8150     * @deprecated
8151     */
8152    @Deprecated
8153    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8154        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8155            return;
8156        }
8157        // reader
8158        synchronized (mPackages) {
8159            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8160                    .entrySet().iterator();
8161            final int userId = UserHandle.getCallingUserId();
8162            while (i.hasNext()) {
8163                Map.Entry<String, PackageParser.Provider> entry = i.next();
8164                PackageParser.Provider p = entry.getValue();
8165                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8166
8167                if (ps != null && p.syncable
8168                        && (!mSafeMode || (p.info.applicationInfo.flags
8169                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8170                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8171                            ps.readUserState(userId), userId);
8172                    if (info != null) {
8173                        outNames.add(entry.getKey());
8174                        outInfo.add(info);
8175                    }
8176                }
8177            }
8178        }
8179    }
8180
8181    @Override
8182    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8183            int uid, int flags, String metaDataKey) {
8184        final int callingUid = Binder.getCallingUid();
8185        final int userId = processName != null ? UserHandle.getUserId(uid)
8186                : UserHandle.getCallingUserId();
8187        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8188        flags = updateFlagsForComponent(flags, userId, processName);
8189        ArrayList<ProviderInfo> finalList = null;
8190        // reader
8191        synchronized (mPackages) {
8192            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8193            while (i.hasNext()) {
8194                final PackageParser.Provider p = i.next();
8195                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8196                if (ps != null && p.info.authority != null
8197                        && (processName == null
8198                                || (p.info.processName.equals(processName)
8199                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8200                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8201
8202                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8203                    // parameter.
8204                    if (metaDataKey != null
8205                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8206                        continue;
8207                    }
8208                    final ComponentName component =
8209                            new ComponentName(p.info.packageName, p.info.name);
8210                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8211                        continue;
8212                    }
8213                    if (finalList == null) {
8214                        finalList = new ArrayList<ProviderInfo>(3);
8215                    }
8216                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8217                            ps.readUserState(userId), userId);
8218                    if (info != null) {
8219                        finalList.add(info);
8220                    }
8221                }
8222            }
8223        }
8224
8225        if (finalList != null) {
8226            Collections.sort(finalList, mProviderInitOrderSorter);
8227            return new ParceledListSlice<ProviderInfo>(finalList);
8228        }
8229
8230        return ParceledListSlice.emptyList();
8231    }
8232
8233    @Override
8234    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8235        // reader
8236        synchronized (mPackages) {
8237            final int callingUid = Binder.getCallingUid();
8238            final int callingUserId = UserHandle.getUserId(callingUid);
8239            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8240            if (ps == null) return null;
8241            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8242                return null;
8243            }
8244            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8245            return PackageParser.generateInstrumentationInfo(i, flags);
8246        }
8247    }
8248
8249    @Override
8250    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8251            String targetPackage, int flags) {
8252        final int callingUid = Binder.getCallingUid();
8253        final int callingUserId = UserHandle.getUserId(callingUid);
8254        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8255        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8256            return ParceledListSlice.emptyList();
8257        }
8258        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8259    }
8260
8261    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8262            int flags) {
8263        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8264
8265        // reader
8266        synchronized (mPackages) {
8267            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8268            while (i.hasNext()) {
8269                final PackageParser.Instrumentation p = i.next();
8270                if (targetPackage == null
8271                        || targetPackage.equals(p.info.targetPackage)) {
8272                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8273                            flags);
8274                    if (ii != null) {
8275                        finalList.add(ii);
8276                    }
8277                }
8278            }
8279        }
8280
8281        return finalList;
8282    }
8283
8284    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8286        try {
8287            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8288        } finally {
8289            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8290        }
8291    }
8292
8293    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8294        final File[] files = scanDir.listFiles();
8295        if (ArrayUtils.isEmpty(files)) {
8296            Log.d(TAG, "No files in app dir " + scanDir);
8297            return;
8298        }
8299
8300        if (DEBUG_PACKAGE_SCANNING) {
8301            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8302                    + " flags=0x" + Integer.toHexString(parseFlags));
8303        }
8304        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8305                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8306                mParallelPackageParserCallback)) {
8307            // Submit files for parsing in parallel
8308            int fileCount = 0;
8309            for (File file : files) {
8310                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8311                        && !PackageInstallerService.isStageName(file.getName());
8312                if (!isPackage) {
8313                    // Ignore entries which are not packages
8314                    continue;
8315                }
8316                parallelPackageParser.submit(file, parseFlags);
8317                fileCount++;
8318            }
8319
8320            // Process results one by one
8321            for (; fileCount > 0; fileCount--) {
8322                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8323                Throwable throwable = parseResult.throwable;
8324                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8325
8326                if (throwable == null) {
8327                    // TODO(toddke): move lower in the scan chain
8328                    // Static shared libraries have synthetic package names
8329                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8330                        renameStaticSharedLibraryPackage(parseResult.pkg);
8331                    }
8332                    try {
8333                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8334                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8335                                    currentTime, null);
8336                        }
8337                    } catch (PackageManagerException e) {
8338                        errorCode = e.error;
8339                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8340                    }
8341                } else if (throwable instanceof PackageParser.PackageParserException) {
8342                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8343                            throwable;
8344                    errorCode = e.error;
8345                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8346                } else {
8347                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8348                            + parseResult.scanFile, throwable);
8349                }
8350
8351                // Delete invalid userdata apps
8352                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8353                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8354                    logCriticalInfo(Log.WARN,
8355                            "Deleting invalid package at " + parseResult.scanFile);
8356                    removeCodePathLI(parseResult.scanFile);
8357                }
8358            }
8359        }
8360    }
8361
8362    public static void reportSettingsProblem(int priority, String msg) {
8363        logCriticalInfo(priority, msg);
8364    }
8365
8366    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8367            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8368        // When upgrading from pre-N MR1, verify the package time stamp using the package
8369        // directory and not the APK file.
8370        final long lastModifiedTime = mIsPreNMR1Upgrade
8371                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8372        if (ps != null && !forceCollect
8373                && ps.codePathString.equals(pkg.codePath)
8374                && ps.timeStamp == lastModifiedTime
8375                && !isCompatSignatureUpdateNeeded(pkg)
8376                && !isRecoverSignatureUpdateNeeded(pkg)) {
8377            if (ps.signatures.mSigningDetails.signatures != null
8378                    && ps.signatures.mSigningDetails.signatures.length != 0
8379                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8380                            != SignatureSchemeVersion.UNKNOWN) {
8381                // Optimization: reuse the existing cached signing data
8382                // if the package appears to be unchanged.
8383                pkg.mSigningDetails =
8384                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8385                return;
8386            }
8387
8388            Slog.w(TAG, "PackageSetting for " + ps.name
8389                    + " is missing signatures.  Collecting certs again to recover them.");
8390        } else {
8391            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8392                    (forceCollect ? " (forced)" : ""));
8393        }
8394
8395        try {
8396            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8397            PackageParser.collectCertificates(pkg, skipVerify);
8398        } catch (PackageParserException e) {
8399            throw PackageManagerException.from(e);
8400        } finally {
8401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8402        }
8403    }
8404
8405    /**
8406     *  Traces a package scan.
8407     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8408     */
8409    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8410            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8411        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8412        try {
8413            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8414        } finally {
8415            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8416        }
8417    }
8418
8419    /**
8420     *  Scans a package and returns the newly parsed package.
8421     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8422     */
8423    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8424            long currentTime, UserHandle user) throws PackageManagerException {
8425        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8426        PackageParser pp = new PackageParser();
8427        pp.setSeparateProcesses(mSeparateProcesses);
8428        pp.setOnlyCoreApps(mOnlyCore);
8429        pp.setDisplayMetrics(mMetrics);
8430        pp.setCallback(mPackageParserCallback);
8431
8432        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8433        final PackageParser.Package pkg;
8434        try {
8435            pkg = pp.parsePackage(scanFile, parseFlags);
8436        } catch (PackageParserException e) {
8437            throw PackageManagerException.from(e);
8438        } finally {
8439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8440        }
8441
8442        // Static shared libraries have synthetic package names
8443        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8444            renameStaticSharedLibraryPackage(pkg);
8445        }
8446
8447        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8448    }
8449
8450    /**
8451     *  Scans a package and returns the newly parsed package.
8452     *  @throws PackageManagerException on a parse error.
8453     */
8454    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8455            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8456            @Nullable UserHandle user)
8457                    throws PackageManagerException {
8458        // If the package has children and this is the first dive in the function
8459        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8460        // packages (parent and children) would be successfully scanned before the
8461        // actual scan since scanning mutates internal state and we want to atomically
8462        // install the package and its children.
8463        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8464            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8465                scanFlags |= SCAN_CHECK_ONLY;
8466            }
8467        } else {
8468            scanFlags &= ~SCAN_CHECK_ONLY;
8469        }
8470
8471        // Scan the parent
8472        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8473                scanFlags, currentTime, user);
8474
8475        // Scan the children
8476        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8477        for (int i = 0; i < childCount; i++) {
8478            PackageParser.Package childPackage = pkg.childPackages.get(i);
8479            addForInitLI(childPackage, parseFlags, scanFlags,
8480                    currentTime, user);
8481        }
8482
8483
8484        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8485            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8486        }
8487
8488        return scannedPkg;
8489    }
8490
8491    /**
8492     * Returns if full apk verification can be skipped for the whole package, including the splits.
8493     */
8494    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8495        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8496            return false;
8497        }
8498        // TODO: Allow base and splits to be verified individually.
8499        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8500            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8501                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8502                    return false;
8503                }
8504            }
8505        }
8506        return true;
8507    }
8508
8509    /**
8510     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8511     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8512     * match one in a trusted source, and should be done separately.
8513     */
8514    private boolean canSkipFullApkVerification(String apkPath) {
8515        byte[] rootHashObserved = null;
8516        try {
8517            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8518            if (rootHashObserved == null) {
8519                return false;  // APK does not contain Merkle tree root hash.
8520            }
8521            synchronized (mInstallLock) {
8522                // Returns whether the observed root hash matches what kernel has.
8523                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8524                return true;
8525            }
8526        } catch (InstallerException | IOException | DigestException |
8527                NoSuchAlgorithmException e) {
8528            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8529        }
8530        return false;
8531    }
8532
8533    /**
8534     * Adds a new package to the internal data structures during platform initialization.
8535     * <p>After adding, the package is known to the system and available for querying.
8536     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8537     * etc...], additional checks are performed. Basic verification [such as ensuring
8538     * matching signatures, checking version codes, etc...] occurs if the package is
8539     * identical to a previously known package. If the package fails a signature check,
8540     * the version installed on /data will be removed. If the version of the new package
8541     * is less than or equal than the version on /data, it will be ignored.
8542     * <p>Regardless of the package location, the results are applied to the internal
8543     * structures and the package is made available to the rest of the system.
8544     * <p>NOTE: The return value should be removed. It's the passed in package object.
8545     */
8546    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8547            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8548            @Nullable UserHandle user)
8549                    throws PackageManagerException {
8550        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8551        final String renamedPkgName;
8552        final PackageSetting disabledPkgSetting;
8553        final boolean isSystemPkgUpdated;
8554        final boolean pkgAlreadyExists;
8555        PackageSetting pkgSetting;
8556
8557        // NOTE: installPackageLI() has the same code to setup the package's
8558        // application info. This probably should be done lower in the call
8559        // stack [such as scanPackageOnly()]. However, we verify the application
8560        // info prior to that [in scanPackageNew()] and thus have to setup
8561        // the application info early.
8562        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8563        pkg.setApplicationInfoCodePath(pkg.codePath);
8564        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8565        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8566        pkg.setApplicationInfoResourcePath(pkg.codePath);
8567        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8568        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8569
8570        synchronized (mPackages) {
8571            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8572            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8573            if (realPkgName != null) {
8574                ensurePackageRenamed(pkg, renamedPkgName);
8575            }
8576            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8577            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8578            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8579            pkgAlreadyExists = pkgSetting != null;
8580            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8581            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8582            isSystemPkgUpdated = disabledPkgSetting != null;
8583
8584            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8585                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8586            }
8587
8588            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8589                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8590                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8591                    : null;
8592            if (DEBUG_PACKAGE_SCANNING
8593                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8594                    && sharedUserSetting != null) {
8595                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8596                        + " (uid=" + sharedUserSetting.userId + "):"
8597                        + " packages=" + sharedUserSetting.packages);
8598            }
8599
8600            if (scanSystemPartition) {
8601                // Potentially prune child packages. If the application on the /system
8602                // partition has been updated via OTA, but, is still disabled by a
8603                // version on /data, cycle through all of its children packages and
8604                // remove children that are no longer defined.
8605                if (isSystemPkgUpdated) {
8606                    final int scannedChildCount = (pkg.childPackages != null)
8607                            ? pkg.childPackages.size() : 0;
8608                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8609                            ? disabledPkgSetting.childPackageNames.size() : 0;
8610                    for (int i = 0; i < disabledChildCount; i++) {
8611                        String disabledChildPackageName =
8612                                disabledPkgSetting.childPackageNames.get(i);
8613                        boolean disabledPackageAvailable = false;
8614                        for (int j = 0; j < scannedChildCount; j++) {
8615                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8616                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8617                                disabledPackageAvailable = true;
8618                                break;
8619                            }
8620                        }
8621                        if (!disabledPackageAvailable) {
8622                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8623                        }
8624                    }
8625                    // we're updating the disabled package, so, scan it as the package setting
8626                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8627                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8628                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8629                            (pkg == mPlatformPackage), user);
8630                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8631                }
8632            }
8633        }
8634
8635        final boolean newPkgChangedPaths =
8636                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8637        final boolean newPkgVersionGreater =
8638                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8639        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8640                && newPkgChangedPaths && newPkgVersionGreater;
8641        if (isSystemPkgBetter) {
8642            // The version of the application on /system is greater than the version on
8643            // /data. Switch back to the application on /system.
8644            // It's safe to assume the application on /system will correctly scan. If not,
8645            // there won't be a working copy of the application.
8646            synchronized (mPackages) {
8647                // just remove the loaded entries from package lists
8648                mPackages.remove(pkgSetting.name);
8649            }
8650
8651            logCriticalInfo(Log.WARN,
8652                    "System package updated;"
8653                    + " name: " + pkgSetting.name
8654                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8655                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8656
8657            final InstallArgs args = createInstallArgsForExisting(
8658                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8659                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8660            args.cleanUpResourcesLI();
8661            synchronized (mPackages) {
8662                mSettings.enableSystemPackageLPw(pkgSetting.name);
8663            }
8664        }
8665
8666        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8667            // The version of the application on the /system partition is less than or
8668            // equal to the version on the /data partition. Throw an exception and use
8669            // the application already installed on the /data partition.
8670            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8671                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8672                    + " better than this " + pkg.getLongVersionCode());
8673        }
8674
8675        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8676        // force re-collecting certificate.
8677        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8678                disabledPkgSetting);
8679        // Full APK verification can be skipped during certificate collection, only if the file is
8680        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8681        // cases, only data in Signing Block is verified instead of the whole file.
8682        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8683                (forceCollect && canSkipFullPackageVerification(pkg));
8684        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8685
8686        boolean shouldHideSystemApp = false;
8687        // A new application appeared on /system, but, we already have a copy of
8688        // the application installed on /data.
8689        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8690                && !pkgSetting.isSystem()) {
8691
8692            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8693                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8694                logCriticalInfo(Log.WARN,
8695                        "System package signature mismatch;"
8696                        + " name: " + pkgSetting.name);
8697                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8698                        "scanPackageInternalLI")) {
8699                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8700                }
8701                pkgSetting = null;
8702            } else if (newPkgVersionGreater) {
8703                // The application on /system is newer than the application on /data.
8704                // Simply remove the application on /data [keeping application data]
8705                // and replace it with the version on /system.
8706                logCriticalInfo(Log.WARN,
8707                        "System package enabled;"
8708                        + " name: " + pkgSetting.name
8709                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8710                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8711                InstallArgs args = createInstallArgsForExisting(
8712                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8713                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8714                synchronized (mInstallLock) {
8715                    args.cleanUpResourcesLI();
8716                }
8717            } else {
8718                // The application on /system is older than the application on /data. Hide
8719                // the application on /system and the version on /data will be scanned later
8720                // and re-added like an update.
8721                shouldHideSystemApp = true;
8722                logCriticalInfo(Log.INFO,
8723                        "System package disabled;"
8724                        + " name: " + pkgSetting.name
8725                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8726                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8727            }
8728        }
8729
8730        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8731                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8732
8733        if (shouldHideSystemApp) {
8734            synchronized (mPackages) {
8735                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8736            }
8737        }
8738        return scannedPkg;
8739    }
8740
8741    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8742        // Derive the new package synthetic package name
8743        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8744                + pkg.staticSharedLibVersion);
8745    }
8746
8747    private static String fixProcessName(String defProcessName,
8748            String processName) {
8749        if (processName == null) {
8750            return defProcessName;
8751        }
8752        return processName;
8753    }
8754
8755    /**
8756     * Enforces that only the system UID or root's UID can call a method exposed
8757     * via Binder.
8758     *
8759     * @param message used as message if SecurityException is thrown
8760     * @throws SecurityException if the caller is not system or root
8761     */
8762    private static final void enforceSystemOrRoot(String message) {
8763        final int uid = Binder.getCallingUid();
8764        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8765            throw new SecurityException(message);
8766        }
8767    }
8768
8769    @Override
8770    public void performFstrimIfNeeded() {
8771        enforceSystemOrRoot("Only the system can request fstrim");
8772
8773        // Before everything else, see whether we need to fstrim.
8774        try {
8775            IStorageManager sm = PackageHelper.getStorageManager();
8776            if (sm != null) {
8777                boolean doTrim = false;
8778                final long interval = android.provider.Settings.Global.getLong(
8779                        mContext.getContentResolver(),
8780                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8781                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8782                if (interval > 0) {
8783                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8784                    if (timeSinceLast > interval) {
8785                        doTrim = true;
8786                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8787                                + "; running immediately");
8788                    }
8789                }
8790                if (doTrim) {
8791                    final boolean dexOptDialogShown;
8792                    synchronized (mPackages) {
8793                        dexOptDialogShown = mDexOptDialogShown;
8794                    }
8795                    if (!isFirstBoot() && dexOptDialogShown) {
8796                        try {
8797                            ActivityManager.getService().showBootMessage(
8798                                    mContext.getResources().getString(
8799                                            R.string.android_upgrading_fstrim), true);
8800                        } catch (RemoteException e) {
8801                        }
8802                    }
8803                    sm.runMaintenance();
8804                }
8805            } else {
8806                Slog.e(TAG, "storageManager service unavailable!");
8807            }
8808        } catch (RemoteException e) {
8809            // Can't happen; StorageManagerService is local
8810        }
8811    }
8812
8813    @Override
8814    public void updatePackagesIfNeeded() {
8815        enforceSystemOrRoot("Only the system can request package update");
8816
8817        // We need to re-extract after an OTA.
8818        boolean causeUpgrade = isUpgrade();
8819
8820        // First boot or factory reset.
8821        // Note: we also handle devices that are upgrading to N right now as if it is their
8822        //       first boot, as they do not have profile data.
8823        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8824
8825        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8826        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8827
8828        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8829            return;
8830        }
8831
8832        List<PackageParser.Package> pkgs;
8833        synchronized (mPackages) {
8834            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8835        }
8836
8837        final long startTime = System.nanoTime();
8838        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8839                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8840                    false /* bootComplete */);
8841
8842        final int elapsedTimeSeconds =
8843                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8844
8845        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8846        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8847        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8848        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8849        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8850    }
8851
8852    /*
8853     * Return the prebuilt profile path given a package base code path.
8854     */
8855    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8856        return pkg.baseCodePath + ".prof";
8857    }
8858
8859    /**
8860     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8861     * containing statistics about the invocation. The array consists of three elements,
8862     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8863     * and {@code numberOfPackagesFailed}.
8864     */
8865    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8866            final String compilerFilter, boolean bootComplete) {
8867
8868        int numberOfPackagesVisited = 0;
8869        int numberOfPackagesOptimized = 0;
8870        int numberOfPackagesSkipped = 0;
8871        int numberOfPackagesFailed = 0;
8872        final int numberOfPackagesToDexopt = pkgs.size();
8873
8874        for (PackageParser.Package pkg : pkgs) {
8875            numberOfPackagesVisited++;
8876
8877            boolean useProfileForDexopt = false;
8878
8879            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8880                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8881                // that are already compiled.
8882                File profileFile = new File(getPrebuildProfilePath(pkg));
8883                // Copy profile if it exists.
8884                if (profileFile.exists()) {
8885                    try {
8886                        // We could also do this lazily before calling dexopt in
8887                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8888                        // is that we don't have a good way to say "do this only once".
8889                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8890                                pkg.applicationInfo.uid, pkg.packageName,
8891                                ArtManager.getProfileName(null))) {
8892                            Log.e(TAG, "Installer failed to copy system profile!");
8893                        } else {
8894                            // Disabled as this causes speed-profile compilation during first boot
8895                            // even if things are already compiled.
8896                            // useProfileForDexopt = true;
8897                        }
8898                    } catch (Exception e) {
8899                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8900                                e);
8901                    }
8902                } else {
8903                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8904                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8905                    // minimize the number off apps being speed-profile compiled during first boot.
8906                    // The other paths will not change the filter.
8907                    if (disabledPs != null && disabledPs.pkg.isStub) {
8908                        // The package is the stub one, remove the stub suffix to get the normal
8909                        // package and APK names.
8910                        String systemProfilePath =
8911                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8912                        profileFile = new File(systemProfilePath);
8913                        // If we have a profile for a compressed APK, copy it to the reference
8914                        // location.
8915                        // Note that copying the profile here will cause it to override the
8916                        // reference profile every OTA even though the existing reference profile
8917                        // may have more data. We can't copy during decompression since the
8918                        // directories are not set up at that point.
8919                        if (profileFile.exists()) {
8920                            try {
8921                                // We could also do this lazily before calling dexopt in
8922                                // PackageDexOptimizer to prevent this happening on first boot. The
8923                                // issue is that we don't have a good way to say "do this only
8924                                // once".
8925                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8926                                        pkg.applicationInfo.uid, pkg.packageName,
8927                                        ArtManager.getProfileName(null))) {
8928                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8929                                } else {
8930                                    useProfileForDexopt = true;
8931                                }
8932                            } catch (Exception e) {
8933                                Log.e(TAG, "Failed to copy profile " +
8934                                        profileFile.getAbsolutePath() + " ", e);
8935                            }
8936                        }
8937                    }
8938                }
8939            }
8940
8941            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8942                if (DEBUG_DEXOPT) {
8943                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8944                }
8945                numberOfPackagesSkipped++;
8946                continue;
8947            }
8948
8949            if (DEBUG_DEXOPT) {
8950                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8951                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8952            }
8953
8954            if (showDialog) {
8955                try {
8956                    ActivityManager.getService().showBootMessage(
8957                            mContext.getResources().getString(R.string.android_upgrading_apk,
8958                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8959                } catch (RemoteException e) {
8960                }
8961                synchronized (mPackages) {
8962                    mDexOptDialogShown = true;
8963                }
8964            }
8965
8966            String pkgCompilerFilter = compilerFilter;
8967            if (useProfileForDexopt) {
8968                // Use background dexopt mode to try and use the profile. Note that this does not
8969                // guarantee usage of the profile.
8970                pkgCompilerFilter =
8971                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8972                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8973            }
8974
8975            // checkProfiles is false to avoid merging profiles during boot which
8976            // might interfere with background compilation (b/28612421).
8977            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8978            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8979            // trade-off worth doing to save boot time work.
8980            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8981            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8982                    pkg.packageName,
8983                    pkgCompilerFilter,
8984                    dexoptFlags));
8985
8986            switch (primaryDexOptStaus) {
8987                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8988                    numberOfPackagesOptimized++;
8989                    break;
8990                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8991                    numberOfPackagesSkipped++;
8992                    break;
8993                case PackageDexOptimizer.DEX_OPT_FAILED:
8994                    numberOfPackagesFailed++;
8995                    break;
8996                default:
8997                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8998                    break;
8999            }
9000        }
9001
9002        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9003                numberOfPackagesFailed };
9004    }
9005
9006    @Override
9007    public void notifyPackageUse(String packageName, int reason) {
9008        synchronized (mPackages) {
9009            final int callingUid = Binder.getCallingUid();
9010            final int callingUserId = UserHandle.getUserId(callingUid);
9011            if (getInstantAppPackageName(callingUid) != null) {
9012                if (!isCallerSameApp(packageName, callingUid)) {
9013                    return;
9014                }
9015            } else {
9016                if (isInstantApp(packageName, callingUserId)) {
9017                    return;
9018                }
9019            }
9020            notifyPackageUseLocked(packageName, reason);
9021        }
9022    }
9023
9024    @GuardedBy("mPackages")
9025    private void notifyPackageUseLocked(String packageName, int reason) {
9026        final PackageParser.Package p = mPackages.get(packageName);
9027        if (p == null) {
9028            return;
9029        }
9030        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9031    }
9032
9033    @Override
9034    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9035            List<String> classPaths, String loaderIsa) {
9036        int userId = UserHandle.getCallingUserId();
9037        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9038        if (ai == null) {
9039            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9040                + loadingPackageName + ", user=" + userId);
9041            return;
9042        }
9043        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9044    }
9045
9046    @Override
9047    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9048            IDexModuleRegisterCallback callback) {
9049        int userId = UserHandle.getCallingUserId();
9050        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9051        DexManager.RegisterDexModuleResult result;
9052        if (ai == null) {
9053            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9054                     " calling user. package=" + packageName + ", user=" + userId);
9055            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9056        } else {
9057            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9058        }
9059
9060        if (callback != null) {
9061            mHandler.post(() -> {
9062                try {
9063                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9064                } catch (RemoteException e) {
9065                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9066                }
9067            });
9068        }
9069    }
9070
9071    /**
9072     * Ask the package manager to perform a dex-opt with the given compiler filter.
9073     *
9074     * Note: exposed only for the shell command to allow moving packages explicitly to a
9075     *       definite state.
9076     */
9077    @Override
9078    public boolean performDexOptMode(String packageName,
9079            boolean checkProfiles, String targetCompilerFilter, boolean force,
9080            boolean bootComplete, String splitName) {
9081        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9082                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9083                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9084        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9085                splitName, flags));
9086    }
9087
9088    /**
9089     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9090     * secondary dex files belonging to the given package.
9091     *
9092     * Note: exposed only for the shell command to allow moving packages explicitly to a
9093     *       definite state.
9094     */
9095    @Override
9096    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9097            boolean force) {
9098        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9099                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9100                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9101                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9102        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9103    }
9104
9105    /*package*/ boolean performDexOpt(DexoptOptions options) {
9106        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9107            return false;
9108        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9109            return false;
9110        }
9111
9112        if (options.isDexoptOnlySecondaryDex()) {
9113            return mDexManager.dexoptSecondaryDex(options);
9114        } else {
9115            int dexoptStatus = performDexOptWithStatus(options);
9116            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9117        }
9118    }
9119
9120    /**
9121     * Perform dexopt on the given package and return one of following result:
9122     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9123     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9124     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9125     */
9126    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9127        return performDexOptTraced(options);
9128    }
9129
9130    private int performDexOptTraced(DexoptOptions options) {
9131        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9132        try {
9133            return performDexOptInternal(options);
9134        } finally {
9135            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9136        }
9137    }
9138
9139    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9140    // if the package can now be considered up to date for the given filter.
9141    private int performDexOptInternal(DexoptOptions options) {
9142        PackageParser.Package p;
9143        synchronized (mPackages) {
9144            p = mPackages.get(options.getPackageName());
9145            if (p == null) {
9146                // Package could not be found. Report failure.
9147                return PackageDexOptimizer.DEX_OPT_FAILED;
9148            }
9149            mPackageUsage.maybeWriteAsync(mPackages);
9150            mCompilerStats.maybeWriteAsync();
9151        }
9152        long callingId = Binder.clearCallingIdentity();
9153        try {
9154            synchronized (mInstallLock) {
9155                return performDexOptInternalWithDependenciesLI(p, options);
9156            }
9157        } finally {
9158            Binder.restoreCallingIdentity(callingId);
9159        }
9160    }
9161
9162    public ArraySet<String> getOptimizablePackages() {
9163        ArraySet<String> pkgs = new ArraySet<String>();
9164        synchronized (mPackages) {
9165            for (PackageParser.Package p : mPackages.values()) {
9166                if (PackageDexOptimizer.canOptimizePackage(p)) {
9167                    pkgs.add(p.packageName);
9168                }
9169            }
9170        }
9171        return pkgs;
9172    }
9173
9174    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9175            DexoptOptions options) {
9176        // Select the dex optimizer based on the force parameter.
9177        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9178        //       allocate an object here.
9179        PackageDexOptimizer pdo = options.isForce()
9180                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9181                : mPackageDexOptimizer;
9182
9183        // Dexopt all dependencies first. Note: we ignore the return value and march on
9184        // on errors.
9185        // Note that we are going to call performDexOpt on those libraries as many times as
9186        // they are referenced in packages. When we do a batch of performDexOpt (for example
9187        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9188        // and the first package that uses the library will dexopt it. The
9189        // others will see that the compiled code for the library is up to date.
9190        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9191        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9192        if (!deps.isEmpty()) {
9193            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9194                    options.getCompilerFilter(), options.getSplitName(),
9195                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9196            for (PackageParser.Package depPackage : deps) {
9197                // TODO: Analyze and investigate if we (should) profile libraries.
9198                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9199                        getOrCreateCompilerPackageStats(depPackage),
9200                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9201            }
9202        }
9203        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9204                getOrCreateCompilerPackageStats(p),
9205                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9206    }
9207
9208    /**
9209     * Reconcile the information we have about the secondary dex files belonging to
9210     * {@code packagName} and the actual dex files. For all dex files that were
9211     * deleted, update the internal records and delete the generated oat files.
9212     */
9213    @Override
9214    public void reconcileSecondaryDexFiles(String packageName) {
9215        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9216            return;
9217        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9218            return;
9219        }
9220        mDexManager.reconcileSecondaryDexFiles(packageName);
9221    }
9222
9223    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9224    // a reference there.
9225    /*package*/ DexManager getDexManager() {
9226        return mDexManager;
9227    }
9228
9229    /**
9230     * Execute the background dexopt job immediately.
9231     */
9232    @Override
9233    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9234        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9235            return false;
9236        }
9237        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9238    }
9239
9240    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9241        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9242                || p.usesStaticLibraries != null) {
9243            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9244            Set<String> collectedNames = new HashSet<>();
9245            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9246
9247            retValue.remove(p);
9248
9249            return retValue;
9250        } else {
9251            return Collections.emptyList();
9252        }
9253    }
9254
9255    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9256            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9257        if (!collectedNames.contains(p.packageName)) {
9258            collectedNames.add(p.packageName);
9259            collected.add(p);
9260
9261            if (p.usesLibraries != null) {
9262                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9263                        null, collected, collectedNames);
9264            }
9265            if (p.usesOptionalLibraries != null) {
9266                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9267                        null, collected, collectedNames);
9268            }
9269            if (p.usesStaticLibraries != null) {
9270                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9271                        p.usesStaticLibrariesVersions, collected, collectedNames);
9272            }
9273        }
9274    }
9275
9276    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9277            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9278        final int libNameCount = libs.size();
9279        for (int i = 0; i < libNameCount; i++) {
9280            String libName = libs.get(i);
9281            long version = (versions != null && versions.length == libNameCount)
9282                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9283            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9284            if (libPkg != null) {
9285                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9286            }
9287        }
9288    }
9289
9290    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9291        synchronized (mPackages) {
9292            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9293            if (libEntry != null) {
9294                return mPackages.get(libEntry.apk);
9295            }
9296            return null;
9297        }
9298    }
9299
9300    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9301        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9302        if (versionedLib == null) {
9303            return null;
9304        }
9305        return versionedLib.get(version);
9306    }
9307
9308    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9309        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9310                pkg.staticSharedLibName);
9311        if (versionedLib == null) {
9312            return null;
9313        }
9314        long previousLibVersion = -1;
9315        final int versionCount = versionedLib.size();
9316        for (int i = 0; i < versionCount; i++) {
9317            final long libVersion = versionedLib.keyAt(i);
9318            if (libVersion < pkg.staticSharedLibVersion) {
9319                previousLibVersion = Math.max(previousLibVersion, libVersion);
9320            }
9321        }
9322        if (previousLibVersion >= 0) {
9323            return versionedLib.get(previousLibVersion);
9324        }
9325        return null;
9326    }
9327
9328    public void shutdown() {
9329        mPackageUsage.writeNow(mPackages);
9330        mCompilerStats.writeNow();
9331        mDexManager.writePackageDexUsageNow();
9332    }
9333
9334    @Override
9335    public void dumpProfiles(String packageName) {
9336        PackageParser.Package pkg;
9337        synchronized (mPackages) {
9338            pkg = mPackages.get(packageName);
9339            if (pkg == null) {
9340                throw new IllegalArgumentException("Unknown package: " + packageName);
9341            }
9342        }
9343        /* Only the shell, root, or the app user should be able to dump profiles. */
9344        int callingUid = Binder.getCallingUid();
9345        if (callingUid != Process.SHELL_UID &&
9346            callingUid != Process.ROOT_UID &&
9347            callingUid != pkg.applicationInfo.uid) {
9348            throw new SecurityException("dumpProfiles");
9349        }
9350
9351        synchronized (mInstallLock) {
9352            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9353            mArtManagerService.dumpProfiles(pkg);
9354            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9355        }
9356    }
9357
9358    @Override
9359    public void forceDexOpt(String packageName) {
9360        enforceSystemOrRoot("forceDexOpt");
9361
9362        PackageParser.Package pkg;
9363        synchronized (mPackages) {
9364            pkg = mPackages.get(packageName);
9365            if (pkg == null) {
9366                throw new IllegalArgumentException("Unknown package: " + packageName);
9367            }
9368        }
9369
9370        synchronized (mInstallLock) {
9371            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9372
9373            // Whoever is calling forceDexOpt wants a compiled package.
9374            // Don't use profiles since that may cause compilation to be skipped.
9375            final int res = performDexOptInternalWithDependenciesLI(
9376                    pkg,
9377                    new DexoptOptions(packageName,
9378                            getDefaultCompilerFilter(),
9379                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9380
9381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9382            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9383                throw new IllegalStateException("Failed to dexopt: " + res);
9384            }
9385        }
9386    }
9387
9388    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9389        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9390            Slog.w(TAG, "Unable to update from " + oldPkg.name
9391                    + " to " + newPkg.packageName
9392                    + ": old package not in system partition");
9393            return false;
9394        } else if (mPackages.get(oldPkg.name) != null) {
9395            Slog.w(TAG, "Unable to update from " + oldPkg.name
9396                    + " to " + newPkg.packageName
9397                    + ": old package still exists");
9398            return false;
9399        }
9400        return true;
9401    }
9402
9403    void removeCodePathLI(File codePath) {
9404        if (codePath.isDirectory()) {
9405            try {
9406                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9407            } catch (InstallerException e) {
9408                Slog.w(TAG, "Failed to remove code path", e);
9409            }
9410        } else {
9411            codePath.delete();
9412        }
9413    }
9414
9415    private int[] resolveUserIds(int userId) {
9416        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9417    }
9418
9419    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9420        if (pkg == null) {
9421            Slog.wtf(TAG, "Package was null!", new Throwable());
9422            return;
9423        }
9424        clearAppDataLeafLIF(pkg, userId, flags);
9425        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9426        for (int i = 0; i < childCount; i++) {
9427            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9428        }
9429
9430        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9431    }
9432
9433    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9434        final PackageSetting ps;
9435        synchronized (mPackages) {
9436            ps = mSettings.mPackages.get(pkg.packageName);
9437        }
9438        for (int realUserId : resolveUserIds(userId)) {
9439            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9440            try {
9441                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9442                        ceDataInode);
9443            } catch (InstallerException e) {
9444                Slog.w(TAG, String.valueOf(e));
9445            }
9446        }
9447    }
9448
9449    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9450        if (pkg == null) {
9451            Slog.wtf(TAG, "Package was null!", new Throwable());
9452            return;
9453        }
9454        destroyAppDataLeafLIF(pkg, userId, flags);
9455        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9456        for (int i = 0; i < childCount; i++) {
9457            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9458        }
9459    }
9460
9461    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9462        final PackageSetting ps;
9463        synchronized (mPackages) {
9464            ps = mSettings.mPackages.get(pkg.packageName);
9465        }
9466        for (int realUserId : resolveUserIds(userId)) {
9467            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9468            try {
9469                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9470                        ceDataInode);
9471            } catch (InstallerException e) {
9472                Slog.w(TAG, String.valueOf(e));
9473            }
9474            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9475        }
9476    }
9477
9478    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9479        if (pkg == null) {
9480            Slog.wtf(TAG, "Package was null!", new Throwable());
9481            return;
9482        }
9483        destroyAppProfilesLeafLIF(pkg);
9484        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9485        for (int i = 0; i < childCount; i++) {
9486            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9487        }
9488    }
9489
9490    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9491        try {
9492            mInstaller.destroyAppProfiles(pkg.packageName);
9493        } catch (InstallerException e) {
9494            Slog.w(TAG, String.valueOf(e));
9495        }
9496    }
9497
9498    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9499        if (pkg == null) {
9500            Slog.wtf(TAG, "Package was null!", new Throwable());
9501            return;
9502        }
9503        mArtManagerService.clearAppProfiles(pkg);
9504        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9505        for (int i = 0; i < childCount; i++) {
9506            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9507        }
9508    }
9509
9510    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9511            long lastUpdateTime) {
9512        // Set parent install/update time
9513        PackageSetting ps = (PackageSetting) pkg.mExtras;
9514        if (ps != null) {
9515            ps.firstInstallTime = firstInstallTime;
9516            ps.lastUpdateTime = lastUpdateTime;
9517        }
9518        // Set children install/update time
9519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9520        for (int i = 0; i < childCount; i++) {
9521            PackageParser.Package childPkg = pkg.childPackages.get(i);
9522            ps = (PackageSetting) childPkg.mExtras;
9523            if (ps != null) {
9524                ps.firstInstallTime = firstInstallTime;
9525                ps.lastUpdateTime = lastUpdateTime;
9526            }
9527        }
9528    }
9529
9530    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9531            SharedLibraryEntry file,
9532            PackageParser.Package changingLib) {
9533        if (file.path != null) {
9534            usesLibraryFiles.add(file.path);
9535            return;
9536        }
9537        PackageParser.Package p = mPackages.get(file.apk);
9538        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9539            // If we are doing this while in the middle of updating a library apk,
9540            // then we need to make sure to use that new apk for determining the
9541            // dependencies here.  (We haven't yet finished committing the new apk
9542            // to the package manager state.)
9543            if (p == null || p.packageName.equals(changingLib.packageName)) {
9544                p = changingLib;
9545            }
9546        }
9547        if (p != null) {
9548            usesLibraryFiles.addAll(p.getAllCodePaths());
9549            if (p.usesLibraryFiles != null) {
9550                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9551            }
9552        }
9553    }
9554
9555    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9556            PackageParser.Package changingLib) throws PackageManagerException {
9557        if (pkg == null) {
9558            return;
9559        }
9560        // The collection used here must maintain the order of addition (so
9561        // that libraries are searched in the correct order) and must have no
9562        // duplicates.
9563        Set<String> usesLibraryFiles = null;
9564        if (pkg.usesLibraries != null) {
9565            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9566                    null, null, pkg.packageName, changingLib, true,
9567                    pkg.applicationInfo.targetSdkVersion, null);
9568        }
9569        if (pkg.usesStaticLibraries != null) {
9570            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9571                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9572                    pkg.packageName, changingLib, true,
9573                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9574        }
9575        if (pkg.usesOptionalLibraries != null) {
9576            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9577                    null, null, pkg.packageName, changingLib, false,
9578                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9579        }
9580        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9581            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9582        } else {
9583            pkg.usesLibraryFiles = null;
9584        }
9585    }
9586
9587    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9588            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9589            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9590            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9591            throws PackageManagerException {
9592        final int libCount = requestedLibraries.size();
9593        for (int i = 0; i < libCount; i++) {
9594            final String libName = requestedLibraries.get(i);
9595            final long libVersion = requiredVersions != null ? requiredVersions[i]
9596                    : SharedLibraryInfo.VERSION_UNDEFINED;
9597            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9598            if (libEntry == null) {
9599                if (required) {
9600                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9601                            "Package " + packageName + " requires unavailable shared library "
9602                                    + libName + "; failing!");
9603                } else if (DEBUG_SHARED_LIBRARIES) {
9604                    Slog.i(TAG, "Package " + packageName
9605                            + " desires unavailable shared library "
9606                            + libName + "; ignoring!");
9607                }
9608            } else {
9609                if (requiredVersions != null && requiredCertDigests != null) {
9610                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9611                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9612                            "Package " + packageName + " requires unavailable static shared"
9613                                    + " library " + libName + " version "
9614                                    + libEntry.info.getLongVersion() + "; failing!");
9615                    }
9616
9617                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9618                    if (libPkg == null) {
9619                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9620                                "Package " + packageName + " requires unavailable static shared"
9621                                        + " library; failing!");
9622                    }
9623
9624                    final String[] expectedCertDigests = requiredCertDigests[i];
9625
9626
9627                    if (expectedCertDigests.length > 1) {
9628
9629                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9630                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9631                                ? PackageUtils.computeSignaturesSha256Digests(
9632                                libPkg.mSigningDetails.signatures)
9633                                : PackageUtils.computeSignaturesSha256Digests(
9634                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9635
9636                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9637                        // target O we don't parse the "additional-certificate" tags similarly
9638                        // how we only consider all certs only for apps targeting O (see above).
9639                        // Therefore, the size check is safe to make.
9640                        if (expectedCertDigests.length != libCertDigests.length) {
9641                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9642                                    "Package " + packageName + " requires differently signed" +
9643                                            " static shared library; failing!");
9644                        }
9645
9646                        // Use a predictable order as signature order may vary
9647                        Arrays.sort(libCertDigests);
9648                        Arrays.sort(expectedCertDigests);
9649
9650                        final int certCount = libCertDigests.length;
9651                        for (int j = 0; j < certCount; j++) {
9652                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9653                                throw new PackageManagerException(
9654                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9655                                        "Package " + packageName + " requires differently signed" +
9656                                                " static shared library; failing!");
9657                            }
9658                        }
9659                    } else {
9660
9661                        // lib signing cert could have rotated beyond the one expected, check to see
9662                        // if the new one has been blessed by the old
9663                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9664                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9665                            throw new PackageManagerException(
9666                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9667                                    "Package " + packageName + " requires differently signed" +
9668                                            " static shared library; failing!");
9669                        }
9670                    }
9671                }
9672
9673                if (outUsedLibraries == null) {
9674                    // Use LinkedHashSet to preserve the order of files added to
9675                    // usesLibraryFiles while eliminating duplicates.
9676                    outUsedLibraries = new LinkedHashSet<>();
9677                }
9678                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9679            }
9680        }
9681        return outUsedLibraries;
9682    }
9683
9684    private static boolean hasString(List<String> list, List<String> which) {
9685        if (list == null) {
9686            return false;
9687        }
9688        for (int i=list.size()-1; i>=0; i--) {
9689            for (int j=which.size()-1; j>=0; j--) {
9690                if (which.get(j).equals(list.get(i))) {
9691                    return true;
9692                }
9693            }
9694        }
9695        return false;
9696    }
9697
9698    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9699            PackageParser.Package changingPkg) {
9700        ArrayList<PackageParser.Package> res = null;
9701        for (PackageParser.Package pkg : mPackages.values()) {
9702            if (changingPkg != null
9703                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9704                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9705                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9706                            changingPkg.staticSharedLibName)) {
9707                return null;
9708            }
9709            if (res == null) {
9710                res = new ArrayList<>();
9711            }
9712            res.add(pkg);
9713            try {
9714                updateSharedLibrariesLPr(pkg, changingPkg);
9715            } catch (PackageManagerException e) {
9716                // If a system app update or an app and a required lib missing we
9717                // delete the package and for updated system apps keep the data as
9718                // it is better for the user to reinstall than to be in an limbo
9719                // state. Also libs disappearing under an app should never happen
9720                // - just in case.
9721                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9722                    final int flags = pkg.isUpdatedSystemApp()
9723                            ? PackageManager.DELETE_KEEP_DATA : 0;
9724                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9725                            flags , null, true, null);
9726                }
9727                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9728            }
9729        }
9730        return res;
9731    }
9732
9733    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9734            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9735            @Nullable UserHandle user) throws PackageManagerException {
9736        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9737        // If the package has children and this is the first dive in the function
9738        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9739        // whether all packages (parent and children) would be successfully scanned
9740        // before the actual scan since scanning mutates internal state and we want
9741        // to atomically install the package and its children.
9742        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9743            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9744                scanFlags |= SCAN_CHECK_ONLY;
9745            }
9746        } else {
9747            scanFlags &= ~SCAN_CHECK_ONLY;
9748        }
9749
9750        final PackageParser.Package scannedPkg;
9751        try {
9752            // Scan the parent
9753            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9754            // Scan the children
9755            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9756            for (int i = 0; i < childCount; i++) {
9757                PackageParser.Package childPkg = pkg.childPackages.get(i);
9758                scanPackageNewLI(childPkg, parseFlags,
9759                        scanFlags, currentTime, user);
9760            }
9761        } finally {
9762            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9763        }
9764
9765        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9766            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9767        }
9768
9769        return scannedPkg;
9770    }
9771
9772    /** The result of a package scan. */
9773    private static class ScanResult {
9774        /** Whether or not the package scan was successful */
9775        public final boolean success;
9776        /**
9777         * The final package settings. This may be the same object passed in
9778         * the {@link ScanRequest}, but, with modified values.
9779         */
9780        @Nullable public final PackageSetting pkgSetting;
9781        /** ABI code paths that have changed in the package scan */
9782        @Nullable public final List<String> changedAbiCodePath;
9783        public ScanResult(
9784                boolean success,
9785                @Nullable PackageSetting pkgSetting,
9786                @Nullable List<String> changedAbiCodePath) {
9787            this.success = success;
9788            this.pkgSetting = pkgSetting;
9789            this.changedAbiCodePath = changedAbiCodePath;
9790        }
9791    }
9792
9793    /** A package to be scanned */
9794    private static class ScanRequest {
9795        /** The parsed package */
9796        @NonNull public final PackageParser.Package pkg;
9797        /** Shared user settings, if the package has a shared user */
9798        @Nullable public final SharedUserSetting sharedUserSetting;
9799        /**
9800         * Package settings of the currently installed version.
9801         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9802         * during scan.
9803         */
9804        @Nullable public final PackageSetting pkgSetting;
9805        /** A copy of the settings for the currently installed version */
9806        @Nullable public final PackageSetting oldPkgSetting;
9807        /** Package settings for the disabled version on the /system partition */
9808        @Nullable public final PackageSetting disabledPkgSetting;
9809        /** Package settings for the installed version under its original package name */
9810        @Nullable public final PackageSetting originalPkgSetting;
9811        /** The real package name of a renamed application */
9812        @Nullable public final String realPkgName;
9813        public final @ParseFlags int parseFlags;
9814        public final @ScanFlags int scanFlags;
9815        /** The user for which the package is being scanned */
9816        @Nullable public final UserHandle user;
9817        /** Whether or not the platform package is being scanned */
9818        public final boolean isPlatformPackage;
9819        public ScanRequest(
9820                @NonNull PackageParser.Package pkg,
9821                @Nullable SharedUserSetting sharedUserSetting,
9822                @Nullable PackageSetting pkgSetting,
9823                @Nullable PackageSetting disabledPkgSetting,
9824                @Nullable PackageSetting originalPkgSetting,
9825                @Nullable String realPkgName,
9826                @ParseFlags int parseFlags,
9827                @ScanFlags int scanFlags,
9828                boolean isPlatformPackage,
9829                @Nullable UserHandle user) {
9830            this.pkg = pkg;
9831            this.pkgSetting = pkgSetting;
9832            this.sharedUserSetting = sharedUserSetting;
9833            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9834            this.disabledPkgSetting = disabledPkgSetting;
9835            this.originalPkgSetting = originalPkgSetting;
9836            this.realPkgName = realPkgName;
9837            this.parseFlags = parseFlags;
9838            this.scanFlags = scanFlags;
9839            this.isPlatformPackage = isPlatformPackage;
9840            this.user = user;
9841        }
9842    }
9843
9844    /**
9845     * Returns the actual scan flags depending upon the state of the other settings.
9846     * <p>Updated system applications will not have the following flags set
9847     * by default and need to be adjusted after the fact:
9848     * <ul>
9849     * <li>{@link #SCAN_AS_SYSTEM}</li>
9850     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9851     * <li>{@link #SCAN_AS_OEM}</li>
9852     * <li>{@link #SCAN_AS_VENDOR}</li>
9853     * <li>{@link #SCAN_AS_PRODUCT}</li>
9854     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9855     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9856     * </ul>
9857     */
9858    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9859            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9860            PackageParser.Package pkg) {
9861        if (disabledPkgSetting != null) {
9862            // updated system application, must at least have SCAN_AS_SYSTEM
9863            scanFlags |= SCAN_AS_SYSTEM;
9864            if ((disabledPkgSetting.pkgPrivateFlags
9865                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9866                scanFlags |= SCAN_AS_PRIVILEGED;
9867            }
9868            if ((disabledPkgSetting.pkgPrivateFlags
9869                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9870                scanFlags |= SCAN_AS_OEM;
9871            }
9872            if ((disabledPkgSetting.pkgPrivateFlags
9873                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9874                scanFlags |= SCAN_AS_VENDOR;
9875            }
9876            if ((disabledPkgSetting.pkgPrivateFlags
9877                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9878                scanFlags |= SCAN_AS_PRODUCT;
9879            }
9880        }
9881        if (pkgSetting != null) {
9882            final int userId = ((user == null) ? 0 : user.getIdentifier());
9883            if (pkgSetting.getInstantApp(userId)) {
9884                scanFlags |= SCAN_AS_INSTANT_APP;
9885            }
9886            if (pkgSetting.getVirtulalPreload(userId)) {
9887                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9888            }
9889        }
9890
9891        // Scan as privileged apps that share a user with a priv-app.
9892        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9893                && (pkg.mSharedUserId != null)) {
9894            SharedUserSetting sharedUserSetting = null;
9895            try {
9896                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9897            } catch (PackageManagerException ignore) {}
9898            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9899                // Exempt SharedUsers signed with the platform key.
9900                // TODO(b/72378145) Fix this exemption. Force signature apps
9901                // to whitelist their privileged permissions just like other
9902                // priv-apps.
9903                synchronized (mPackages) {
9904                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9905                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9906                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9907                        scanFlags |= SCAN_AS_PRIVILEGED;
9908                    }
9909                }
9910            }
9911        }
9912
9913        return scanFlags;
9914    }
9915
9916    @GuardedBy("mInstallLock")
9917    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9918            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9919            @Nullable UserHandle user) throws PackageManagerException {
9920
9921        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9922        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9923        if (realPkgName != null) {
9924            ensurePackageRenamed(pkg, renamedPkgName);
9925        }
9926        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9927        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9928        final PackageSetting disabledPkgSetting =
9929                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9930
9931        if (mTransferedPackages.contains(pkg.packageName)) {
9932            Slog.w(TAG, "Package " + pkg.packageName
9933                    + " was transferred to another, but its .apk remains");
9934        }
9935
9936        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9937        synchronized (mPackages) {
9938            applyPolicy(pkg, parseFlags, scanFlags);
9939            assertPackageIsValid(pkg, parseFlags, scanFlags);
9940
9941            SharedUserSetting sharedUserSetting = null;
9942            if (pkg.mSharedUserId != null) {
9943                // SIDE EFFECTS; may potentially allocate a new shared user
9944                sharedUserSetting = mSettings.getSharedUserLPw(
9945                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9946                if (DEBUG_PACKAGE_SCANNING) {
9947                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9948                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9949                                + " (uid=" + sharedUserSetting.userId + "):"
9950                                + " packages=" + sharedUserSetting.packages);
9951                }
9952            }
9953
9954            boolean scanSucceeded = false;
9955            try {
9956                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9957                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9958                        (pkg == mPlatformPackage), user);
9959                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9960                if (result.success) {
9961                    commitScanResultsLocked(request, result);
9962                }
9963                scanSucceeded = true;
9964            } finally {
9965                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9966                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9967                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9968                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9969                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9970                  }
9971            }
9972        }
9973        return pkg;
9974    }
9975
9976    /**
9977     * Commits the package scan and modifies system state.
9978     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9979     * of committing the package, leaving the system in an inconsistent state.
9980     * This needs to be fixed so, once we get to this point, no errors are
9981     * possible and the system is not left in an inconsistent state.
9982     */
9983    @GuardedBy("mPackages")
9984    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9985            throws PackageManagerException {
9986        final PackageParser.Package pkg = request.pkg;
9987        final @ParseFlags int parseFlags = request.parseFlags;
9988        final @ScanFlags int scanFlags = request.scanFlags;
9989        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9990        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9991        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9992        final UserHandle user = request.user;
9993        final String realPkgName = request.realPkgName;
9994        final PackageSetting pkgSetting = result.pkgSetting;
9995        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9996        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9997
9998        if (newPkgSettingCreated) {
9999            if (originalPkgSetting != null) {
10000                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10001            }
10002            // THROWS: when we can't allocate a user id. add call to check if there's
10003            // enough space to ensure we won't throw; otherwise, don't modify state
10004            mSettings.addUserToSettingLPw(pkgSetting);
10005
10006            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10007                mTransferedPackages.add(originalPkgSetting.name);
10008            }
10009        }
10010        // TODO(toddke): Consider a method specifically for modifying the Package object
10011        // post scan; or, moving this stuff out of the Package object since it has nothing
10012        // to do with the package on disk.
10013        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10014        // for creating the application ID. If we did this earlier, we would be saving the
10015        // correct ID.
10016        pkg.applicationInfo.uid = pkgSetting.appId;
10017
10018        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10019
10020        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10021            mTransferedPackages.add(pkg.packageName);
10022        }
10023
10024        // THROWS: when requested libraries that can't be found. it only changes
10025        // the state of the passed in pkg object, so, move to the top of the method
10026        // and allow it to abort
10027        if ((scanFlags & SCAN_BOOTING) == 0
10028                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10029            // Check all shared libraries and map to their actual file path.
10030            // We only do this here for apps not on a system dir, because those
10031            // are the only ones that can fail an install due to this.  We
10032            // will take care of the system apps by updating all of their
10033            // library paths after the scan is done. Also during the initial
10034            // scan don't update any libs as we do this wholesale after all
10035            // apps are scanned to avoid dependency based scanning.
10036            updateSharedLibrariesLPr(pkg, null);
10037        }
10038
10039        // All versions of a static shared library are referenced with the same
10040        // package name. Internally, we use a synthetic package name to allow
10041        // multiple versions of the same shared library to be installed. So,
10042        // we need to generate the synthetic package name of the latest shared
10043        // library in order to compare signatures.
10044        PackageSetting signatureCheckPs = pkgSetting;
10045        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10046            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10047            if (libraryEntry != null) {
10048                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10049            }
10050        }
10051
10052        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10053        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10054            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10055                // We just determined the app is signed correctly, so bring
10056                // over the latest parsed certs.
10057                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10058            } else {
10059                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10060                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10061                            "Package " + pkg.packageName + " upgrade keys do not match the "
10062                                    + "previously installed version");
10063                } else {
10064                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10065                    String msg = "System package " + pkg.packageName
10066                            + " signature changed; retaining data.";
10067                    reportSettingsProblem(Log.WARN, msg);
10068                }
10069            }
10070        } else {
10071            try {
10072                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10073                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10074                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10075                        pkg.mSigningDetails, compareCompat, compareRecover);
10076                // The new KeySets will be re-added later in the scanning process.
10077                if (compatMatch) {
10078                    synchronized (mPackages) {
10079                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10080                    }
10081                }
10082                // We just determined the app is signed correctly, so bring
10083                // over the latest parsed certs.
10084                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10085
10086
10087                // if this is is a sharedUser, check to see if the new package is signed by a newer
10088                // signing certificate than the existing one, and if so, copy over the new details
10089                if (signatureCheckPs.sharedUser != null
10090                        && pkg.mSigningDetails.hasAncestor(
10091                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10092                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10093                }
10094            } catch (PackageManagerException e) {
10095                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10096                    throw e;
10097                }
10098                // The signature has changed, but this package is in the system
10099                // image...  let's recover!
10100                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10101                // However...  if this package is part of a shared user, but it
10102                // doesn't match the signature of the shared user, let's fail.
10103                // What this means is that you can't change the signatures
10104                // associated with an overall shared user, which doesn't seem all
10105                // that unreasonable.
10106                if (signatureCheckPs.sharedUser != null) {
10107                    if (compareSignatures(
10108                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10109                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10110                        throw new PackageManagerException(
10111                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10112                                "Signature mismatch for shared user: "
10113                                        + pkgSetting.sharedUser);
10114                    }
10115                }
10116                // File a report about this.
10117                String msg = "System package " + pkg.packageName
10118                        + " signature changed; retaining data.";
10119                reportSettingsProblem(Log.WARN, msg);
10120            } catch (IllegalArgumentException e) {
10121
10122                // should never happen: certs matched when checking, but not when comparing
10123                // old to new for sharedUser
10124                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10125                        "Signing certificates comparison made on incomparable signing details"
10126                        + " but somehow passed verifySignatures!");
10127            }
10128        }
10129
10130        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10131            // This package wants to adopt ownership of permissions from
10132            // another package.
10133            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10134                final String origName = pkg.mAdoptPermissions.get(i);
10135                final PackageSetting orig = mSettings.getPackageLPr(origName);
10136                if (orig != null) {
10137                    if (verifyPackageUpdateLPr(orig, pkg)) {
10138                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10139                                + pkg.packageName);
10140                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10141                    }
10142                }
10143            }
10144        }
10145
10146        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10147            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10148                final String codePathString = changedAbiCodePath.get(i);
10149                try {
10150                    mInstaller.rmdex(codePathString,
10151                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10152                } catch (InstallerException ignored) {
10153                }
10154            }
10155        }
10156
10157        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10158            if (oldPkgSetting != null) {
10159                synchronized (mPackages) {
10160                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10161                }
10162            }
10163        } else {
10164            final int userId = user == null ? 0 : user.getIdentifier();
10165            // Modify state for the given package setting
10166            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10167                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10168            if (pkgSetting.getInstantApp(userId)) {
10169                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10170            }
10171        }
10172    }
10173
10174    /**
10175     * Returns the "real" name of the package.
10176     * <p>This may differ from the package's actual name if the application has already
10177     * been installed under one of this package's original names.
10178     */
10179    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10180            @Nullable String renamedPkgName) {
10181        if (isPackageRenamed(pkg, renamedPkgName)) {
10182            return pkg.mRealPackage;
10183        }
10184        return null;
10185    }
10186
10187    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10188    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10189            @Nullable String renamedPkgName) {
10190        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10191    }
10192
10193    /**
10194     * Returns the original package setting.
10195     * <p>A package can migrate its name during an update. In this scenario, a package
10196     * designates a set of names that it considers as one of its original names.
10197     * <p>An original package must be signed identically and it must have the same
10198     * shared user [if any].
10199     */
10200    @GuardedBy("mPackages")
10201    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10202            @Nullable String renamedPkgName) {
10203        if (!isPackageRenamed(pkg, renamedPkgName)) {
10204            return null;
10205        }
10206        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10207            final PackageSetting originalPs =
10208                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10209            if (originalPs != null) {
10210                // the package is already installed under its original name...
10211                // but, should we use it?
10212                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10213                    // the new package is incompatible with the original
10214                    continue;
10215                } else if (originalPs.sharedUser != null) {
10216                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10217                        // the shared user id is incompatible with the original
10218                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10219                                + " to " + pkg.packageName + ": old uid "
10220                                + originalPs.sharedUser.name
10221                                + " differs from " + pkg.mSharedUserId);
10222                        continue;
10223                    }
10224                    // TODO: Add case when shared user id is added [b/28144775]
10225                } else {
10226                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10227                            + pkg.packageName + " to old name " + originalPs.name);
10228                }
10229                return originalPs;
10230            }
10231        }
10232        return null;
10233    }
10234
10235    /**
10236     * Renames the package if it was installed under a different name.
10237     * <p>When we've already installed the package under an original name, update
10238     * the new package so we can continue to have the old name.
10239     */
10240    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10241            @NonNull String renamedPackageName) {
10242        if (pkg.mOriginalPackages == null
10243                || !pkg.mOriginalPackages.contains(renamedPackageName)
10244                || pkg.packageName.equals(renamedPackageName)) {
10245            return;
10246        }
10247        pkg.setPackageName(renamedPackageName);
10248    }
10249
10250    /**
10251     * Just scans the package without any side effects.
10252     * <p>Not entirely true at the moment. There is still one side effect -- this
10253     * method potentially modifies a live {@link PackageSetting} object representing
10254     * the package being scanned. This will be resolved in the future.
10255     *
10256     * @param request Information about the package to be scanned
10257     * @param isUnderFactoryTest Whether or not the device is under factory test
10258     * @param currentTime The current time, in millis
10259     * @return The results of the scan
10260     */
10261    @GuardedBy("mInstallLock")
10262    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10263            boolean isUnderFactoryTest, long currentTime)
10264                    throws PackageManagerException {
10265        final PackageParser.Package pkg = request.pkg;
10266        PackageSetting pkgSetting = request.pkgSetting;
10267        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10268        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10269        final @ParseFlags int parseFlags = request.parseFlags;
10270        final @ScanFlags int scanFlags = request.scanFlags;
10271        final String realPkgName = request.realPkgName;
10272        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10273        final UserHandle user = request.user;
10274        final boolean isPlatformPackage = request.isPlatformPackage;
10275
10276        List<String> changedAbiCodePath = null;
10277
10278        if (DEBUG_PACKAGE_SCANNING) {
10279            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10280                Log.d(TAG, "Scanning package " + pkg.packageName);
10281        }
10282
10283        if (Build.IS_DEBUGGABLE &&
10284                pkg.isPrivileged() &&
10285                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10286            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10287        }
10288
10289        // Initialize package source and resource directories
10290        final File scanFile = new File(pkg.codePath);
10291        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10292        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10293
10294        // We keep references to the derived CPU Abis from settings in oder to reuse
10295        // them in the case where we're not upgrading or booting for the first time.
10296        String primaryCpuAbiFromSettings = null;
10297        String secondaryCpuAbiFromSettings = null;
10298        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10299
10300        if (!needToDeriveAbi) {
10301            if (pkgSetting != null) {
10302                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10303                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10304            } else {
10305                // Re-scanning a system package after uninstalling updates; need to derive ABI
10306                needToDeriveAbi = true;
10307            }
10308        }
10309
10310        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10311            PackageManagerService.reportSettingsProblem(Log.WARN,
10312                    "Package " + pkg.packageName + " shared user changed from "
10313                            + (pkgSetting.sharedUser != null
10314                            ? pkgSetting.sharedUser.name : "<nothing>")
10315                            + " to "
10316                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10317                            + "; replacing with new");
10318            pkgSetting = null;
10319        }
10320
10321        String[] usesStaticLibraries = null;
10322        if (pkg.usesStaticLibraries != null) {
10323            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10324            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10325        }
10326        final boolean createNewPackage = (pkgSetting == null);
10327        if (createNewPackage) {
10328            final String parentPackageName = (pkg.parentPackage != null)
10329                    ? pkg.parentPackage.packageName : null;
10330            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10331            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10332            // REMOVE SharedUserSetting from method; update in a separate call
10333            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10334                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10335                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10336                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10337                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10338                    user, true /*allowInstall*/, instantApp, virtualPreload,
10339                    parentPackageName, pkg.getChildPackageNames(),
10340                    UserManagerService.getInstance(), usesStaticLibraries,
10341                    pkg.usesStaticLibrariesVersions);
10342        } else {
10343            // REMOVE SharedUserSetting from method; update in a separate call.
10344            //
10345            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10346            // secondaryCpuAbi are not known at this point so we always update them
10347            // to null here, only to reset them at a later point.
10348            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10349                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10350                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10351                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10352                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10353                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10354        }
10355        if (createNewPackage && originalPkgSetting != null) {
10356            // This is the initial transition from the original package, so,
10357            // fix up the new package's name now. We must do this after looking
10358            // up the package under its new name, so getPackageLP takes care of
10359            // fiddling things correctly.
10360            pkg.setPackageName(originalPkgSetting.name);
10361
10362            // File a report about this.
10363            String msg = "New package " + pkgSetting.realName
10364                    + " renamed to replace old package " + pkgSetting.name;
10365            reportSettingsProblem(Log.WARN, msg);
10366        }
10367
10368        if (disabledPkgSetting != null) {
10369            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10370        }
10371
10372        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10373        // To ensure that apps with sharedUserId are placed in the same selinux domain
10374        // without breaking any assumptions about access, put them into the least
10375        // restrictive targetSdkVersion=25 domain.
10376        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10377        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10378        final int targetSdk = (sharedUserSetting != null) ? 25
10379                : pkg.applicationInfo.targetSdkVersion;
10380        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10381        // They currently can be if the sharedUser apps are signed with the platform key.
10382        final boolean isPrivileged = (sharedUserSetting != null) ?
10383            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10384
10385        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10386
10387        pkg.mExtras = pkgSetting;
10388        pkg.applicationInfo.processName = fixProcessName(
10389                pkg.applicationInfo.packageName,
10390                pkg.applicationInfo.processName);
10391
10392        if (!isPlatformPackage) {
10393            // Get all of our default paths setup
10394            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10395        }
10396
10397        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10398
10399        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10400            if (needToDeriveAbi) {
10401                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10402                final boolean extractNativeLibs = !pkg.isLibrary();
10403                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10404                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10405
10406                // Some system apps still use directory structure for native libraries
10407                // in which case we might end up not detecting abi solely based on apk
10408                // structure. Try to detect abi based on directory structure.
10409                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10410                        pkg.applicationInfo.primaryCpuAbi == null) {
10411                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10412                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10413                }
10414            } else {
10415                // This is not a first boot or an upgrade, don't bother deriving the
10416                // ABI during the scan. Instead, trust the value that was stored in the
10417                // package setting.
10418                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10419                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10420
10421                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10422
10423                if (DEBUG_ABI_SELECTION) {
10424                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10425                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10426                            pkg.applicationInfo.secondaryCpuAbi);
10427                }
10428            }
10429        } else {
10430            if ((scanFlags & SCAN_MOVE) != 0) {
10431                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10432                // but we already have this packages package info in the PackageSetting. We just
10433                // use that and derive the native library path based on the new codepath.
10434                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10435                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10436            }
10437
10438            // Set native library paths again. For moves, the path will be updated based on the
10439            // ABIs we've determined above. For non-moves, the path will be updated based on the
10440            // ABIs we determined during compilation, but the path will depend on the final
10441            // package path (after the rename away from the stage path).
10442            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10443        }
10444
10445        // This is a special case for the "system" package, where the ABI is
10446        // dictated by the zygote configuration (and init.rc). We should keep track
10447        // of this ABI so that we can deal with "normal" applications that run under
10448        // the same UID correctly.
10449        if (isPlatformPackage) {
10450            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10451                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10452        }
10453
10454        // If there's a mismatch between the abi-override in the package setting
10455        // and the abiOverride specified for the install. Warn about this because we
10456        // would've already compiled the app without taking the package setting into
10457        // account.
10458        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10459            if (cpuAbiOverride == null && pkg.packageName != null) {
10460                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10461                        " for package " + pkg.packageName);
10462            }
10463        }
10464
10465        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10466        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10467        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10468
10469        // Copy the derived override back to the parsed package, so that we can
10470        // update the package settings accordingly.
10471        pkg.cpuAbiOverride = cpuAbiOverride;
10472
10473        if (DEBUG_ABI_SELECTION) {
10474            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10475                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10476                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10477        }
10478
10479        // Push the derived path down into PackageSettings so we know what to
10480        // clean up at uninstall time.
10481        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10482
10483        if (DEBUG_ABI_SELECTION) {
10484            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10485                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10486                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10487        }
10488
10489        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10490            // We don't do this here during boot because we can do it all
10491            // at once after scanning all existing packages.
10492            //
10493            // We also do this *before* we perform dexopt on this package, so that
10494            // we can avoid redundant dexopts, and also to make sure we've got the
10495            // code and package path correct.
10496            changedAbiCodePath =
10497                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10498        }
10499
10500        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10501                android.Manifest.permission.FACTORY_TEST)) {
10502            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10503        }
10504
10505        if (isSystemApp(pkg)) {
10506            pkgSetting.isOrphaned = true;
10507        }
10508
10509        // Take care of first install / last update times.
10510        final long scanFileTime = getLastModifiedTime(pkg);
10511        if (currentTime != 0) {
10512            if (pkgSetting.firstInstallTime == 0) {
10513                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10514            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10515                pkgSetting.lastUpdateTime = currentTime;
10516            }
10517        } else if (pkgSetting.firstInstallTime == 0) {
10518            // We need *something*.  Take time time stamp of the file.
10519            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10520        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10521            if (scanFileTime != pkgSetting.timeStamp) {
10522                // A package on the system image has changed; consider this
10523                // to be an update.
10524                pkgSetting.lastUpdateTime = scanFileTime;
10525            }
10526        }
10527        pkgSetting.setTimeStamp(scanFileTime);
10528
10529        pkgSetting.pkg = pkg;
10530        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10531        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10532            pkgSetting.versionCode = pkg.getLongVersionCode();
10533        }
10534        // Update volume if needed
10535        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10536        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10537            Slog.i(PackageManagerService.TAG,
10538                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10539                    + " package " + pkg.packageName
10540                    + " volume from " + pkgSetting.volumeUuid
10541                    + " to " + volumeUuid);
10542            pkgSetting.volumeUuid = volumeUuid;
10543        }
10544
10545        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10546    }
10547
10548    /**
10549     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10550     */
10551    private static boolean apkHasCode(String fileName) {
10552        StrictJarFile jarFile = null;
10553        try {
10554            jarFile = new StrictJarFile(fileName,
10555                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10556            return jarFile.findEntry("classes.dex") != null;
10557        } catch (IOException ignore) {
10558        } finally {
10559            try {
10560                if (jarFile != null) {
10561                    jarFile.close();
10562                }
10563            } catch (IOException ignore) {}
10564        }
10565        return false;
10566    }
10567
10568    /**
10569     * Enforces code policy for the package. This ensures that if an APK has
10570     * declared hasCode="true" in its manifest that the APK actually contains
10571     * code.
10572     *
10573     * @throws PackageManagerException If bytecode could not be found when it should exist
10574     */
10575    private static void assertCodePolicy(PackageParser.Package pkg)
10576            throws PackageManagerException {
10577        final boolean shouldHaveCode =
10578                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10579        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10580            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10581                    "Package " + pkg.baseCodePath + " code is missing");
10582        }
10583
10584        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10585            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10586                final boolean splitShouldHaveCode =
10587                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10588                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10589                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10590                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10591                }
10592            }
10593        }
10594    }
10595
10596    /**
10597     * Applies policy to the parsed package based upon the given policy flags.
10598     * Ensures the package is in a good state.
10599     * <p>
10600     * Implementation detail: This method must NOT have any side effect. It would
10601     * ideally be static, but, it requires locks to read system state.
10602     */
10603    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10604            final @ScanFlags int scanFlags) {
10605        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10606            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10607            if (pkg.applicationInfo.isDirectBootAware()) {
10608                // we're direct boot aware; set for all components
10609                for (PackageParser.Service s : pkg.services) {
10610                    s.info.encryptionAware = s.info.directBootAware = true;
10611                }
10612                for (PackageParser.Provider p : pkg.providers) {
10613                    p.info.encryptionAware = p.info.directBootAware = true;
10614                }
10615                for (PackageParser.Activity a : pkg.activities) {
10616                    a.info.encryptionAware = a.info.directBootAware = true;
10617                }
10618                for (PackageParser.Activity r : pkg.receivers) {
10619                    r.info.encryptionAware = r.info.directBootAware = true;
10620                }
10621            }
10622            if (compressedFileExists(pkg.codePath)) {
10623                pkg.isStub = true;
10624            }
10625        } else {
10626            // non system apps can't be flagged as core
10627            pkg.coreApp = false;
10628            // clear flags not applicable to regular apps
10629            pkg.applicationInfo.flags &=
10630                    ~ApplicationInfo.FLAG_PERSISTENT;
10631            pkg.applicationInfo.privateFlags &=
10632                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10633            pkg.applicationInfo.privateFlags &=
10634                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10635            // cap permission priorities
10636            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10637                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10638                    pkg.permissionGroups.get(i).info.priority = 0;
10639                }
10640            }
10641        }
10642        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10643            // clear protected broadcasts
10644            pkg.protectedBroadcasts = null;
10645            // ignore export request for single user receivers
10646            if (pkg.receivers != null) {
10647                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10648                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10649                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10650                        receiver.info.exported = false;
10651                    }
10652                }
10653            }
10654            // ignore export request for single user services
10655            if (pkg.services != null) {
10656                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10657                    final PackageParser.Service service = pkg.services.get(i);
10658                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10659                        service.info.exported = false;
10660                    }
10661                }
10662            }
10663            // ignore export request for single user providers
10664            if (pkg.providers != null) {
10665                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10666                    final PackageParser.Provider provider = pkg.providers.get(i);
10667                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10668                        provider.info.exported = false;
10669                    }
10670                }
10671            }
10672        }
10673
10674        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10675            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10676        }
10677
10678        if ((scanFlags & SCAN_AS_OEM) != 0) {
10679            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10680        }
10681
10682        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10683            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10684        }
10685
10686        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10687            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10688        }
10689
10690        if (!isSystemApp(pkg)) {
10691            // Only system apps can use these features.
10692            pkg.mOriginalPackages = null;
10693            pkg.mRealPackage = null;
10694            pkg.mAdoptPermissions = null;
10695        }
10696    }
10697
10698    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10699            throws PackageManagerException {
10700        if (object == null) {
10701            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10702        }
10703        return object;
10704    }
10705
10706    /**
10707     * Asserts the parsed package is valid according to the given policy. If the
10708     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10709     * <p>
10710     * Implementation detail: This method must NOT have any side effects. It would
10711     * ideally be static, but, it requires locks to read system state.
10712     *
10713     * @throws PackageManagerException If the package fails any of the validation checks
10714     */
10715    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10716            final @ScanFlags int scanFlags)
10717                    throws PackageManagerException {
10718        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10719            assertCodePolicy(pkg);
10720        }
10721
10722        if (pkg.applicationInfo.getCodePath() == null ||
10723                pkg.applicationInfo.getResourcePath() == null) {
10724            // Bail out. The resource and code paths haven't been set.
10725            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10726                    "Code and resource paths haven't been set correctly");
10727        }
10728
10729        // Make sure we're not adding any bogus keyset info
10730        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10731        ksms.assertScannedPackageValid(pkg);
10732
10733        synchronized (mPackages) {
10734            // The special "android" package can only be defined once
10735            if (pkg.packageName.equals("android")) {
10736                if (mAndroidApplication != null) {
10737                    Slog.w(TAG, "*************************************************");
10738                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10739                    Slog.w(TAG, " codePath=" + pkg.codePath);
10740                    Slog.w(TAG, "*************************************************");
10741                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10742                            "Core android package being redefined.  Skipping.");
10743                }
10744            }
10745
10746            // A package name must be unique; don't allow duplicates
10747            if (mPackages.containsKey(pkg.packageName)) {
10748                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10749                        "Application package " + pkg.packageName
10750                        + " already installed.  Skipping duplicate.");
10751            }
10752
10753            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10754                // Static libs have a synthetic package name containing the version
10755                // but we still want the base name to be unique.
10756                if (mPackages.containsKey(pkg.manifestPackageName)) {
10757                    throw new PackageManagerException(
10758                            "Duplicate static shared lib provider package");
10759                }
10760
10761                // Static shared libraries should have at least O target SDK
10762                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10763                    throw new PackageManagerException(
10764                            "Packages declaring static-shared libs must target O SDK or higher");
10765                }
10766
10767                // Package declaring static a shared lib cannot be instant apps
10768                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10769                    throw new PackageManagerException(
10770                            "Packages declaring static-shared libs cannot be instant apps");
10771                }
10772
10773                // Package declaring static a shared lib cannot be renamed since the package
10774                // name is synthetic and apps can't code around package manager internals.
10775                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10776                    throw new PackageManagerException(
10777                            "Packages declaring static-shared libs cannot be renamed");
10778                }
10779
10780                // Package declaring static a shared lib cannot declare child packages
10781                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10782                    throw new PackageManagerException(
10783                            "Packages declaring static-shared libs cannot have child packages");
10784                }
10785
10786                // Package declaring static a shared lib cannot declare dynamic libs
10787                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10788                    throw new PackageManagerException(
10789                            "Packages declaring static-shared libs cannot declare dynamic libs");
10790                }
10791
10792                // Package declaring static a shared lib cannot declare shared users
10793                if (pkg.mSharedUserId != null) {
10794                    throw new PackageManagerException(
10795                            "Packages declaring static-shared libs cannot declare shared users");
10796                }
10797
10798                // Static shared libs cannot declare activities
10799                if (!pkg.activities.isEmpty()) {
10800                    throw new PackageManagerException(
10801                            "Static shared libs cannot declare activities");
10802                }
10803
10804                // Static shared libs cannot declare services
10805                if (!pkg.services.isEmpty()) {
10806                    throw new PackageManagerException(
10807                            "Static shared libs cannot declare services");
10808                }
10809
10810                // Static shared libs cannot declare providers
10811                if (!pkg.providers.isEmpty()) {
10812                    throw new PackageManagerException(
10813                            "Static shared libs cannot declare content providers");
10814                }
10815
10816                // Static shared libs cannot declare receivers
10817                if (!pkg.receivers.isEmpty()) {
10818                    throw new PackageManagerException(
10819                            "Static shared libs cannot declare broadcast receivers");
10820                }
10821
10822                // Static shared libs cannot declare permission groups
10823                if (!pkg.permissionGroups.isEmpty()) {
10824                    throw new PackageManagerException(
10825                            "Static shared libs cannot declare permission groups");
10826                }
10827
10828                // Static shared libs cannot declare permissions
10829                if (!pkg.permissions.isEmpty()) {
10830                    throw new PackageManagerException(
10831                            "Static shared libs cannot declare permissions");
10832                }
10833
10834                // Static shared libs cannot declare protected broadcasts
10835                if (pkg.protectedBroadcasts != null) {
10836                    throw new PackageManagerException(
10837                            "Static shared libs cannot declare protected broadcasts");
10838                }
10839
10840                // Static shared libs cannot be overlay targets
10841                if (pkg.mOverlayTarget != null) {
10842                    throw new PackageManagerException(
10843                            "Static shared libs cannot be overlay targets");
10844                }
10845
10846                // The version codes must be ordered as lib versions
10847                long minVersionCode = Long.MIN_VALUE;
10848                long maxVersionCode = Long.MAX_VALUE;
10849
10850                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10851                        pkg.staticSharedLibName);
10852                if (versionedLib != null) {
10853                    final int versionCount = versionedLib.size();
10854                    for (int i = 0; i < versionCount; i++) {
10855                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10856                        final long libVersionCode = libInfo.getDeclaringPackage()
10857                                .getLongVersionCode();
10858                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10859                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10860                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10861                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10862                        } else {
10863                            minVersionCode = maxVersionCode = libVersionCode;
10864                            break;
10865                        }
10866                    }
10867                }
10868                if (pkg.getLongVersionCode() < minVersionCode
10869                        || pkg.getLongVersionCode() > maxVersionCode) {
10870                    throw new PackageManagerException("Static shared"
10871                            + " lib version codes must be ordered as lib versions");
10872                }
10873            }
10874
10875            // Only privileged apps and updated privileged apps can add child packages.
10876            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10877                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10878                    throw new PackageManagerException("Only privileged apps can add child "
10879                            + "packages. Ignoring package " + pkg.packageName);
10880                }
10881                final int childCount = pkg.childPackages.size();
10882                for (int i = 0; i < childCount; i++) {
10883                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10884                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10885                            childPkg.packageName)) {
10886                        throw new PackageManagerException("Can't override child of "
10887                                + "another disabled app. Ignoring package " + pkg.packageName);
10888                    }
10889                }
10890            }
10891
10892            // If we're only installing presumed-existing packages, require that the
10893            // scanned APK is both already known and at the path previously established
10894            // for it.  Previously unknown packages we pick up normally, but if we have an
10895            // a priori expectation about this package's install presence, enforce it.
10896            // With a singular exception for new system packages. When an OTA contains
10897            // a new system package, we allow the codepath to change from a system location
10898            // to the user-installed location. If we don't allow this change, any newer,
10899            // user-installed version of the application will be ignored.
10900            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10901                if (mExpectingBetter.containsKey(pkg.packageName)) {
10902                    logCriticalInfo(Log.WARN,
10903                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10904                } else {
10905                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10906                    if (known != null) {
10907                        if (DEBUG_PACKAGE_SCANNING) {
10908                            Log.d(TAG, "Examining " + pkg.codePath
10909                                    + " and requiring known paths " + known.codePathString
10910                                    + " & " + known.resourcePathString);
10911                        }
10912                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10913                                || !pkg.applicationInfo.getResourcePath().equals(
10914                                        known.resourcePathString)) {
10915                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10916                                    "Application package " + pkg.packageName
10917                                    + " found at " + pkg.applicationInfo.getCodePath()
10918                                    + " but expected at " + known.codePathString
10919                                    + "; ignoring.");
10920                        }
10921                    } else {
10922                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10923                                "Application package " + pkg.packageName
10924                                + " not found; ignoring.");
10925                    }
10926                }
10927            }
10928
10929            // Verify that this new package doesn't have any content providers
10930            // that conflict with existing packages.  Only do this if the
10931            // package isn't already installed, since we don't want to break
10932            // things that are installed.
10933            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10934                final int N = pkg.providers.size();
10935                int i;
10936                for (i=0; i<N; i++) {
10937                    PackageParser.Provider p = pkg.providers.get(i);
10938                    if (p.info.authority != null) {
10939                        String names[] = p.info.authority.split(";");
10940                        for (int j = 0; j < names.length; j++) {
10941                            if (mProvidersByAuthority.containsKey(names[j])) {
10942                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10943                                final String otherPackageName =
10944                                        ((other != null && other.getComponentName() != null) ?
10945                                                other.getComponentName().getPackageName() : "?");
10946                                throw new PackageManagerException(
10947                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10948                                        "Can't install because provider name " + names[j]
10949                                                + " (in package " + pkg.applicationInfo.packageName
10950                                                + ") is already used by " + otherPackageName);
10951                            }
10952                        }
10953                    }
10954                }
10955            }
10956
10957            // Verify that packages sharing a user with a privileged app are marked as privileged.
10958            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10959                SharedUserSetting sharedUserSetting = null;
10960                try {
10961                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10962                } catch (PackageManagerException ignore) {}
10963                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10964                    // Exempt SharedUsers signed with the platform key.
10965                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10966                    if ((platformPkgSetting.signatures.mSigningDetails
10967                            != PackageParser.SigningDetails.UNKNOWN)
10968                            && (compareSignatures(
10969                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10970                                    pkg.mSigningDetails.signatures)
10971                                            != PackageManager.SIGNATURE_MATCH)) {
10972                        throw new PackageManagerException("Apps that share a user with a " +
10973                                "privileged app must themselves be marked as privileged. " +
10974                                pkg.packageName + " shares privileged user " +
10975                                pkg.mSharedUserId + ".");
10976                    }
10977                }
10978            }
10979
10980            // Apply policies specific for runtime resource overlays (RROs).
10981            if (pkg.mOverlayTarget != null) {
10982                // System overlays have some restrictions on their use of the 'static' state.
10983                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10984                    // We are scanning a system overlay. This can be the first scan of the
10985                    // system/vendor/oem partition, or an update to the system overlay.
10986                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10987                        // This must be an update to a system overlay.
10988                        final PackageSetting previousPkg = assertNotNull(
10989                                mSettings.getPackageLPr(pkg.packageName),
10990                                "previous package state not present");
10991
10992                        // Static overlays cannot be updated.
10993                        if (previousPkg.pkg.mOverlayIsStatic) {
10994                            throw new PackageManagerException("Overlay " + pkg.packageName +
10995                                    " is static and cannot be upgraded.");
10996                        // Non-static overlays cannot be converted to static overlays.
10997                        } else if (pkg.mOverlayIsStatic) {
10998                            throw new PackageManagerException("Overlay " + pkg.packageName +
10999                                    " cannot be upgraded into a static overlay.");
11000                        }
11001                    }
11002                } else {
11003                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11004                    if (pkg.mOverlayIsStatic) {
11005                        throw new PackageManagerException("Overlay " + pkg.packageName +
11006                                " is static but not pre-installed.");
11007                    }
11008
11009                    // The only case where we allow installation of a non-system overlay is when
11010                    // its signature is signed with the platform certificate.
11011                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11012                    if ((platformPkgSetting.signatures.mSigningDetails
11013                            != PackageParser.SigningDetails.UNKNOWN)
11014                            && (compareSignatures(
11015                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11016                                    pkg.mSigningDetails.signatures)
11017                                            != PackageManager.SIGNATURE_MATCH)) {
11018                        throw new PackageManagerException("Overlay " + pkg.packageName +
11019                                " must be signed with the platform certificate.");
11020                    }
11021                }
11022            }
11023        }
11024    }
11025
11026    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11027            int type, String declaringPackageName, long declaringVersionCode) {
11028        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11029        if (versionedLib == null) {
11030            versionedLib = new LongSparseArray<>();
11031            mSharedLibraries.put(name, versionedLib);
11032            if (type == SharedLibraryInfo.TYPE_STATIC) {
11033                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11034            }
11035        } else if (versionedLib.indexOfKey(version) >= 0) {
11036            return false;
11037        }
11038        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11039                version, type, declaringPackageName, declaringVersionCode);
11040        versionedLib.put(version, libEntry);
11041        return true;
11042    }
11043
11044    private boolean removeSharedLibraryLPw(String name, long version) {
11045        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11046        if (versionedLib == null) {
11047            return false;
11048        }
11049        final int libIdx = versionedLib.indexOfKey(version);
11050        if (libIdx < 0) {
11051            return false;
11052        }
11053        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11054        versionedLib.remove(version);
11055        if (versionedLib.size() <= 0) {
11056            mSharedLibraries.remove(name);
11057            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11058                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11059                        .getPackageName());
11060            }
11061        }
11062        return true;
11063    }
11064
11065    /**
11066     * Adds a scanned package to the system. When this method is finished, the package will
11067     * be available for query, resolution, etc...
11068     */
11069    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11070            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11071        final String pkgName = pkg.packageName;
11072        if (mCustomResolverComponentName != null &&
11073                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11074            setUpCustomResolverActivity(pkg);
11075        }
11076
11077        if (pkg.packageName.equals("android")) {
11078            synchronized (mPackages) {
11079                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11080                    // Set up information for our fall-back user intent resolution activity.
11081                    mPlatformPackage = pkg;
11082                    pkg.mVersionCode = mSdkVersion;
11083                    pkg.mVersionCodeMajor = 0;
11084                    mAndroidApplication = pkg.applicationInfo;
11085                    if (!mResolverReplaced) {
11086                        mResolveActivity.applicationInfo = mAndroidApplication;
11087                        mResolveActivity.name = ResolverActivity.class.getName();
11088                        mResolveActivity.packageName = mAndroidApplication.packageName;
11089                        mResolveActivity.processName = "system:ui";
11090                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11091                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11092                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11093                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11094                        mResolveActivity.exported = true;
11095                        mResolveActivity.enabled = true;
11096                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11097                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11098                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11099                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11100                                | ActivityInfo.CONFIG_ORIENTATION
11101                                | ActivityInfo.CONFIG_KEYBOARD
11102                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11103                        mResolveInfo.activityInfo = mResolveActivity;
11104                        mResolveInfo.priority = 0;
11105                        mResolveInfo.preferredOrder = 0;
11106                        mResolveInfo.match = 0;
11107                        mResolveComponentName = new ComponentName(
11108                                mAndroidApplication.packageName, mResolveActivity.name);
11109                    }
11110                }
11111            }
11112        }
11113
11114        ArrayList<PackageParser.Package> clientLibPkgs = null;
11115        // writer
11116        synchronized (mPackages) {
11117            boolean hasStaticSharedLibs = false;
11118
11119            // Any app can add new static shared libraries
11120            if (pkg.staticSharedLibName != null) {
11121                // Static shared libs don't allow renaming as they have synthetic package
11122                // names to allow install of multiple versions, so use name from manifest.
11123                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11124                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11125                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11126                    hasStaticSharedLibs = true;
11127                } else {
11128                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11129                                + pkg.staticSharedLibName + " already exists; skipping");
11130                }
11131                // Static shared libs cannot be updated once installed since they
11132                // use synthetic package name which includes the version code, so
11133                // not need to update other packages's shared lib dependencies.
11134            }
11135
11136            if (!hasStaticSharedLibs
11137                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11138                // Only system apps can add new dynamic shared libraries.
11139                if (pkg.libraryNames != null) {
11140                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11141                        String name = pkg.libraryNames.get(i);
11142                        boolean allowed = false;
11143                        if (pkg.isUpdatedSystemApp()) {
11144                            // New library entries can only be added through the
11145                            // system image.  This is important to get rid of a lot
11146                            // of nasty edge cases: for example if we allowed a non-
11147                            // system update of the app to add a library, then uninstalling
11148                            // the update would make the library go away, and assumptions
11149                            // we made such as through app install filtering would now
11150                            // have allowed apps on the device which aren't compatible
11151                            // with it.  Better to just have the restriction here, be
11152                            // conservative, and create many fewer cases that can negatively
11153                            // impact the user experience.
11154                            final PackageSetting sysPs = mSettings
11155                                    .getDisabledSystemPkgLPr(pkg.packageName);
11156                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11157                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11158                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11159                                        allowed = true;
11160                                        break;
11161                                    }
11162                                }
11163                            }
11164                        } else {
11165                            allowed = true;
11166                        }
11167                        if (allowed) {
11168                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11169                                    SharedLibraryInfo.VERSION_UNDEFINED,
11170                                    SharedLibraryInfo.TYPE_DYNAMIC,
11171                                    pkg.packageName, pkg.getLongVersionCode())) {
11172                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11173                                        + name + " already exists; skipping");
11174                            }
11175                        } else {
11176                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11177                                    + name + " that is not declared on system image; skipping");
11178                        }
11179                    }
11180
11181                    if ((scanFlags & SCAN_BOOTING) == 0) {
11182                        // If we are not booting, we need to update any applications
11183                        // that are clients of our shared library.  If we are booting,
11184                        // this will all be done once the scan is complete.
11185                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11186                    }
11187                }
11188            }
11189        }
11190
11191        if ((scanFlags & SCAN_BOOTING) != 0) {
11192            // No apps can run during boot scan, so they don't need to be frozen
11193        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11194            // Caller asked to not kill app, so it's probably not frozen
11195        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11196            // Caller asked us to ignore frozen check for some reason; they
11197            // probably didn't know the package name
11198        } else {
11199            // We're doing major surgery on this package, so it better be frozen
11200            // right now to keep it from launching
11201            checkPackageFrozen(pkgName);
11202        }
11203
11204        // Also need to kill any apps that are dependent on the library.
11205        if (clientLibPkgs != null) {
11206            for (int i=0; i<clientLibPkgs.size(); i++) {
11207                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11208                killApplication(clientPkg.applicationInfo.packageName,
11209                        clientPkg.applicationInfo.uid, "update lib");
11210            }
11211        }
11212
11213        // writer
11214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11215
11216        synchronized (mPackages) {
11217            // We don't expect installation to fail beyond this point
11218
11219            // Add the new setting to mSettings
11220            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11221            // Add the new setting to mPackages
11222            mPackages.put(pkg.applicationInfo.packageName, pkg);
11223            // Make sure we don't accidentally delete its data.
11224            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11225            while (iter.hasNext()) {
11226                PackageCleanItem item = iter.next();
11227                if (pkgName.equals(item.packageName)) {
11228                    iter.remove();
11229                }
11230            }
11231
11232            // Add the package's KeySets to the global KeySetManagerService
11233            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11234            ksms.addScannedPackageLPw(pkg);
11235
11236            int N = pkg.providers.size();
11237            StringBuilder r = null;
11238            int i;
11239            for (i=0; i<N; i++) {
11240                PackageParser.Provider p = pkg.providers.get(i);
11241                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11242                        p.info.processName);
11243                mProviders.addProvider(p);
11244                p.syncable = p.info.isSyncable;
11245                if (p.info.authority != null) {
11246                    String names[] = p.info.authority.split(";");
11247                    p.info.authority = null;
11248                    for (int j = 0; j < names.length; j++) {
11249                        if (j == 1 && p.syncable) {
11250                            // We only want the first authority for a provider to possibly be
11251                            // syncable, so if we already added this provider using a different
11252                            // authority clear the syncable flag. We copy the provider before
11253                            // changing it because the mProviders object contains a reference
11254                            // to a provider that we don't want to change.
11255                            // Only do this for the second authority since the resulting provider
11256                            // object can be the same for all future authorities for this provider.
11257                            p = new PackageParser.Provider(p);
11258                            p.syncable = false;
11259                        }
11260                        if (!mProvidersByAuthority.containsKey(names[j])) {
11261                            mProvidersByAuthority.put(names[j], p);
11262                            if (p.info.authority == null) {
11263                                p.info.authority = names[j];
11264                            } else {
11265                                p.info.authority = p.info.authority + ";" + names[j];
11266                            }
11267                            if (DEBUG_PACKAGE_SCANNING) {
11268                                if (chatty)
11269                                    Log.d(TAG, "Registered content provider: " + names[j]
11270                                            + ", className = " + p.info.name + ", isSyncable = "
11271                                            + p.info.isSyncable);
11272                            }
11273                        } else {
11274                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11275                            Slog.w(TAG, "Skipping provider name " + names[j] +
11276                                    " (in package " + pkg.applicationInfo.packageName +
11277                                    "): name already used by "
11278                                    + ((other != null && other.getComponentName() != null)
11279                                            ? other.getComponentName().getPackageName() : "?"));
11280                        }
11281                    }
11282                }
11283                if (chatty) {
11284                    if (r == null) {
11285                        r = new StringBuilder(256);
11286                    } else {
11287                        r.append(' ');
11288                    }
11289                    r.append(p.info.name);
11290                }
11291            }
11292            if (r != null) {
11293                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11294            }
11295
11296            N = pkg.services.size();
11297            r = null;
11298            for (i=0; i<N; i++) {
11299                PackageParser.Service s = pkg.services.get(i);
11300                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11301                        s.info.processName);
11302                mServices.addService(s);
11303                if (chatty) {
11304                    if (r == null) {
11305                        r = new StringBuilder(256);
11306                    } else {
11307                        r.append(' ');
11308                    }
11309                    r.append(s.info.name);
11310                }
11311            }
11312            if (r != null) {
11313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11314            }
11315
11316            N = pkg.receivers.size();
11317            r = null;
11318            for (i=0; i<N; i++) {
11319                PackageParser.Activity a = pkg.receivers.get(i);
11320                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11321                        a.info.processName);
11322                mReceivers.addActivity(a, "receiver");
11323                if (chatty) {
11324                    if (r == null) {
11325                        r = new StringBuilder(256);
11326                    } else {
11327                        r.append(' ');
11328                    }
11329                    r.append(a.info.name);
11330                }
11331            }
11332            if (r != null) {
11333                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11334            }
11335
11336            N = pkg.activities.size();
11337            r = null;
11338            for (i=0; i<N; i++) {
11339                PackageParser.Activity a = pkg.activities.get(i);
11340                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11341                        a.info.processName);
11342                mActivities.addActivity(a, "activity");
11343                if (chatty) {
11344                    if (r == null) {
11345                        r = new StringBuilder(256);
11346                    } else {
11347                        r.append(' ');
11348                    }
11349                    r.append(a.info.name);
11350                }
11351            }
11352            if (r != null) {
11353                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11354            }
11355
11356            // Don't allow ephemeral applications to define new permissions groups.
11357            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11358                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11359                        + " ignored: instant apps cannot define new permission groups.");
11360            } else {
11361                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11362            }
11363
11364            // Don't allow ephemeral applications to define new permissions.
11365            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11366                Slog.w(TAG, "Permissions from package " + pkg.packageName
11367                        + " ignored: instant apps cannot define new permissions.");
11368            } else {
11369                mPermissionManager.addAllPermissions(pkg, chatty);
11370            }
11371
11372            N = pkg.instrumentation.size();
11373            r = null;
11374            for (i=0; i<N; i++) {
11375                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11376                a.info.packageName = pkg.applicationInfo.packageName;
11377                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11378                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11379                a.info.splitNames = pkg.splitNames;
11380                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11381                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11382                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11383                a.info.dataDir = pkg.applicationInfo.dataDir;
11384                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11385                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11386                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11387                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11388                mInstrumentation.put(a.getComponentName(), a);
11389                if (chatty) {
11390                    if (r == null) {
11391                        r = new StringBuilder(256);
11392                    } else {
11393                        r.append(' ');
11394                    }
11395                    r.append(a.info.name);
11396                }
11397            }
11398            if (r != null) {
11399                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11400            }
11401
11402            if (pkg.protectedBroadcasts != null) {
11403                N = pkg.protectedBroadcasts.size();
11404                synchronized (mProtectedBroadcasts) {
11405                    for (i = 0; i < N; i++) {
11406                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11407                    }
11408                }
11409            }
11410        }
11411
11412        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11413    }
11414
11415    /**
11416     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11417     * is derived purely on the basis of the contents of {@code scanFile} and
11418     * {@code cpuAbiOverride}.
11419     *
11420     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11421     */
11422    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11423            boolean extractLibs)
11424                    throws PackageManagerException {
11425        // Give ourselves some initial paths; we'll come back for another
11426        // pass once we've determined ABI below.
11427        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11428
11429        // We would never need to extract libs for forward-locked and external packages,
11430        // since the container service will do it for us. We shouldn't attempt to
11431        // extract libs from system app when it was not updated.
11432        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11433                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11434            extractLibs = false;
11435        }
11436
11437        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11438        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11439
11440        NativeLibraryHelper.Handle handle = null;
11441        try {
11442            handle = NativeLibraryHelper.Handle.create(pkg);
11443            // TODO(multiArch): This can be null for apps that didn't go through the
11444            // usual installation process. We can calculate it again, like we
11445            // do during install time.
11446            //
11447            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11448            // unnecessary.
11449            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11450
11451            // Null out the abis so that they can be recalculated.
11452            pkg.applicationInfo.primaryCpuAbi = null;
11453            pkg.applicationInfo.secondaryCpuAbi = null;
11454            if (isMultiArch(pkg.applicationInfo)) {
11455                // Warn if we've set an abiOverride for multi-lib packages..
11456                // By definition, we need to copy both 32 and 64 bit libraries for
11457                // such packages.
11458                if (pkg.cpuAbiOverride != null
11459                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11460                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11461                }
11462
11463                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11464                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11465                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11466                    if (extractLibs) {
11467                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11468                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11469                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11470                                useIsaSpecificSubdirs);
11471                    } else {
11472                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11473                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11474                    }
11475                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11476                }
11477
11478                // Shared library native code should be in the APK zip aligned
11479                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11480                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11481                            "Shared library native lib extraction not supported");
11482                }
11483
11484                maybeThrowExceptionForMultiArchCopy(
11485                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11486
11487                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11488                    if (extractLibs) {
11489                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11490                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11491                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11492                                useIsaSpecificSubdirs);
11493                    } else {
11494                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11495                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11496                    }
11497                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11498                }
11499
11500                maybeThrowExceptionForMultiArchCopy(
11501                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11502
11503                if (abi64 >= 0) {
11504                    // Shared library native libs should be in the APK zip aligned
11505                    if (extractLibs && pkg.isLibrary()) {
11506                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11507                                "Shared library native lib extraction not supported");
11508                    }
11509                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11510                }
11511
11512                if (abi32 >= 0) {
11513                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11514                    if (abi64 >= 0) {
11515                        if (pkg.use32bitAbi) {
11516                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11517                            pkg.applicationInfo.primaryCpuAbi = abi;
11518                        } else {
11519                            pkg.applicationInfo.secondaryCpuAbi = abi;
11520                        }
11521                    } else {
11522                        pkg.applicationInfo.primaryCpuAbi = abi;
11523                    }
11524                }
11525            } else {
11526                String[] abiList = (cpuAbiOverride != null) ?
11527                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11528
11529                // Enable gross and lame hacks for apps that are built with old
11530                // SDK tools. We must scan their APKs for renderscript bitcode and
11531                // not launch them if it's present. Don't bother checking on devices
11532                // that don't have 64 bit support.
11533                boolean needsRenderScriptOverride = false;
11534                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11535                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11536                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11537                    needsRenderScriptOverride = true;
11538                }
11539
11540                final int copyRet;
11541                if (extractLibs) {
11542                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11543                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11544                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11545                } else {
11546                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11547                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11548                }
11549                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11550
11551                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11552                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11553                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11554                }
11555
11556                if (copyRet >= 0) {
11557                    // Shared libraries that have native libs must be multi-architecture
11558                    if (pkg.isLibrary()) {
11559                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11560                                "Shared library with native libs must be multiarch");
11561                    }
11562                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11563                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11564                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11565                } else if (needsRenderScriptOverride) {
11566                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11567                }
11568            }
11569        } catch (IOException ioe) {
11570            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11571        } finally {
11572            IoUtils.closeQuietly(handle);
11573        }
11574
11575        // Now that we've calculated the ABIs and determined if it's an internal app,
11576        // we will go ahead and populate the nativeLibraryPath.
11577        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11578    }
11579
11580    /**
11581     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11582     * i.e, so that all packages can be run inside a single process if required.
11583     *
11584     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11585     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11586     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11587     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11588     * updating a package that belongs to a shared user.
11589     *
11590     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11591     * adds unnecessary complexity.
11592     */
11593    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11594            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11595        List<String> changedAbiCodePath = null;
11596        String requiredInstructionSet = null;
11597        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11598            requiredInstructionSet = VMRuntime.getInstructionSet(
11599                     scannedPackage.applicationInfo.primaryCpuAbi);
11600        }
11601
11602        PackageSetting requirer = null;
11603        for (PackageSetting ps : packagesForUser) {
11604            // If packagesForUser contains scannedPackage, we skip it. This will happen
11605            // when scannedPackage is an update of an existing package. Without this check,
11606            // we will never be able to change the ABI of any package belonging to a shared
11607            // user, even if it's compatible with other packages.
11608            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11609                if (ps.primaryCpuAbiString == null) {
11610                    continue;
11611                }
11612
11613                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11614                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11615                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11616                    // this but there's not much we can do.
11617                    String errorMessage = "Instruction set mismatch, "
11618                            + ((requirer == null) ? "[caller]" : requirer)
11619                            + " requires " + requiredInstructionSet + " whereas " + ps
11620                            + " requires " + instructionSet;
11621                    Slog.w(TAG, errorMessage);
11622                }
11623
11624                if (requiredInstructionSet == null) {
11625                    requiredInstructionSet = instructionSet;
11626                    requirer = ps;
11627                }
11628            }
11629        }
11630
11631        if (requiredInstructionSet != null) {
11632            String adjustedAbi;
11633            if (requirer != null) {
11634                // requirer != null implies that either scannedPackage was null or that scannedPackage
11635                // did not require an ABI, in which case we have to adjust scannedPackage to match
11636                // the ABI of the set (which is the same as requirer's ABI)
11637                adjustedAbi = requirer.primaryCpuAbiString;
11638                if (scannedPackage != null) {
11639                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11640                }
11641            } else {
11642                // requirer == null implies that we're updating all ABIs in the set to
11643                // match scannedPackage.
11644                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11645            }
11646
11647            for (PackageSetting ps : packagesForUser) {
11648                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11649                    if (ps.primaryCpuAbiString != null) {
11650                        continue;
11651                    }
11652
11653                    ps.primaryCpuAbiString = adjustedAbi;
11654                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11655                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11656                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11657                        if (DEBUG_ABI_SELECTION) {
11658                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11659                                    + " (requirer="
11660                                    + (requirer != null ? requirer.pkg : "null")
11661                                    + ", scannedPackage="
11662                                    + (scannedPackage != null ? scannedPackage : "null")
11663                                    + ")");
11664                        }
11665                        if (changedAbiCodePath == null) {
11666                            changedAbiCodePath = new ArrayList<>();
11667                        }
11668                        changedAbiCodePath.add(ps.codePathString);
11669                    }
11670                }
11671            }
11672        }
11673        return changedAbiCodePath;
11674    }
11675
11676    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11677        synchronized (mPackages) {
11678            mResolverReplaced = true;
11679            // Set up information for custom user intent resolution activity.
11680            mResolveActivity.applicationInfo = pkg.applicationInfo;
11681            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11682            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11683            mResolveActivity.processName = pkg.applicationInfo.packageName;
11684            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11685            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11686                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11687            mResolveActivity.theme = 0;
11688            mResolveActivity.exported = true;
11689            mResolveActivity.enabled = true;
11690            mResolveInfo.activityInfo = mResolveActivity;
11691            mResolveInfo.priority = 0;
11692            mResolveInfo.preferredOrder = 0;
11693            mResolveInfo.match = 0;
11694            mResolveComponentName = mCustomResolverComponentName;
11695            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11696                    mResolveComponentName);
11697        }
11698    }
11699
11700    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11701        if (installerActivity == null) {
11702            if (DEBUG_INSTANT) {
11703                Slog.d(TAG, "Clear ephemeral installer activity");
11704            }
11705            mInstantAppInstallerActivity = null;
11706            return;
11707        }
11708
11709        if (DEBUG_INSTANT) {
11710            Slog.d(TAG, "Set ephemeral installer activity: "
11711                    + installerActivity.getComponentName());
11712        }
11713        // Set up information for ephemeral installer activity
11714        mInstantAppInstallerActivity = installerActivity;
11715        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11716                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11717        mInstantAppInstallerActivity.exported = true;
11718        mInstantAppInstallerActivity.enabled = true;
11719        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11720        mInstantAppInstallerInfo.priority = 1;
11721        mInstantAppInstallerInfo.preferredOrder = 1;
11722        mInstantAppInstallerInfo.isDefault = true;
11723        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11724                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11725    }
11726
11727    private static String calculateBundledApkRoot(final String codePathString) {
11728        final File codePath = new File(codePathString);
11729        final File codeRoot;
11730        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11731            codeRoot = Environment.getRootDirectory();
11732        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11733            codeRoot = Environment.getOemDirectory();
11734        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11735            codeRoot = Environment.getVendorDirectory();
11736        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11737            codeRoot = Environment.getProductDirectory();
11738        } else {
11739            // Unrecognized code path; take its top real segment as the apk root:
11740            // e.g. /something/app/blah.apk => /something
11741            try {
11742                File f = codePath.getCanonicalFile();
11743                File parent = f.getParentFile();    // non-null because codePath is a file
11744                File tmp;
11745                while ((tmp = parent.getParentFile()) != null) {
11746                    f = parent;
11747                    parent = tmp;
11748                }
11749                codeRoot = f;
11750                Slog.w(TAG, "Unrecognized code path "
11751                        + codePath + " - using " + codeRoot);
11752            } catch (IOException e) {
11753                // Can't canonicalize the code path -- shenanigans?
11754                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11755                return Environment.getRootDirectory().getPath();
11756            }
11757        }
11758        return codeRoot.getPath();
11759    }
11760
11761    /**
11762     * Derive and set the location of native libraries for the given package,
11763     * which varies depending on where and how the package was installed.
11764     */
11765    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11766        final ApplicationInfo info = pkg.applicationInfo;
11767        final String codePath = pkg.codePath;
11768        final File codeFile = new File(codePath);
11769        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11770        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11771
11772        info.nativeLibraryRootDir = null;
11773        info.nativeLibraryRootRequiresIsa = false;
11774        info.nativeLibraryDir = null;
11775        info.secondaryNativeLibraryDir = null;
11776
11777        if (isApkFile(codeFile)) {
11778            // Monolithic install
11779            if (bundledApp) {
11780                // If "/system/lib64/apkname" exists, assume that is the per-package
11781                // native library directory to use; otherwise use "/system/lib/apkname".
11782                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11783                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11784                        getPrimaryInstructionSet(info));
11785
11786                // This is a bundled system app so choose the path based on the ABI.
11787                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11788                // is just the default path.
11789                final String apkName = deriveCodePathName(codePath);
11790                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11791                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11792                        apkName).getAbsolutePath();
11793
11794                if (info.secondaryCpuAbi != null) {
11795                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11796                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11797                            secondaryLibDir, apkName).getAbsolutePath();
11798                }
11799            } else if (asecApp) {
11800                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11801                        .getAbsolutePath();
11802            } else {
11803                final String apkName = deriveCodePathName(codePath);
11804                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11805                        .getAbsolutePath();
11806            }
11807
11808            info.nativeLibraryRootRequiresIsa = false;
11809            info.nativeLibraryDir = info.nativeLibraryRootDir;
11810        } else {
11811            // Cluster install
11812            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11813            info.nativeLibraryRootRequiresIsa = true;
11814
11815            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11816                    getPrimaryInstructionSet(info)).getAbsolutePath();
11817
11818            if (info.secondaryCpuAbi != null) {
11819                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11820                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11821            }
11822        }
11823    }
11824
11825    /**
11826     * Calculate the abis and roots for a bundled app. These can uniquely
11827     * be determined from the contents of the system partition, i.e whether
11828     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11829     * of this information, and instead assume that the system was built
11830     * sensibly.
11831     */
11832    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11833                                           PackageSetting pkgSetting) {
11834        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11835
11836        // If "/system/lib64/apkname" exists, assume that is the per-package
11837        // native library directory to use; otherwise use "/system/lib/apkname".
11838        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11839        setBundledAppAbi(pkg, apkRoot, apkName);
11840        // pkgSetting might be null during rescan following uninstall of updates
11841        // to a bundled app, so accommodate that possibility.  The settings in
11842        // that case will be established later from the parsed package.
11843        //
11844        // If the settings aren't null, sync them up with what we've just derived.
11845        // note that apkRoot isn't stored in the package settings.
11846        if (pkgSetting != null) {
11847            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11848            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11849        }
11850    }
11851
11852    /**
11853     * Deduces the ABI of a bundled app and sets the relevant fields on the
11854     * parsed pkg object.
11855     *
11856     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11857     *        under which system libraries are installed.
11858     * @param apkName the name of the installed package.
11859     */
11860    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11861        final File codeFile = new File(pkg.codePath);
11862
11863        final boolean has64BitLibs;
11864        final boolean has32BitLibs;
11865        if (isApkFile(codeFile)) {
11866            // Monolithic install
11867            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11868            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11869        } else {
11870            // Cluster install
11871            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11872            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11873                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11874                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11875                has64BitLibs = (new File(rootDir, isa)).exists();
11876            } else {
11877                has64BitLibs = false;
11878            }
11879            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11880                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11881                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11882                has32BitLibs = (new File(rootDir, isa)).exists();
11883            } else {
11884                has32BitLibs = false;
11885            }
11886        }
11887
11888        if (has64BitLibs && !has32BitLibs) {
11889            // The package has 64 bit libs, but not 32 bit libs. Its primary
11890            // ABI should be 64 bit. We can safely assume here that the bundled
11891            // native libraries correspond to the most preferred ABI in the list.
11892
11893            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11894            pkg.applicationInfo.secondaryCpuAbi = null;
11895        } else if (has32BitLibs && !has64BitLibs) {
11896            // The package has 32 bit libs but not 64 bit libs. Its primary
11897            // ABI should be 32 bit.
11898
11899            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11900            pkg.applicationInfo.secondaryCpuAbi = null;
11901        } else if (has32BitLibs && has64BitLibs) {
11902            // The application has both 64 and 32 bit bundled libraries. We check
11903            // here that the app declares multiArch support, and warn if it doesn't.
11904            //
11905            // We will be lenient here and record both ABIs. The primary will be the
11906            // ABI that's higher on the list, i.e, a device that's configured to prefer
11907            // 64 bit apps will see a 64 bit primary ABI,
11908
11909            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11910                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11911            }
11912
11913            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11914                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11915                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11916            } else {
11917                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11918                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11919            }
11920        } else {
11921            pkg.applicationInfo.primaryCpuAbi = null;
11922            pkg.applicationInfo.secondaryCpuAbi = null;
11923        }
11924    }
11925
11926    private void killApplication(String pkgName, int appId, String reason) {
11927        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11928    }
11929
11930    private void killApplication(String pkgName, int appId, int userId, String reason) {
11931        // Request the ActivityManager to kill the process(only for existing packages)
11932        // so that we do not end up in a confused state while the user is still using the older
11933        // version of the application while the new one gets installed.
11934        final long token = Binder.clearCallingIdentity();
11935        try {
11936            IActivityManager am = ActivityManager.getService();
11937            if (am != null) {
11938                try {
11939                    am.killApplication(pkgName, appId, userId, reason);
11940                } catch (RemoteException e) {
11941                }
11942            }
11943        } finally {
11944            Binder.restoreCallingIdentity(token);
11945        }
11946    }
11947
11948    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11949        // Remove the parent package setting
11950        PackageSetting ps = (PackageSetting) pkg.mExtras;
11951        if (ps != null) {
11952            removePackageLI(ps, chatty);
11953        }
11954        // Remove the child package setting
11955        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11956        for (int i = 0; i < childCount; i++) {
11957            PackageParser.Package childPkg = pkg.childPackages.get(i);
11958            ps = (PackageSetting) childPkg.mExtras;
11959            if (ps != null) {
11960                removePackageLI(ps, chatty);
11961            }
11962        }
11963    }
11964
11965    void removePackageLI(PackageSetting ps, boolean chatty) {
11966        if (DEBUG_INSTALL) {
11967            if (chatty)
11968                Log.d(TAG, "Removing package " + ps.name);
11969        }
11970
11971        // writer
11972        synchronized (mPackages) {
11973            mPackages.remove(ps.name);
11974            final PackageParser.Package pkg = ps.pkg;
11975            if (pkg != null) {
11976                cleanPackageDataStructuresLILPw(pkg, chatty);
11977            }
11978        }
11979    }
11980
11981    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11982        if (DEBUG_INSTALL) {
11983            if (chatty)
11984                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11985        }
11986
11987        // writer
11988        synchronized (mPackages) {
11989            // Remove the parent package
11990            mPackages.remove(pkg.applicationInfo.packageName);
11991            cleanPackageDataStructuresLILPw(pkg, chatty);
11992
11993            // Remove the child packages
11994            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11995            for (int i = 0; i < childCount; i++) {
11996                PackageParser.Package childPkg = pkg.childPackages.get(i);
11997                mPackages.remove(childPkg.applicationInfo.packageName);
11998                cleanPackageDataStructuresLILPw(childPkg, chatty);
11999            }
12000        }
12001    }
12002
12003    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12004        int N = pkg.providers.size();
12005        StringBuilder r = null;
12006        int i;
12007        for (i=0; i<N; i++) {
12008            PackageParser.Provider p = pkg.providers.get(i);
12009            mProviders.removeProvider(p);
12010            if (p.info.authority == null) {
12011
12012                /* There was another ContentProvider with this authority when
12013                 * this app was installed so this authority is null,
12014                 * Ignore it as we don't have to unregister the provider.
12015                 */
12016                continue;
12017            }
12018            String names[] = p.info.authority.split(";");
12019            for (int j = 0; j < names.length; j++) {
12020                if (mProvidersByAuthority.get(names[j]) == p) {
12021                    mProvidersByAuthority.remove(names[j]);
12022                    if (DEBUG_REMOVE) {
12023                        if (chatty)
12024                            Log.d(TAG, "Unregistered content provider: " + names[j]
12025                                    + ", className = " + p.info.name + ", isSyncable = "
12026                                    + p.info.isSyncable);
12027                    }
12028                }
12029            }
12030            if (DEBUG_REMOVE && chatty) {
12031                if (r == null) {
12032                    r = new StringBuilder(256);
12033                } else {
12034                    r.append(' ');
12035                }
12036                r.append(p.info.name);
12037            }
12038        }
12039        if (r != null) {
12040            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12041        }
12042
12043        N = pkg.services.size();
12044        r = null;
12045        for (i=0; i<N; i++) {
12046            PackageParser.Service s = pkg.services.get(i);
12047            mServices.removeService(s);
12048            if (chatty) {
12049                if (r == null) {
12050                    r = new StringBuilder(256);
12051                } else {
12052                    r.append(' ');
12053                }
12054                r.append(s.info.name);
12055            }
12056        }
12057        if (r != null) {
12058            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12059        }
12060
12061        N = pkg.receivers.size();
12062        r = null;
12063        for (i=0; i<N; i++) {
12064            PackageParser.Activity a = pkg.receivers.get(i);
12065            mReceivers.removeActivity(a, "receiver");
12066            if (DEBUG_REMOVE && chatty) {
12067                if (r == null) {
12068                    r = new StringBuilder(256);
12069                } else {
12070                    r.append(' ');
12071                }
12072                r.append(a.info.name);
12073            }
12074        }
12075        if (r != null) {
12076            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12077        }
12078
12079        N = pkg.activities.size();
12080        r = null;
12081        for (i=0; i<N; i++) {
12082            PackageParser.Activity a = pkg.activities.get(i);
12083            mActivities.removeActivity(a, "activity");
12084            if (DEBUG_REMOVE && chatty) {
12085                if (r == null) {
12086                    r = new StringBuilder(256);
12087                } else {
12088                    r.append(' ');
12089                }
12090                r.append(a.info.name);
12091            }
12092        }
12093        if (r != null) {
12094            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12095        }
12096
12097        mPermissionManager.removeAllPermissions(pkg, chatty);
12098
12099        N = pkg.instrumentation.size();
12100        r = null;
12101        for (i=0; i<N; i++) {
12102            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12103            mInstrumentation.remove(a.getComponentName());
12104            if (DEBUG_REMOVE && chatty) {
12105                if (r == null) {
12106                    r = new StringBuilder(256);
12107                } else {
12108                    r.append(' ');
12109                }
12110                r.append(a.info.name);
12111            }
12112        }
12113        if (r != null) {
12114            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12115        }
12116
12117        r = null;
12118        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12119            // Only system apps can hold shared libraries.
12120            if (pkg.libraryNames != null) {
12121                for (i = 0; i < pkg.libraryNames.size(); i++) {
12122                    String name = pkg.libraryNames.get(i);
12123                    if (removeSharedLibraryLPw(name, 0)) {
12124                        if (DEBUG_REMOVE && chatty) {
12125                            if (r == null) {
12126                                r = new StringBuilder(256);
12127                            } else {
12128                                r.append(' ');
12129                            }
12130                            r.append(name);
12131                        }
12132                    }
12133                }
12134            }
12135        }
12136
12137        r = null;
12138
12139        // Any package can hold static shared libraries.
12140        if (pkg.staticSharedLibName != null) {
12141            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12142                if (DEBUG_REMOVE && chatty) {
12143                    if (r == null) {
12144                        r = new StringBuilder(256);
12145                    } else {
12146                        r.append(' ');
12147                    }
12148                    r.append(pkg.staticSharedLibName);
12149                }
12150            }
12151        }
12152
12153        if (r != null) {
12154            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12155        }
12156    }
12157
12158
12159    final class ActivityIntentResolver
12160            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12161        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12162                boolean defaultOnly, int userId) {
12163            if (!sUserManager.exists(userId)) return null;
12164            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12165            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12166        }
12167
12168        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12169                int userId) {
12170            if (!sUserManager.exists(userId)) return null;
12171            mFlags = flags;
12172            return super.queryIntent(intent, resolvedType,
12173                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12174                    userId);
12175        }
12176
12177        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12178                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12179            if (!sUserManager.exists(userId)) return null;
12180            if (packageActivities == null) {
12181                return null;
12182            }
12183            mFlags = flags;
12184            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12185            final int N = packageActivities.size();
12186            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12187                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12188
12189            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12190            for (int i = 0; i < N; ++i) {
12191                intentFilters = packageActivities.get(i).intents;
12192                if (intentFilters != null && intentFilters.size() > 0) {
12193                    PackageParser.ActivityIntentInfo[] array =
12194                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12195                    intentFilters.toArray(array);
12196                    listCut.add(array);
12197                }
12198            }
12199            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12200        }
12201
12202        /**
12203         * Finds a privileged activity that matches the specified activity names.
12204         */
12205        private PackageParser.Activity findMatchingActivity(
12206                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12207            for (PackageParser.Activity sysActivity : activityList) {
12208                if (sysActivity.info.name.equals(activityInfo.name)) {
12209                    return sysActivity;
12210                }
12211                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12212                    return sysActivity;
12213                }
12214                if (sysActivity.info.targetActivity != null) {
12215                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12216                        return sysActivity;
12217                    }
12218                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12219                        return sysActivity;
12220                    }
12221                }
12222            }
12223            return null;
12224        }
12225
12226        public class IterGenerator<E> {
12227            public Iterator<E> generate(ActivityIntentInfo info) {
12228                return null;
12229            }
12230        }
12231
12232        public class ActionIterGenerator extends IterGenerator<String> {
12233            @Override
12234            public Iterator<String> generate(ActivityIntentInfo info) {
12235                return info.actionsIterator();
12236            }
12237        }
12238
12239        public class CategoriesIterGenerator extends IterGenerator<String> {
12240            @Override
12241            public Iterator<String> generate(ActivityIntentInfo info) {
12242                return info.categoriesIterator();
12243            }
12244        }
12245
12246        public class SchemesIterGenerator extends IterGenerator<String> {
12247            @Override
12248            public Iterator<String> generate(ActivityIntentInfo info) {
12249                return info.schemesIterator();
12250            }
12251        }
12252
12253        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12254            @Override
12255            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12256                return info.authoritiesIterator();
12257            }
12258        }
12259
12260        /**
12261         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12262         * MODIFIED. Do not pass in a list that should not be changed.
12263         */
12264        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12265                IterGenerator<T> generator, Iterator<T> searchIterator) {
12266            // loop through the set of actions; every one must be found in the intent filter
12267            while (searchIterator.hasNext()) {
12268                // we must have at least one filter in the list to consider a match
12269                if (intentList.size() == 0) {
12270                    break;
12271                }
12272
12273                final T searchAction = searchIterator.next();
12274
12275                // loop through the set of intent filters
12276                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12277                while (intentIter.hasNext()) {
12278                    final ActivityIntentInfo intentInfo = intentIter.next();
12279                    boolean selectionFound = false;
12280
12281                    // loop through the intent filter's selection criteria; at least one
12282                    // of them must match the searched criteria
12283                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12284                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12285                        final T intentSelection = intentSelectionIter.next();
12286                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12287                            selectionFound = true;
12288                            break;
12289                        }
12290                    }
12291
12292                    // the selection criteria wasn't found in this filter's set; this filter
12293                    // is not a potential match
12294                    if (!selectionFound) {
12295                        intentIter.remove();
12296                    }
12297                }
12298            }
12299        }
12300
12301        private boolean isProtectedAction(ActivityIntentInfo filter) {
12302            final Iterator<String> actionsIter = filter.actionsIterator();
12303            while (actionsIter != null && actionsIter.hasNext()) {
12304                final String filterAction = actionsIter.next();
12305                if (PROTECTED_ACTIONS.contains(filterAction)) {
12306                    return true;
12307                }
12308            }
12309            return false;
12310        }
12311
12312        /**
12313         * Adjusts the priority of the given intent filter according to policy.
12314         * <p>
12315         * <ul>
12316         * <li>The priority for non privileged applications is capped to '0'</li>
12317         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12318         * <li>The priority for unbundled updates to privileged applications is capped to the
12319         *      priority defined on the system partition</li>
12320         * </ul>
12321         * <p>
12322         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12323         * allowed to obtain any priority on any action.
12324         */
12325        private void adjustPriority(
12326                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12327            // nothing to do; priority is fine as-is
12328            if (intent.getPriority() <= 0) {
12329                return;
12330            }
12331
12332            final ActivityInfo activityInfo = intent.activity.info;
12333            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12334
12335            final boolean privilegedApp =
12336                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12337            if (!privilegedApp) {
12338                // non-privileged applications can never define a priority >0
12339                if (DEBUG_FILTERS) {
12340                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12341                            + " package: " + applicationInfo.packageName
12342                            + " activity: " + intent.activity.className
12343                            + " origPrio: " + intent.getPriority());
12344                }
12345                intent.setPriority(0);
12346                return;
12347            }
12348
12349            if (systemActivities == null) {
12350                // the system package is not disabled; we're parsing the system partition
12351                if (isProtectedAction(intent)) {
12352                    if (mDeferProtectedFilters) {
12353                        // We can't deal with these just yet. No component should ever obtain a
12354                        // >0 priority for a protected actions, with ONE exception -- the setup
12355                        // wizard. The setup wizard, however, cannot be known until we're able to
12356                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12357                        // until all intent filters have been processed. Chicken, meet egg.
12358                        // Let the filter temporarily have a high priority and rectify the
12359                        // priorities after all system packages have been scanned.
12360                        mProtectedFilters.add(intent);
12361                        if (DEBUG_FILTERS) {
12362                            Slog.i(TAG, "Protected action; save for later;"
12363                                    + " package: " + applicationInfo.packageName
12364                                    + " activity: " + intent.activity.className
12365                                    + " origPrio: " + intent.getPriority());
12366                        }
12367                        return;
12368                    } else {
12369                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12370                            Slog.i(TAG, "No setup wizard;"
12371                                + " All protected intents capped to priority 0");
12372                        }
12373                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12374                            if (DEBUG_FILTERS) {
12375                                Slog.i(TAG, "Found setup wizard;"
12376                                    + " allow priority " + intent.getPriority() + ";"
12377                                    + " package: " + intent.activity.info.packageName
12378                                    + " activity: " + intent.activity.className
12379                                    + " priority: " + intent.getPriority());
12380                            }
12381                            // setup wizard gets whatever it wants
12382                            return;
12383                        }
12384                        if (DEBUG_FILTERS) {
12385                            Slog.i(TAG, "Protected action; cap priority to 0;"
12386                                    + " package: " + intent.activity.info.packageName
12387                                    + " activity: " + intent.activity.className
12388                                    + " origPrio: " + intent.getPriority());
12389                        }
12390                        intent.setPriority(0);
12391                        return;
12392                    }
12393                }
12394                // privileged apps on the system image get whatever priority they request
12395                return;
12396            }
12397
12398            // privileged app unbundled update ... try to find the same activity
12399            final PackageParser.Activity foundActivity =
12400                    findMatchingActivity(systemActivities, activityInfo);
12401            if (foundActivity == null) {
12402                // this is a new activity; it cannot obtain >0 priority
12403                if (DEBUG_FILTERS) {
12404                    Slog.i(TAG, "New activity; cap priority to 0;"
12405                            + " package: " + applicationInfo.packageName
12406                            + " activity: " + intent.activity.className
12407                            + " origPrio: " + intent.getPriority());
12408                }
12409                intent.setPriority(0);
12410                return;
12411            }
12412
12413            // found activity, now check for filter equivalence
12414
12415            // a shallow copy is enough; we modify the list, not its contents
12416            final List<ActivityIntentInfo> intentListCopy =
12417                    new ArrayList<>(foundActivity.intents);
12418            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12419
12420            // find matching action subsets
12421            final Iterator<String> actionsIterator = intent.actionsIterator();
12422            if (actionsIterator != null) {
12423                getIntentListSubset(
12424                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12425                if (intentListCopy.size() == 0) {
12426                    // no more intents to match; we're not equivalent
12427                    if (DEBUG_FILTERS) {
12428                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12429                                + " package: " + applicationInfo.packageName
12430                                + " activity: " + intent.activity.className
12431                                + " origPrio: " + intent.getPriority());
12432                    }
12433                    intent.setPriority(0);
12434                    return;
12435                }
12436            }
12437
12438            // find matching category subsets
12439            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12440            if (categoriesIterator != null) {
12441                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12442                        categoriesIterator);
12443                if (intentListCopy.size() == 0) {
12444                    // no more intents to match; we're not equivalent
12445                    if (DEBUG_FILTERS) {
12446                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12447                                + " package: " + applicationInfo.packageName
12448                                + " activity: " + intent.activity.className
12449                                + " origPrio: " + intent.getPriority());
12450                    }
12451                    intent.setPriority(0);
12452                    return;
12453                }
12454            }
12455
12456            // find matching schemes subsets
12457            final Iterator<String> schemesIterator = intent.schemesIterator();
12458            if (schemesIterator != null) {
12459                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12460                        schemesIterator);
12461                if (intentListCopy.size() == 0) {
12462                    // no more intents to match; we're not equivalent
12463                    if (DEBUG_FILTERS) {
12464                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12465                                + " package: " + applicationInfo.packageName
12466                                + " activity: " + intent.activity.className
12467                                + " origPrio: " + intent.getPriority());
12468                    }
12469                    intent.setPriority(0);
12470                    return;
12471                }
12472            }
12473
12474            // find matching authorities subsets
12475            final Iterator<IntentFilter.AuthorityEntry>
12476                    authoritiesIterator = intent.authoritiesIterator();
12477            if (authoritiesIterator != null) {
12478                getIntentListSubset(intentListCopy,
12479                        new AuthoritiesIterGenerator(),
12480                        authoritiesIterator);
12481                if (intentListCopy.size() == 0) {
12482                    // no more intents to match; we're not equivalent
12483                    if (DEBUG_FILTERS) {
12484                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12485                                + " package: " + applicationInfo.packageName
12486                                + " activity: " + intent.activity.className
12487                                + " origPrio: " + intent.getPriority());
12488                    }
12489                    intent.setPriority(0);
12490                    return;
12491                }
12492            }
12493
12494            // we found matching filter(s); app gets the max priority of all intents
12495            int cappedPriority = 0;
12496            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12497                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12498            }
12499            if (intent.getPriority() > cappedPriority) {
12500                if (DEBUG_FILTERS) {
12501                    Slog.i(TAG, "Found matching filter(s);"
12502                            + " cap priority to " + cappedPriority + ";"
12503                            + " package: " + applicationInfo.packageName
12504                            + " activity: " + intent.activity.className
12505                            + " origPrio: " + intent.getPriority());
12506                }
12507                intent.setPriority(cappedPriority);
12508                return;
12509            }
12510            // all this for nothing; the requested priority was <= what was on the system
12511        }
12512
12513        public final void addActivity(PackageParser.Activity a, String type) {
12514            mActivities.put(a.getComponentName(), a);
12515            if (DEBUG_SHOW_INFO)
12516                Log.v(
12517                TAG, "  " + type + " " +
12518                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12519            if (DEBUG_SHOW_INFO)
12520                Log.v(TAG, "    Class=" + a.info.name);
12521            final int NI = a.intents.size();
12522            for (int j=0; j<NI; j++) {
12523                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12524                if ("activity".equals(type)) {
12525                    final PackageSetting ps =
12526                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12527                    final List<PackageParser.Activity> systemActivities =
12528                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12529                    adjustPriority(systemActivities, intent);
12530                }
12531                if (DEBUG_SHOW_INFO) {
12532                    Log.v(TAG, "    IntentFilter:");
12533                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12534                }
12535                if (!intent.debugCheck()) {
12536                    Log.w(TAG, "==> For Activity " + a.info.name);
12537                }
12538                addFilter(intent);
12539            }
12540        }
12541
12542        public final void removeActivity(PackageParser.Activity a, String type) {
12543            mActivities.remove(a.getComponentName());
12544            if (DEBUG_SHOW_INFO) {
12545                Log.v(TAG, "  " + type + " "
12546                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12547                                : a.info.name) + ":");
12548                Log.v(TAG, "    Class=" + a.info.name);
12549            }
12550            final int NI = a.intents.size();
12551            for (int j=0; j<NI; j++) {
12552                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12553                if (DEBUG_SHOW_INFO) {
12554                    Log.v(TAG, "    IntentFilter:");
12555                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12556                }
12557                removeFilter(intent);
12558            }
12559        }
12560
12561        @Override
12562        protected boolean allowFilterResult(
12563                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12564            ActivityInfo filterAi = filter.activity.info;
12565            for (int i=dest.size()-1; i>=0; i--) {
12566                ActivityInfo destAi = dest.get(i).activityInfo;
12567                if (destAi.name == filterAi.name
12568                        && destAi.packageName == filterAi.packageName) {
12569                    return false;
12570                }
12571            }
12572            return true;
12573        }
12574
12575        @Override
12576        protected ActivityIntentInfo[] newArray(int size) {
12577            return new ActivityIntentInfo[size];
12578        }
12579
12580        @Override
12581        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12582            if (!sUserManager.exists(userId)) return true;
12583            PackageParser.Package p = filter.activity.owner;
12584            if (p != null) {
12585                PackageSetting ps = (PackageSetting)p.mExtras;
12586                if (ps != null) {
12587                    // System apps are never considered stopped for purposes of
12588                    // filtering, because there may be no way for the user to
12589                    // actually re-launch them.
12590                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12591                            && ps.getStopped(userId);
12592                }
12593            }
12594            return false;
12595        }
12596
12597        @Override
12598        protected boolean isPackageForFilter(String packageName,
12599                PackageParser.ActivityIntentInfo info) {
12600            return packageName.equals(info.activity.owner.packageName);
12601        }
12602
12603        @Override
12604        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12605                int match, int userId) {
12606            if (!sUserManager.exists(userId)) return null;
12607            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12608                return null;
12609            }
12610            final PackageParser.Activity activity = info.activity;
12611            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12612            if (ps == null) {
12613                return null;
12614            }
12615            final PackageUserState userState = ps.readUserState(userId);
12616            ActivityInfo ai =
12617                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12618            if (ai == null) {
12619                return null;
12620            }
12621            final boolean matchExplicitlyVisibleOnly =
12622                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12623            final boolean matchVisibleToInstantApp =
12624                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12625            final boolean componentVisible =
12626                    matchVisibleToInstantApp
12627                    && info.isVisibleToInstantApp()
12628                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12629            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12630            // throw out filters that aren't visible to ephemeral apps
12631            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12632                return null;
12633            }
12634            // throw out instant app filters if we're not explicitly requesting them
12635            if (!matchInstantApp && userState.instantApp) {
12636                return null;
12637            }
12638            // throw out instant app filters if updates are available; will trigger
12639            // instant app resolution
12640            if (userState.instantApp && ps.isUpdateAvailable()) {
12641                return null;
12642            }
12643            final ResolveInfo res = new ResolveInfo();
12644            res.activityInfo = ai;
12645            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12646                res.filter = info;
12647            }
12648            if (info != null) {
12649                res.handleAllWebDataURI = info.handleAllWebDataURI();
12650            }
12651            res.priority = info.getPriority();
12652            res.preferredOrder = activity.owner.mPreferredOrder;
12653            //System.out.println("Result: " + res.activityInfo.className +
12654            //                   " = " + res.priority);
12655            res.match = match;
12656            res.isDefault = info.hasDefault;
12657            res.labelRes = info.labelRes;
12658            res.nonLocalizedLabel = info.nonLocalizedLabel;
12659            if (userNeedsBadging(userId)) {
12660                res.noResourceId = true;
12661            } else {
12662                res.icon = info.icon;
12663            }
12664            res.iconResourceId = info.icon;
12665            res.system = res.activityInfo.applicationInfo.isSystemApp();
12666            res.isInstantAppAvailable = userState.instantApp;
12667            return res;
12668        }
12669
12670        @Override
12671        protected void sortResults(List<ResolveInfo> results) {
12672            Collections.sort(results, mResolvePrioritySorter);
12673        }
12674
12675        @Override
12676        protected void dumpFilter(PrintWriter out, String prefix,
12677                PackageParser.ActivityIntentInfo filter) {
12678            out.print(prefix); out.print(
12679                    Integer.toHexString(System.identityHashCode(filter.activity)));
12680                    out.print(' ');
12681                    filter.activity.printComponentShortName(out);
12682                    out.print(" filter ");
12683                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12684        }
12685
12686        @Override
12687        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12688            return filter.activity;
12689        }
12690
12691        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12692            PackageParser.Activity activity = (PackageParser.Activity)label;
12693            out.print(prefix); out.print(
12694                    Integer.toHexString(System.identityHashCode(activity)));
12695                    out.print(' ');
12696                    activity.printComponentShortName(out);
12697            if (count > 1) {
12698                out.print(" ("); out.print(count); out.print(" filters)");
12699            }
12700            out.println();
12701        }
12702
12703        // Keys are String (activity class name), values are Activity.
12704        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12705                = new ArrayMap<ComponentName, PackageParser.Activity>();
12706        private int mFlags;
12707    }
12708
12709    private final class ServiceIntentResolver
12710            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12711        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12712                boolean defaultOnly, int userId) {
12713            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12714            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12715        }
12716
12717        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12718                int userId) {
12719            if (!sUserManager.exists(userId)) return null;
12720            mFlags = flags;
12721            return super.queryIntent(intent, resolvedType,
12722                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12723                    userId);
12724        }
12725
12726        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12727                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12728            if (!sUserManager.exists(userId)) return null;
12729            if (packageServices == null) {
12730                return null;
12731            }
12732            mFlags = flags;
12733            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12734            final int N = packageServices.size();
12735            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12736                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12737
12738            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12739            for (int i = 0; i < N; ++i) {
12740                intentFilters = packageServices.get(i).intents;
12741                if (intentFilters != null && intentFilters.size() > 0) {
12742                    PackageParser.ServiceIntentInfo[] array =
12743                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12744                    intentFilters.toArray(array);
12745                    listCut.add(array);
12746                }
12747            }
12748            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12749        }
12750
12751        public final void addService(PackageParser.Service s) {
12752            mServices.put(s.getComponentName(), s);
12753            if (DEBUG_SHOW_INFO) {
12754                Log.v(TAG, "  "
12755                        + (s.info.nonLocalizedLabel != null
12756                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12757                Log.v(TAG, "    Class=" + s.info.name);
12758            }
12759            final int NI = s.intents.size();
12760            int j;
12761            for (j=0; j<NI; j++) {
12762                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12763                if (DEBUG_SHOW_INFO) {
12764                    Log.v(TAG, "    IntentFilter:");
12765                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12766                }
12767                if (!intent.debugCheck()) {
12768                    Log.w(TAG, "==> For Service " + s.info.name);
12769                }
12770                addFilter(intent);
12771            }
12772        }
12773
12774        public final void removeService(PackageParser.Service s) {
12775            mServices.remove(s.getComponentName());
12776            if (DEBUG_SHOW_INFO) {
12777                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12778                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12779                Log.v(TAG, "    Class=" + s.info.name);
12780            }
12781            final int NI = s.intents.size();
12782            int j;
12783            for (j=0; j<NI; j++) {
12784                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12785                if (DEBUG_SHOW_INFO) {
12786                    Log.v(TAG, "    IntentFilter:");
12787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12788                }
12789                removeFilter(intent);
12790            }
12791        }
12792
12793        @Override
12794        protected boolean allowFilterResult(
12795                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12796            ServiceInfo filterSi = filter.service.info;
12797            for (int i=dest.size()-1; i>=0; i--) {
12798                ServiceInfo destAi = dest.get(i).serviceInfo;
12799                if (destAi.name == filterSi.name
12800                        && destAi.packageName == filterSi.packageName) {
12801                    return false;
12802                }
12803            }
12804            return true;
12805        }
12806
12807        @Override
12808        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12809            return new PackageParser.ServiceIntentInfo[size];
12810        }
12811
12812        @Override
12813        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12814            if (!sUserManager.exists(userId)) return true;
12815            PackageParser.Package p = filter.service.owner;
12816            if (p != null) {
12817                PackageSetting ps = (PackageSetting)p.mExtras;
12818                if (ps != null) {
12819                    // System apps are never considered stopped for purposes of
12820                    // filtering, because there may be no way for the user to
12821                    // actually re-launch them.
12822                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12823                            && ps.getStopped(userId);
12824                }
12825            }
12826            return false;
12827        }
12828
12829        @Override
12830        protected boolean isPackageForFilter(String packageName,
12831                PackageParser.ServiceIntentInfo info) {
12832            return packageName.equals(info.service.owner.packageName);
12833        }
12834
12835        @Override
12836        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12837                int match, int userId) {
12838            if (!sUserManager.exists(userId)) return null;
12839            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12840            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12841                return null;
12842            }
12843            final PackageParser.Service service = info.service;
12844            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12845            if (ps == null) {
12846                return null;
12847            }
12848            final PackageUserState userState = ps.readUserState(userId);
12849            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12850                    userState, userId);
12851            if (si == null) {
12852                return null;
12853            }
12854            final boolean matchVisibleToInstantApp =
12855                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12856            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12857            // throw out filters that aren't visible to ephemeral apps
12858            if (matchVisibleToInstantApp
12859                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12860                return null;
12861            }
12862            // throw out ephemeral filters if we're not explicitly requesting them
12863            if (!isInstantApp && userState.instantApp) {
12864                return null;
12865            }
12866            // throw out instant app filters if updates are available; will trigger
12867            // instant app resolution
12868            if (userState.instantApp && ps.isUpdateAvailable()) {
12869                return null;
12870            }
12871            final ResolveInfo res = new ResolveInfo();
12872            res.serviceInfo = si;
12873            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12874                res.filter = filter;
12875            }
12876            res.priority = info.getPriority();
12877            res.preferredOrder = service.owner.mPreferredOrder;
12878            res.match = match;
12879            res.isDefault = info.hasDefault;
12880            res.labelRes = info.labelRes;
12881            res.nonLocalizedLabel = info.nonLocalizedLabel;
12882            res.icon = info.icon;
12883            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12884            return res;
12885        }
12886
12887        @Override
12888        protected void sortResults(List<ResolveInfo> results) {
12889            Collections.sort(results, mResolvePrioritySorter);
12890        }
12891
12892        @Override
12893        protected void dumpFilter(PrintWriter out, String prefix,
12894                PackageParser.ServiceIntentInfo filter) {
12895            out.print(prefix); out.print(
12896                    Integer.toHexString(System.identityHashCode(filter.service)));
12897                    out.print(' ');
12898                    filter.service.printComponentShortName(out);
12899                    out.print(" filter ");
12900                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12901                    if (filter.service.info.permission != null) {
12902                        out.print(" permission "); out.println(filter.service.info.permission);
12903                    } else {
12904                        out.println();
12905                    }
12906        }
12907
12908        @Override
12909        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12910            return filter.service;
12911        }
12912
12913        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12914            PackageParser.Service service = (PackageParser.Service)label;
12915            out.print(prefix); out.print(
12916                    Integer.toHexString(System.identityHashCode(service)));
12917                    out.print(' ');
12918                    service.printComponentShortName(out);
12919            if (count > 1) {
12920                out.print(" ("); out.print(count); out.print(" filters)");
12921            }
12922            out.println();
12923        }
12924
12925//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12926//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12927//            final List<ResolveInfo> retList = Lists.newArrayList();
12928//            while (i.hasNext()) {
12929//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12930//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12931//                    retList.add(resolveInfo);
12932//                }
12933//            }
12934//            return retList;
12935//        }
12936
12937        // Keys are String (activity class name), values are Activity.
12938        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12939                = new ArrayMap<ComponentName, PackageParser.Service>();
12940        private int mFlags;
12941    }
12942
12943    private final class ProviderIntentResolver
12944            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12945        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12946                boolean defaultOnly, int userId) {
12947            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12948            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12949        }
12950
12951        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12952                int userId) {
12953            if (!sUserManager.exists(userId))
12954                return null;
12955            mFlags = flags;
12956            return super.queryIntent(intent, resolvedType,
12957                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12958                    userId);
12959        }
12960
12961        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12962                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12963            if (!sUserManager.exists(userId))
12964                return null;
12965            if (packageProviders == null) {
12966                return null;
12967            }
12968            mFlags = flags;
12969            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12970            final int N = packageProviders.size();
12971            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12972                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12973
12974            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12975            for (int i = 0; i < N; ++i) {
12976                intentFilters = packageProviders.get(i).intents;
12977                if (intentFilters != null && intentFilters.size() > 0) {
12978                    PackageParser.ProviderIntentInfo[] array =
12979                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12980                    intentFilters.toArray(array);
12981                    listCut.add(array);
12982                }
12983            }
12984            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12985        }
12986
12987        public final void addProvider(PackageParser.Provider p) {
12988            if (mProviders.containsKey(p.getComponentName())) {
12989                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12990                return;
12991            }
12992
12993            mProviders.put(p.getComponentName(), p);
12994            if (DEBUG_SHOW_INFO) {
12995                Log.v(TAG, "  "
12996                        + (p.info.nonLocalizedLabel != null
12997                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12998                Log.v(TAG, "    Class=" + p.info.name);
12999            }
13000            final int NI = p.intents.size();
13001            int j;
13002            for (j = 0; j < NI; j++) {
13003                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13004                if (DEBUG_SHOW_INFO) {
13005                    Log.v(TAG, "    IntentFilter:");
13006                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13007                }
13008                if (!intent.debugCheck()) {
13009                    Log.w(TAG, "==> For Provider " + p.info.name);
13010                }
13011                addFilter(intent);
13012            }
13013        }
13014
13015        public final void removeProvider(PackageParser.Provider p) {
13016            mProviders.remove(p.getComponentName());
13017            if (DEBUG_SHOW_INFO) {
13018                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13019                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13020                Log.v(TAG, "    Class=" + p.info.name);
13021            }
13022            final int NI = p.intents.size();
13023            int j;
13024            for (j = 0; j < NI; j++) {
13025                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13026                if (DEBUG_SHOW_INFO) {
13027                    Log.v(TAG, "    IntentFilter:");
13028                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13029                }
13030                removeFilter(intent);
13031            }
13032        }
13033
13034        @Override
13035        protected boolean allowFilterResult(
13036                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13037            ProviderInfo filterPi = filter.provider.info;
13038            for (int i = dest.size() - 1; i >= 0; i--) {
13039                ProviderInfo destPi = dest.get(i).providerInfo;
13040                if (destPi.name == filterPi.name
13041                        && destPi.packageName == filterPi.packageName) {
13042                    return false;
13043                }
13044            }
13045            return true;
13046        }
13047
13048        @Override
13049        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13050            return new PackageParser.ProviderIntentInfo[size];
13051        }
13052
13053        @Override
13054        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13055            if (!sUserManager.exists(userId))
13056                return true;
13057            PackageParser.Package p = filter.provider.owner;
13058            if (p != null) {
13059                PackageSetting ps = (PackageSetting) p.mExtras;
13060                if (ps != null) {
13061                    // System apps are never considered stopped for purposes of
13062                    // filtering, because there may be no way for the user to
13063                    // actually re-launch them.
13064                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13065                            && ps.getStopped(userId);
13066                }
13067            }
13068            return false;
13069        }
13070
13071        @Override
13072        protected boolean isPackageForFilter(String packageName,
13073                PackageParser.ProviderIntentInfo info) {
13074            return packageName.equals(info.provider.owner.packageName);
13075        }
13076
13077        @Override
13078        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13079                int match, int userId) {
13080            if (!sUserManager.exists(userId))
13081                return null;
13082            final PackageParser.ProviderIntentInfo info = filter;
13083            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13084                return null;
13085            }
13086            final PackageParser.Provider provider = info.provider;
13087            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13088            if (ps == null) {
13089                return null;
13090            }
13091            final PackageUserState userState = ps.readUserState(userId);
13092            final boolean matchVisibleToInstantApp =
13093                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13094            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13095            // throw out filters that aren't visible to instant applications
13096            if (matchVisibleToInstantApp
13097                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13098                return null;
13099            }
13100            // throw out instant application filters if we're not explicitly requesting them
13101            if (!isInstantApp && userState.instantApp) {
13102                return null;
13103            }
13104            // throw out instant application filters if updates are available; will trigger
13105            // instant application resolution
13106            if (userState.instantApp && ps.isUpdateAvailable()) {
13107                return null;
13108            }
13109            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13110                    userState, userId);
13111            if (pi == null) {
13112                return null;
13113            }
13114            final ResolveInfo res = new ResolveInfo();
13115            res.providerInfo = pi;
13116            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13117                res.filter = filter;
13118            }
13119            res.priority = info.getPriority();
13120            res.preferredOrder = provider.owner.mPreferredOrder;
13121            res.match = match;
13122            res.isDefault = info.hasDefault;
13123            res.labelRes = info.labelRes;
13124            res.nonLocalizedLabel = info.nonLocalizedLabel;
13125            res.icon = info.icon;
13126            res.system = res.providerInfo.applicationInfo.isSystemApp();
13127            return res;
13128        }
13129
13130        @Override
13131        protected void sortResults(List<ResolveInfo> results) {
13132            Collections.sort(results, mResolvePrioritySorter);
13133        }
13134
13135        @Override
13136        protected void dumpFilter(PrintWriter out, String prefix,
13137                PackageParser.ProviderIntentInfo filter) {
13138            out.print(prefix);
13139            out.print(
13140                    Integer.toHexString(System.identityHashCode(filter.provider)));
13141            out.print(' ');
13142            filter.provider.printComponentShortName(out);
13143            out.print(" filter ");
13144            out.println(Integer.toHexString(System.identityHashCode(filter)));
13145        }
13146
13147        @Override
13148        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13149            return filter.provider;
13150        }
13151
13152        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13153            PackageParser.Provider provider = (PackageParser.Provider)label;
13154            out.print(prefix); out.print(
13155                    Integer.toHexString(System.identityHashCode(provider)));
13156                    out.print(' ');
13157                    provider.printComponentShortName(out);
13158            if (count > 1) {
13159                out.print(" ("); out.print(count); out.print(" filters)");
13160            }
13161            out.println();
13162        }
13163
13164        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13165                = new ArrayMap<ComponentName, PackageParser.Provider>();
13166        private int mFlags;
13167    }
13168
13169    static final class InstantAppIntentResolver
13170            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13171            AuxiliaryResolveInfo.AuxiliaryFilter> {
13172        /**
13173         * The result that has the highest defined order. Ordering applies on a
13174         * per-package basis. Mapping is from package name to Pair of order and
13175         * EphemeralResolveInfo.
13176         * <p>
13177         * NOTE: This is implemented as a field variable for convenience and efficiency.
13178         * By having a field variable, we're able to track filter ordering as soon as
13179         * a non-zero order is defined. Otherwise, multiple loops across the result set
13180         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13181         * this needs to be contained entirely within {@link #filterResults}.
13182         */
13183        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13184
13185        @Override
13186        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13187            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13188        }
13189
13190        @Override
13191        protected boolean isPackageForFilter(String packageName,
13192                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13193            return true;
13194        }
13195
13196        @Override
13197        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13198                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13199            if (!sUserManager.exists(userId)) {
13200                return null;
13201            }
13202            final String packageName = responseObj.resolveInfo.getPackageName();
13203            final Integer order = responseObj.getOrder();
13204            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13205                    mOrderResult.get(packageName);
13206            // ordering is enabled and this item's order isn't high enough
13207            if (lastOrderResult != null && lastOrderResult.first >= order) {
13208                return null;
13209            }
13210            final InstantAppResolveInfo res = responseObj.resolveInfo;
13211            if (order > 0) {
13212                // non-zero order, enable ordering
13213                mOrderResult.put(packageName, new Pair<>(order, res));
13214            }
13215            return responseObj;
13216        }
13217
13218        @Override
13219        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13220            // only do work if ordering is enabled [most of the time it won't be]
13221            if (mOrderResult.size() == 0) {
13222                return;
13223            }
13224            int resultSize = results.size();
13225            for (int i = 0; i < resultSize; i++) {
13226                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13227                final String packageName = info.getPackageName();
13228                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13229                if (savedInfo == null) {
13230                    // package doesn't having ordering
13231                    continue;
13232                }
13233                if (savedInfo.second == info) {
13234                    // circled back to the highest ordered item; remove from order list
13235                    mOrderResult.remove(packageName);
13236                    if (mOrderResult.size() == 0) {
13237                        // no more ordered items
13238                        break;
13239                    }
13240                    continue;
13241                }
13242                // item has a worse order, remove it from the result list
13243                results.remove(i);
13244                resultSize--;
13245                i--;
13246            }
13247        }
13248    }
13249
13250    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13251            new Comparator<ResolveInfo>() {
13252        public int compare(ResolveInfo r1, ResolveInfo r2) {
13253            int v1 = r1.priority;
13254            int v2 = r2.priority;
13255            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13256            if (v1 != v2) {
13257                return (v1 > v2) ? -1 : 1;
13258            }
13259            v1 = r1.preferredOrder;
13260            v2 = r2.preferredOrder;
13261            if (v1 != v2) {
13262                return (v1 > v2) ? -1 : 1;
13263            }
13264            if (r1.isDefault != r2.isDefault) {
13265                return r1.isDefault ? -1 : 1;
13266            }
13267            v1 = r1.match;
13268            v2 = r2.match;
13269            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13270            if (v1 != v2) {
13271                return (v1 > v2) ? -1 : 1;
13272            }
13273            if (r1.system != r2.system) {
13274                return r1.system ? -1 : 1;
13275            }
13276            if (r1.activityInfo != null) {
13277                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13278            }
13279            if (r1.serviceInfo != null) {
13280                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13281            }
13282            if (r1.providerInfo != null) {
13283                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13284            }
13285            return 0;
13286        }
13287    };
13288
13289    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13290            new Comparator<ProviderInfo>() {
13291        public int compare(ProviderInfo p1, ProviderInfo p2) {
13292            final int v1 = p1.initOrder;
13293            final int v2 = p2.initOrder;
13294            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13295        }
13296    };
13297
13298    @Override
13299    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13300            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13301            final int[] userIds, int[] instantUserIds) {
13302        mHandler.post(new Runnable() {
13303            @Override
13304            public void run() {
13305                try {
13306                    final IActivityManager am = ActivityManager.getService();
13307                    if (am == null) return;
13308                    final int[] resolvedUserIds;
13309                    if (userIds == null) {
13310                        resolvedUserIds = am.getRunningUserIds();
13311                    } else {
13312                        resolvedUserIds = userIds;
13313                    }
13314                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13315                            resolvedUserIds, false);
13316                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13317                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13318                                instantUserIds, true);
13319                    }
13320                } catch (RemoteException ex) {
13321                }
13322            }
13323        });
13324    }
13325
13326    @Override
13327    public void notifyPackageAdded(String packageName) {
13328        final PackageListObserver[] observers;
13329        synchronized (mPackages) {
13330            if (mPackageListObservers.size() == 0) {
13331                return;
13332            }
13333            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13334        }
13335        for (int i = observers.length - 1; i >= 0; --i) {
13336            observers[i].onPackageAdded(packageName);
13337        }
13338    }
13339
13340    @Override
13341    public void notifyPackageRemoved(String packageName) {
13342        final PackageListObserver[] observers;
13343        synchronized (mPackages) {
13344            if (mPackageListObservers.size() == 0) {
13345                return;
13346            }
13347            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13348        }
13349        for (int i = observers.length - 1; i >= 0; --i) {
13350            observers[i].onPackageRemoved(packageName);
13351        }
13352    }
13353
13354    /**
13355     * Sends a broadcast for the given action.
13356     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13357     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13358     * the system and applications allowed to see instant applications to receive package
13359     * lifecycle events for instant applications.
13360     */
13361    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13362            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13363            int[] userIds, boolean isInstantApp)
13364                    throws RemoteException {
13365        for (int id : userIds) {
13366            final Intent intent = new Intent(action,
13367                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13368            final String[] requiredPermissions =
13369                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13370            if (extras != null) {
13371                intent.putExtras(extras);
13372            }
13373            if (targetPkg != null) {
13374                intent.setPackage(targetPkg);
13375            }
13376            // Modify the UID when posting to other users
13377            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13378            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13379                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13380                intent.putExtra(Intent.EXTRA_UID, uid);
13381            }
13382            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13383            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13384            if (DEBUG_BROADCASTS) {
13385                RuntimeException here = new RuntimeException("here");
13386                here.fillInStackTrace();
13387                Slog.d(TAG, "Sending to user " + id + ": "
13388                        + intent.toShortString(false, true, false, false)
13389                        + " " + intent.getExtras(), here);
13390            }
13391            am.broadcastIntent(null, intent, null, finishedReceiver,
13392                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13393                    null, finishedReceiver != null, false, id);
13394        }
13395    }
13396
13397    /**
13398     * Check if the external storage media is available. This is true if there
13399     * is a mounted external storage medium or if the external storage is
13400     * emulated.
13401     */
13402    private boolean isExternalMediaAvailable() {
13403        return mMediaMounted || Environment.isExternalStorageEmulated();
13404    }
13405
13406    @Override
13407    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13408        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13409            return null;
13410        }
13411        if (!isExternalMediaAvailable()) {
13412                // If the external storage is no longer mounted at this point,
13413                // the caller may not have been able to delete all of this
13414                // packages files and can not delete any more.  Bail.
13415            return null;
13416        }
13417        synchronized (mPackages) {
13418            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13419            if (lastPackage != null) {
13420                pkgs.remove(lastPackage);
13421            }
13422            if (pkgs.size() > 0) {
13423                return pkgs.get(0);
13424            }
13425        }
13426        return null;
13427    }
13428
13429    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13430        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13431                userId, andCode ? 1 : 0, packageName);
13432        if (mSystemReady) {
13433            msg.sendToTarget();
13434        } else {
13435            if (mPostSystemReadyMessages == null) {
13436                mPostSystemReadyMessages = new ArrayList<>();
13437            }
13438            mPostSystemReadyMessages.add(msg);
13439        }
13440    }
13441
13442    void startCleaningPackages() {
13443        // reader
13444        if (!isExternalMediaAvailable()) {
13445            return;
13446        }
13447        synchronized (mPackages) {
13448            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13449                return;
13450            }
13451        }
13452        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13453        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13454        IActivityManager am = ActivityManager.getService();
13455        if (am != null) {
13456            int dcsUid = -1;
13457            synchronized (mPackages) {
13458                if (!mDefaultContainerWhitelisted) {
13459                    mDefaultContainerWhitelisted = true;
13460                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13461                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13462                }
13463            }
13464            try {
13465                if (dcsUid > 0) {
13466                    am.backgroundWhitelistUid(dcsUid);
13467                }
13468                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13469                        UserHandle.USER_SYSTEM);
13470            } catch (RemoteException e) {
13471            }
13472        }
13473    }
13474
13475    /**
13476     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13477     * it is acting on behalf on an enterprise or the user).
13478     *
13479     * Note that the ordering of the conditionals in this method is important. The checks we perform
13480     * are as follows, in this order:
13481     *
13482     * 1) If the install is being performed by a system app, we can trust the app to have set the
13483     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13484     *    what it is.
13485     * 2) If the install is being performed by a device or profile owner app, the install reason
13486     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13487     *    set the install reason correctly. If the app targets an older SDK version where install
13488     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13489     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13490     * 3) In all other cases, the install is being performed by a regular app that is neither part
13491     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13492     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13493     *    set to enterprise policy and if so, change it to unknown instead.
13494     */
13495    private int fixUpInstallReason(String installerPackageName, int installerUid,
13496            int installReason) {
13497        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13498                == PERMISSION_GRANTED) {
13499            // If the install is being performed by a system app, we trust that app to have set the
13500            // install reason correctly.
13501            return installReason;
13502        }
13503
13504        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13505            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13506        if (dpm != null) {
13507            ComponentName owner = null;
13508            try {
13509                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13510                if (owner == null) {
13511                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13512                }
13513            } catch (RemoteException e) {
13514            }
13515            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13516                // If the install is being performed by a device or profile owner, the install
13517                // reason should be enterprise policy.
13518                return PackageManager.INSTALL_REASON_POLICY;
13519            }
13520        }
13521
13522        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13523            // If the install is being performed by a regular app (i.e. neither system app nor
13524            // device or profile owner), we have no reason to believe that the app is acting on
13525            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13526            // change it to unknown instead.
13527            return PackageManager.INSTALL_REASON_UNKNOWN;
13528        }
13529
13530        // If the install is being performed by a regular app and the install reason was set to any
13531        // value but enterprise policy, leave the install reason unchanged.
13532        return installReason;
13533    }
13534
13535    void installStage(String packageName, File stagedDir,
13536            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13537            String installerPackageName, int installerUid, UserHandle user,
13538            PackageParser.SigningDetails signingDetails) {
13539        if (DEBUG_INSTANT) {
13540            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13541                Slog.d(TAG, "Ephemeral install of " + packageName);
13542            }
13543        }
13544        final VerificationInfo verificationInfo = new VerificationInfo(
13545                sessionParams.originatingUri, sessionParams.referrerUri,
13546                sessionParams.originatingUid, installerUid);
13547
13548        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13549
13550        final Message msg = mHandler.obtainMessage(INIT_COPY);
13551        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13552                sessionParams.installReason);
13553        final InstallParams params = new InstallParams(origin, null, observer,
13554                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13555                verificationInfo, user, sessionParams.abiOverride,
13556                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13557        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13558        msg.obj = params;
13559
13560        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13561                System.identityHashCode(msg.obj));
13562        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13563                System.identityHashCode(msg.obj));
13564
13565        mHandler.sendMessage(msg);
13566    }
13567
13568    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13569            int userId) {
13570        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13571        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13572        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13573        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13574        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13575                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13576
13577        // Send a session commit broadcast
13578        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13579        info.installReason = pkgSetting.getInstallReason(userId);
13580        info.appPackageName = packageName;
13581        sendSessionCommitBroadcast(info, userId);
13582    }
13583
13584    @Override
13585    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13586            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13587        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13588            return;
13589        }
13590        Bundle extras = new Bundle(1);
13591        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13592        final int uid = UserHandle.getUid(
13593                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13594        extras.putInt(Intent.EXTRA_UID, uid);
13595
13596        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13597                packageName, extras, 0, null, null, userIds, instantUserIds);
13598        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13599            mHandler.post(() -> {
13600                        for (int userId : userIds) {
13601                            sendBootCompletedBroadcastToSystemApp(
13602                                    packageName, includeStopped, userId);
13603                        }
13604                    }
13605            );
13606        }
13607    }
13608
13609    /**
13610     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13611     * automatically without needing an explicit launch.
13612     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13613     */
13614    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13615            int userId) {
13616        // If user is not running, the app didn't miss any broadcast
13617        if (!mUserManagerInternal.isUserRunning(userId)) {
13618            return;
13619        }
13620        final IActivityManager am = ActivityManager.getService();
13621        try {
13622            // Deliver LOCKED_BOOT_COMPLETED first
13623            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13624                    .setPackage(packageName);
13625            if (includeStopped) {
13626                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13627            }
13628            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13629            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13630                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13631
13632            // Deliver BOOT_COMPLETED only if user is unlocked
13633            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13634                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13635                if (includeStopped) {
13636                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13637                }
13638                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13639                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13640            }
13641        } catch (RemoteException e) {
13642            throw e.rethrowFromSystemServer();
13643        }
13644    }
13645
13646    @Override
13647    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13648            int userId) {
13649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13650        PackageSetting pkgSetting;
13651        final int callingUid = Binder.getCallingUid();
13652        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13653                true /* requireFullPermission */, true /* checkShell */,
13654                "setApplicationHiddenSetting for user " + userId);
13655
13656        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13657            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13658            return false;
13659        }
13660
13661        long callingId = Binder.clearCallingIdentity();
13662        try {
13663            boolean sendAdded = false;
13664            boolean sendRemoved = false;
13665            // writer
13666            synchronized (mPackages) {
13667                pkgSetting = mSettings.mPackages.get(packageName);
13668                if (pkgSetting == null) {
13669                    return false;
13670                }
13671                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13672                    return false;
13673                }
13674                // Do not allow "android" is being disabled
13675                if ("android".equals(packageName)) {
13676                    Slog.w(TAG, "Cannot hide package: android");
13677                    return false;
13678                }
13679                // Cannot hide static shared libs as they are considered
13680                // a part of the using app (emulating static linking). Also
13681                // static libs are installed always on internal storage.
13682                PackageParser.Package pkg = mPackages.get(packageName);
13683                if (pkg != null && pkg.staticSharedLibName != null) {
13684                    Slog.w(TAG, "Cannot hide package: " + packageName
13685                            + " providing static shared library: "
13686                            + pkg.staticSharedLibName);
13687                    return false;
13688                }
13689                // Only allow protected packages to hide themselves.
13690                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13691                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13692                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13693                    return false;
13694                }
13695
13696                if (pkgSetting.getHidden(userId) != hidden) {
13697                    pkgSetting.setHidden(hidden, userId);
13698                    mSettings.writePackageRestrictionsLPr(userId);
13699                    if (hidden) {
13700                        sendRemoved = true;
13701                    } else {
13702                        sendAdded = true;
13703                    }
13704                }
13705            }
13706            if (sendAdded) {
13707                sendPackageAddedForUser(packageName, pkgSetting, userId);
13708                return true;
13709            }
13710            if (sendRemoved) {
13711                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13712                        "hiding pkg");
13713                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13714                return true;
13715            }
13716        } finally {
13717            Binder.restoreCallingIdentity(callingId);
13718        }
13719        return false;
13720    }
13721
13722    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13723            int userId) {
13724        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13725        info.removedPackage = packageName;
13726        info.installerPackageName = pkgSetting.installerPackageName;
13727        info.removedUsers = new int[] {userId};
13728        info.broadcastUsers = new int[] {userId};
13729        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13730        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13731    }
13732
13733    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13734        if (pkgList.length > 0) {
13735            Bundle extras = new Bundle(1);
13736            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13737
13738            sendPackageBroadcast(
13739                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13740                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13741                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13742                    new int[] {userId}, null);
13743        }
13744    }
13745
13746    /**
13747     * Returns true if application is not found or there was an error. Otherwise it returns
13748     * the hidden state of the package for the given user.
13749     */
13750    @Override
13751    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13752        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13753        final int callingUid = Binder.getCallingUid();
13754        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13755                true /* requireFullPermission */, false /* checkShell */,
13756                "getApplicationHidden for user " + userId);
13757        PackageSetting ps;
13758        long callingId = Binder.clearCallingIdentity();
13759        try {
13760            // writer
13761            synchronized (mPackages) {
13762                ps = mSettings.mPackages.get(packageName);
13763                if (ps == null) {
13764                    return true;
13765                }
13766                if (filterAppAccessLPr(ps, callingUid, userId)) {
13767                    return true;
13768                }
13769                return ps.getHidden(userId);
13770            }
13771        } finally {
13772            Binder.restoreCallingIdentity(callingId);
13773        }
13774    }
13775
13776    /**
13777     * @hide
13778     */
13779    @Override
13780    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13781            int installReason) {
13782        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13783                null);
13784        PackageSetting pkgSetting;
13785        final int callingUid = Binder.getCallingUid();
13786        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13787                true /* requireFullPermission */, true /* checkShell */,
13788                "installExistingPackage for user " + userId);
13789        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13790            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13791        }
13792
13793        long callingId = Binder.clearCallingIdentity();
13794        try {
13795            boolean installed = false;
13796            final boolean instantApp =
13797                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13798            final boolean fullApp =
13799                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13800
13801            // writer
13802            synchronized (mPackages) {
13803                pkgSetting = mSettings.mPackages.get(packageName);
13804                if (pkgSetting == null) {
13805                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13806                }
13807                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13808                    // only allow the existing package to be used if it's installed as a full
13809                    // application for at least one user
13810                    boolean installAllowed = false;
13811                    for (int checkUserId : sUserManager.getUserIds()) {
13812                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13813                        if (installAllowed) {
13814                            break;
13815                        }
13816                    }
13817                    if (!installAllowed) {
13818                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13819                    }
13820                }
13821                if (!pkgSetting.getInstalled(userId)) {
13822                    pkgSetting.setInstalled(true, userId);
13823                    pkgSetting.setHidden(false, userId);
13824                    pkgSetting.setInstallReason(installReason, userId);
13825                    mSettings.writePackageRestrictionsLPr(userId);
13826                    mSettings.writeKernelMappingLPr(pkgSetting);
13827                    installed = true;
13828                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13829                    // upgrade app from instant to full; we don't allow app downgrade
13830                    installed = true;
13831                }
13832                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13833            }
13834
13835            if (installed) {
13836                if (pkgSetting.pkg != null) {
13837                    synchronized (mInstallLock) {
13838                        // We don't need to freeze for a brand new install
13839                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13840                    }
13841                }
13842                sendPackageAddedForUser(packageName, pkgSetting, userId);
13843                synchronized (mPackages) {
13844                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13845                }
13846            }
13847        } finally {
13848            Binder.restoreCallingIdentity(callingId);
13849        }
13850
13851        return PackageManager.INSTALL_SUCCEEDED;
13852    }
13853
13854    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13855            boolean instantApp, boolean fullApp) {
13856        // no state specified; do nothing
13857        if (!instantApp && !fullApp) {
13858            return;
13859        }
13860        if (userId != UserHandle.USER_ALL) {
13861            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13862                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13863            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13864                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13865            }
13866        } else {
13867            for (int currentUserId : sUserManager.getUserIds()) {
13868                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13869                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13870                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13871                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13872                }
13873            }
13874        }
13875    }
13876
13877    boolean isUserRestricted(int userId, String restrictionKey) {
13878        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13879        if (restrictions.getBoolean(restrictionKey, false)) {
13880            Log.w(TAG, "User is restricted: " + restrictionKey);
13881            return true;
13882        }
13883        return false;
13884    }
13885
13886    @Override
13887    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13888            int userId) {
13889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13890        final int callingUid = Binder.getCallingUid();
13891        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13892                true /* requireFullPermission */, true /* checkShell */,
13893                "setPackagesSuspended for user " + userId);
13894
13895        if (ArrayUtils.isEmpty(packageNames)) {
13896            return packageNames;
13897        }
13898
13899        // List of package names for whom the suspended state has changed.
13900        List<String> changedPackages = new ArrayList<>(packageNames.length);
13901        // List of package names for whom the suspended state is not set as requested in this
13902        // method.
13903        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13904        long callingId = Binder.clearCallingIdentity();
13905        try {
13906            for (int i = 0; i < packageNames.length; i++) {
13907                String packageName = packageNames[i];
13908                boolean changed = false;
13909                final int appId;
13910                synchronized (mPackages) {
13911                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13912                    if (pkgSetting == null
13913                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13914                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13915                                + "\". Skipping suspending/un-suspending.");
13916                        unactionedPackages.add(packageName);
13917                        continue;
13918                    }
13919                    appId = pkgSetting.appId;
13920                    if (pkgSetting.getSuspended(userId) != suspended) {
13921                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13922                            unactionedPackages.add(packageName);
13923                            continue;
13924                        }
13925                        pkgSetting.setSuspended(suspended, userId);
13926                        mSettings.writePackageRestrictionsLPr(userId);
13927                        changed = true;
13928                        changedPackages.add(packageName);
13929                    }
13930                }
13931
13932                if (changed && suspended) {
13933                    killApplication(packageName, UserHandle.getUid(userId, appId),
13934                            "suspending package");
13935                }
13936            }
13937        } finally {
13938            Binder.restoreCallingIdentity(callingId);
13939        }
13940
13941        if (!changedPackages.isEmpty()) {
13942            sendPackagesSuspendedForUser(changedPackages.toArray(
13943                    new String[changedPackages.size()]), userId, suspended);
13944        }
13945
13946        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13947    }
13948
13949    @Override
13950    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13951        final int callingUid = Binder.getCallingUid();
13952        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13953                true /* requireFullPermission */, false /* checkShell */,
13954                "isPackageSuspendedForUser for user " + userId);
13955        synchronized (mPackages) {
13956            final PackageSetting ps = mSettings.mPackages.get(packageName);
13957            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13958                throw new IllegalArgumentException("Unknown target package: " + packageName);
13959            }
13960            return ps.getSuspended(userId);
13961        }
13962    }
13963
13964    @GuardedBy("mPackages")
13965    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13966        if (isPackageDeviceAdmin(packageName, userId)) {
13967            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13968                    + "\": has an active device admin");
13969            return false;
13970        }
13971
13972        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13973        if (packageName.equals(activeLauncherPackageName)) {
13974            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13975                    + "\": contains the active launcher");
13976            return false;
13977        }
13978
13979        if (packageName.equals(mRequiredInstallerPackage)) {
13980            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13981                    + "\": required for package installation");
13982            return false;
13983        }
13984
13985        if (packageName.equals(mRequiredUninstallerPackage)) {
13986            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13987                    + "\": required for package uninstallation");
13988            return false;
13989        }
13990
13991        if (packageName.equals(mRequiredVerifierPackage)) {
13992            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13993                    + "\": required for package verification");
13994            return false;
13995        }
13996
13997        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13998            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13999                    + "\": is the default dialer");
14000            return false;
14001        }
14002
14003        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14004            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14005                    + "\": protected package");
14006            return false;
14007        }
14008
14009        // Cannot suspend static shared libs as they are considered
14010        // a part of the using app (emulating static linking). Also
14011        // static libs are installed always on internal storage.
14012        PackageParser.Package pkg = mPackages.get(packageName);
14013        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14014            Slog.w(TAG, "Cannot suspend package: " + packageName
14015                    + " providing static shared library: "
14016                    + pkg.staticSharedLibName);
14017            return false;
14018        }
14019
14020        return true;
14021    }
14022
14023    private String getActiveLauncherPackageName(int userId) {
14024        Intent intent = new Intent(Intent.ACTION_MAIN);
14025        intent.addCategory(Intent.CATEGORY_HOME);
14026        ResolveInfo resolveInfo = resolveIntent(
14027                intent,
14028                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14029                PackageManager.MATCH_DEFAULT_ONLY,
14030                userId);
14031
14032        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14033    }
14034
14035    private String getDefaultDialerPackageName(int userId) {
14036        synchronized (mPackages) {
14037            return mSettings.getDefaultDialerPackageNameLPw(userId);
14038        }
14039    }
14040
14041    @Override
14042    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14043        mContext.enforceCallingOrSelfPermission(
14044                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14045                "Only package verification agents can verify applications");
14046
14047        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14048        final PackageVerificationResponse response = new PackageVerificationResponse(
14049                verificationCode, Binder.getCallingUid());
14050        msg.arg1 = id;
14051        msg.obj = response;
14052        mHandler.sendMessage(msg);
14053    }
14054
14055    @Override
14056    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14057            long millisecondsToDelay) {
14058        mContext.enforceCallingOrSelfPermission(
14059                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14060                "Only package verification agents can extend verification timeouts");
14061
14062        final PackageVerificationState state = mPendingVerification.get(id);
14063        final PackageVerificationResponse response = new PackageVerificationResponse(
14064                verificationCodeAtTimeout, Binder.getCallingUid());
14065
14066        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14067            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14068        }
14069        if (millisecondsToDelay < 0) {
14070            millisecondsToDelay = 0;
14071        }
14072        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14073                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14074            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14075        }
14076
14077        if ((state != null) && !state.timeoutExtended()) {
14078            state.extendTimeout();
14079
14080            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14081            msg.arg1 = id;
14082            msg.obj = response;
14083            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14084        }
14085    }
14086
14087    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14088            int verificationCode, UserHandle user) {
14089        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14090        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14091        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14092        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14093        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14094
14095        mContext.sendBroadcastAsUser(intent, user,
14096                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14097    }
14098
14099    private ComponentName matchComponentForVerifier(String packageName,
14100            List<ResolveInfo> receivers) {
14101        ActivityInfo targetReceiver = null;
14102
14103        final int NR = receivers.size();
14104        for (int i = 0; i < NR; i++) {
14105            final ResolveInfo info = receivers.get(i);
14106            if (info.activityInfo == null) {
14107                continue;
14108            }
14109
14110            if (packageName.equals(info.activityInfo.packageName)) {
14111                targetReceiver = info.activityInfo;
14112                break;
14113            }
14114        }
14115
14116        if (targetReceiver == null) {
14117            return null;
14118        }
14119
14120        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14121    }
14122
14123    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14124            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14125        if (pkgInfo.verifiers.length == 0) {
14126            return null;
14127        }
14128
14129        final int N = pkgInfo.verifiers.length;
14130        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14131        for (int i = 0; i < N; i++) {
14132            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14133
14134            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14135                    receivers);
14136            if (comp == null) {
14137                continue;
14138            }
14139
14140            final int verifierUid = getUidForVerifier(verifierInfo);
14141            if (verifierUid == -1) {
14142                continue;
14143            }
14144
14145            if (DEBUG_VERIFY) {
14146                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14147                        + " with the correct signature");
14148            }
14149            sufficientVerifiers.add(comp);
14150            verificationState.addSufficientVerifier(verifierUid);
14151        }
14152
14153        return sufficientVerifiers;
14154    }
14155
14156    private int getUidForVerifier(VerifierInfo verifierInfo) {
14157        synchronized (mPackages) {
14158            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14159            if (pkg == null) {
14160                return -1;
14161            } else if (pkg.mSigningDetails.signatures.length != 1) {
14162                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14163                        + " has more than one signature; ignoring");
14164                return -1;
14165            }
14166
14167            /*
14168             * If the public key of the package's signature does not match
14169             * our expected public key, then this is a different package and
14170             * we should skip.
14171             */
14172
14173            final byte[] expectedPublicKey;
14174            try {
14175                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14176                final PublicKey publicKey = verifierSig.getPublicKey();
14177                expectedPublicKey = publicKey.getEncoded();
14178            } catch (CertificateException e) {
14179                return -1;
14180            }
14181
14182            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14183
14184            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14185                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14186                        + " does not have the expected public key; ignoring");
14187                return -1;
14188            }
14189
14190            return pkg.applicationInfo.uid;
14191        }
14192    }
14193
14194    @Override
14195    public void finishPackageInstall(int token, boolean didLaunch) {
14196        enforceSystemOrRoot("Only the system is allowed to finish installs");
14197
14198        if (DEBUG_INSTALL) {
14199            Slog.v(TAG, "BM finishing package install for " + token);
14200        }
14201        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14202
14203        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14204        mHandler.sendMessage(msg);
14205    }
14206
14207    /**
14208     * Get the verification agent timeout.  Used for both the APK verifier and the
14209     * intent filter verifier.
14210     *
14211     * @return verification timeout in milliseconds
14212     */
14213    private long getVerificationTimeout() {
14214        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14215                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14216                DEFAULT_VERIFICATION_TIMEOUT);
14217    }
14218
14219    /**
14220     * Get the default verification agent response code.
14221     *
14222     * @return default verification response code
14223     */
14224    private int getDefaultVerificationResponse(UserHandle user) {
14225        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14226            return PackageManager.VERIFICATION_REJECT;
14227        }
14228        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14229                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14230                DEFAULT_VERIFICATION_RESPONSE);
14231    }
14232
14233    /**
14234     * Check whether or not package verification has been enabled.
14235     *
14236     * @return true if verification should be performed
14237     */
14238    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14239        if (!DEFAULT_VERIFY_ENABLE) {
14240            return false;
14241        }
14242
14243        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14244
14245        // Check if installing from ADB
14246        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14247            // Do not run verification in a test harness environment
14248            if (ActivityManager.isRunningInTestHarness()) {
14249                return false;
14250            }
14251            if (ensureVerifyAppsEnabled) {
14252                return true;
14253            }
14254            // Check if the developer does not want package verification for ADB installs
14255            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14256                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14257                return false;
14258            }
14259        } else {
14260            // only when not installed from ADB, skip verification for instant apps when
14261            // the installer and verifier are the same.
14262            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14263                if (mInstantAppInstallerActivity != null
14264                        && mInstantAppInstallerActivity.packageName.equals(
14265                                mRequiredVerifierPackage)) {
14266                    try {
14267                        mContext.getSystemService(AppOpsManager.class)
14268                                .checkPackage(installerUid, mRequiredVerifierPackage);
14269                        if (DEBUG_VERIFY) {
14270                            Slog.i(TAG, "disable verification for instant app");
14271                        }
14272                        return false;
14273                    } catch (SecurityException ignore) { }
14274                }
14275            }
14276        }
14277
14278        if (ensureVerifyAppsEnabled) {
14279            return true;
14280        }
14281
14282        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14283                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14284    }
14285
14286    @Override
14287    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14288            throws RemoteException {
14289        mContext.enforceCallingOrSelfPermission(
14290                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14291                "Only intentfilter verification agents can verify applications");
14292
14293        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14294        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14295                Binder.getCallingUid(), verificationCode, failedDomains);
14296        msg.arg1 = id;
14297        msg.obj = response;
14298        mHandler.sendMessage(msg);
14299    }
14300
14301    @Override
14302    public int getIntentVerificationStatus(String packageName, int userId) {
14303        final int callingUid = Binder.getCallingUid();
14304        if (UserHandle.getUserId(callingUid) != userId) {
14305            mContext.enforceCallingOrSelfPermission(
14306                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14307                    "getIntentVerificationStatus" + userId);
14308        }
14309        if (getInstantAppPackageName(callingUid) != null) {
14310            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14311        }
14312        synchronized (mPackages) {
14313            final PackageSetting ps = mSettings.mPackages.get(packageName);
14314            if (ps == null
14315                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14316                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14317            }
14318            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14319        }
14320    }
14321
14322    @Override
14323    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14324        mContext.enforceCallingOrSelfPermission(
14325                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14326
14327        boolean result = false;
14328        synchronized (mPackages) {
14329            final PackageSetting ps = mSettings.mPackages.get(packageName);
14330            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14331                return false;
14332            }
14333            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14334        }
14335        if (result) {
14336            scheduleWritePackageRestrictionsLocked(userId);
14337        }
14338        return result;
14339    }
14340
14341    @Override
14342    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14343            String packageName) {
14344        final int callingUid = Binder.getCallingUid();
14345        if (getInstantAppPackageName(callingUid) != null) {
14346            return ParceledListSlice.emptyList();
14347        }
14348        synchronized (mPackages) {
14349            final PackageSetting ps = mSettings.mPackages.get(packageName);
14350            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14351                return ParceledListSlice.emptyList();
14352            }
14353            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14354        }
14355    }
14356
14357    @Override
14358    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14359        if (TextUtils.isEmpty(packageName)) {
14360            return ParceledListSlice.emptyList();
14361        }
14362        final int callingUid = Binder.getCallingUid();
14363        final int callingUserId = UserHandle.getUserId(callingUid);
14364        synchronized (mPackages) {
14365            PackageParser.Package pkg = mPackages.get(packageName);
14366            if (pkg == null || pkg.activities == null) {
14367                return ParceledListSlice.emptyList();
14368            }
14369            if (pkg.mExtras == null) {
14370                return ParceledListSlice.emptyList();
14371            }
14372            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14373            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14374                return ParceledListSlice.emptyList();
14375            }
14376            final int count = pkg.activities.size();
14377            ArrayList<IntentFilter> result = new ArrayList<>();
14378            for (int n=0; n<count; n++) {
14379                PackageParser.Activity activity = pkg.activities.get(n);
14380                if (activity.intents != null && activity.intents.size() > 0) {
14381                    result.addAll(activity.intents);
14382                }
14383            }
14384            return new ParceledListSlice<>(result);
14385        }
14386    }
14387
14388    @Override
14389    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14390        mContext.enforceCallingOrSelfPermission(
14391                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14392        if (UserHandle.getCallingUserId() != userId) {
14393            mContext.enforceCallingOrSelfPermission(
14394                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14395        }
14396
14397        synchronized (mPackages) {
14398            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14399            if (packageName != null) {
14400                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14401                        packageName, userId);
14402            }
14403            return result;
14404        }
14405    }
14406
14407    @Override
14408    public String getDefaultBrowserPackageName(int userId) {
14409        if (UserHandle.getCallingUserId() != userId) {
14410            mContext.enforceCallingOrSelfPermission(
14411                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14412        }
14413        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14414            return null;
14415        }
14416        synchronized (mPackages) {
14417            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14418        }
14419    }
14420
14421    /**
14422     * Get the "allow unknown sources" setting.
14423     *
14424     * @return the current "allow unknown sources" setting
14425     */
14426    private int getUnknownSourcesSettings() {
14427        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14428                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14429                -1);
14430    }
14431
14432    @Override
14433    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14434        final int callingUid = Binder.getCallingUid();
14435        if (getInstantAppPackageName(callingUid) != null) {
14436            return;
14437        }
14438        // writer
14439        synchronized (mPackages) {
14440            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14441            if (targetPackageSetting == null
14442                    || filterAppAccessLPr(
14443                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14444                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14445            }
14446
14447            PackageSetting installerPackageSetting;
14448            if (installerPackageName != null) {
14449                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14450                if (installerPackageSetting == null) {
14451                    throw new IllegalArgumentException("Unknown installer package: "
14452                            + installerPackageName);
14453                }
14454            } else {
14455                installerPackageSetting = null;
14456            }
14457
14458            Signature[] callerSignature;
14459            Object obj = mSettings.getUserIdLPr(callingUid);
14460            if (obj != null) {
14461                if (obj instanceof SharedUserSetting) {
14462                    callerSignature =
14463                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14464                } else if (obj instanceof PackageSetting) {
14465                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14466                } else {
14467                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14468                }
14469            } else {
14470                throw new SecurityException("Unknown calling UID: " + callingUid);
14471            }
14472
14473            // Verify: can't set installerPackageName to a package that is
14474            // not signed with the same cert as the caller.
14475            if (installerPackageSetting != null) {
14476                if (compareSignatures(callerSignature,
14477                        installerPackageSetting.signatures.mSigningDetails.signatures)
14478                        != PackageManager.SIGNATURE_MATCH) {
14479                    throw new SecurityException(
14480                            "Caller does not have same cert as new installer package "
14481                            + installerPackageName);
14482                }
14483            }
14484
14485            // Verify: if target already has an installer package, it must
14486            // be signed with the same cert as the caller.
14487            if (targetPackageSetting.installerPackageName != null) {
14488                PackageSetting setting = mSettings.mPackages.get(
14489                        targetPackageSetting.installerPackageName);
14490                // If the currently set package isn't valid, then it's always
14491                // okay to change it.
14492                if (setting != null) {
14493                    if (compareSignatures(callerSignature,
14494                            setting.signatures.mSigningDetails.signatures)
14495                            != PackageManager.SIGNATURE_MATCH) {
14496                        throw new SecurityException(
14497                                "Caller does not have same cert as old installer package "
14498                                + targetPackageSetting.installerPackageName);
14499                    }
14500                }
14501            }
14502
14503            // Okay!
14504            targetPackageSetting.installerPackageName = installerPackageName;
14505            if (installerPackageName != null) {
14506                mSettings.mInstallerPackages.add(installerPackageName);
14507            }
14508            scheduleWriteSettingsLocked();
14509        }
14510    }
14511
14512    @Override
14513    public void setApplicationCategoryHint(String packageName, int categoryHint,
14514            String callerPackageName) {
14515        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14516            throw new SecurityException("Instant applications don't have access to this method");
14517        }
14518        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14519                callerPackageName);
14520        synchronized (mPackages) {
14521            PackageSetting ps = mSettings.mPackages.get(packageName);
14522            if (ps == null) {
14523                throw new IllegalArgumentException("Unknown target package " + packageName);
14524            }
14525            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14526                throw new IllegalArgumentException("Unknown target package " + packageName);
14527            }
14528            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14529                throw new IllegalArgumentException("Calling package " + callerPackageName
14530                        + " is not installer for " + packageName);
14531            }
14532
14533            if (ps.categoryHint != categoryHint) {
14534                ps.categoryHint = categoryHint;
14535                scheduleWriteSettingsLocked();
14536            }
14537        }
14538    }
14539
14540    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14541        // Queue up an async operation since the package installation may take a little while.
14542        mHandler.post(new Runnable() {
14543            public void run() {
14544                mHandler.removeCallbacks(this);
14545                 // Result object to be returned
14546                PackageInstalledInfo res = new PackageInstalledInfo();
14547                res.setReturnCode(currentStatus);
14548                res.uid = -1;
14549                res.pkg = null;
14550                res.removedInfo = null;
14551                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14552                    args.doPreInstall(res.returnCode);
14553                    synchronized (mInstallLock) {
14554                        installPackageTracedLI(args, res);
14555                    }
14556                    args.doPostInstall(res.returnCode, res.uid);
14557                }
14558
14559                // A restore should be performed at this point if (a) the install
14560                // succeeded, (b) the operation is not an update, and (c) the new
14561                // package has not opted out of backup participation.
14562                final boolean update = res.removedInfo != null
14563                        && res.removedInfo.removedPackage != null;
14564                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14565                boolean doRestore = !update
14566                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14567
14568                // Set up the post-install work request bookkeeping.  This will be used
14569                // and cleaned up by the post-install event handling regardless of whether
14570                // there's a restore pass performed.  Token values are >= 1.
14571                int token;
14572                if (mNextInstallToken < 0) mNextInstallToken = 1;
14573                token = mNextInstallToken++;
14574
14575                PostInstallData data = new PostInstallData(args, res);
14576                mRunningInstalls.put(token, data);
14577                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14578
14579                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14580                    // Pass responsibility to the Backup Manager.  It will perform a
14581                    // restore if appropriate, then pass responsibility back to the
14582                    // Package Manager to run the post-install observer callbacks
14583                    // and broadcasts.
14584                    IBackupManager bm = IBackupManager.Stub.asInterface(
14585                            ServiceManager.getService(Context.BACKUP_SERVICE));
14586                    if (bm != null) {
14587                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14588                                + " to BM for possible restore");
14589                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14590                        try {
14591                            // TODO: http://b/22388012
14592                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14593                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14594                            } else {
14595                                doRestore = false;
14596                            }
14597                        } catch (RemoteException e) {
14598                            // can't happen; the backup manager is local
14599                        } catch (Exception e) {
14600                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14601                            doRestore = false;
14602                        }
14603                    } else {
14604                        Slog.e(TAG, "Backup Manager not found!");
14605                        doRestore = false;
14606                    }
14607                }
14608
14609                if (!doRestore) {
14610                    // No restore possible, or the Backup Manager was mysteriously not
14611                    // available -- just fire the post-install work request directly.
14612                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14613
14614                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14615
14616                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14617                    mHandler.sendMessage(msg);
14618                }
14619            }
14620        });
14621    }
14622
14623    /**
14624     * Callback from PackageSettings whenever an app is first transitioned out of the
14625     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14626     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14627     * here whether the app is the target of an ongoing install, and only send the
14628     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14629     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14630     * handling.
14631     */
14632    void notifyFirstLaunch(final String packageName, final String installerPackage,
14633            final int userId) {
14634        // Serialize this with the rest of the install-process message chain.  In the
14635        // restore-at-install case, this Runnable will necessarily run before the
14636        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14637        // are coherent.  In the non-restore case, the app has already completed install
14638        // and been launched through some other means, so it is not in a problematic
14639        // state for observers to see the FIRST_LAUNCH signal.
14640        mHandler.post(new Runnable() {
14641            @Override
14642            public void run() {
14643                for (int i = 0; i < mRunningInstalls.size(); i++) {
14644                    final PostInstallData data = mRunningInstalls.valueAt(i);
14645                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14646                        continue;
14647                    }
14648                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14649                        // right package; but is it for the right user?
14650                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14651                            if (userId == data.res.newUsers[uIndex]) {
14652                                if (DEBUG_BACKUP) {
14653                                    Slog.i(TAG, "Package " + packageName
14654                                            + " being restored so deferring FIRST_LAUNCH");
14655                                }
14656                                return;
14657                            }
14658                        }
14659                    }
14660                }
14661                // didn't find it, so not being restored
14662                if (DEBUG_BACKUP) {
14663                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14664                }
14665                final boolean isInstantApp = isInstantApp(packageName, userId);
14666                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14667                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14668                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14669            }
14670        });
14671    }
14672
14673    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14674            int[] userIds, int[] instantUserIds) {
14675        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14676                installerPkg, null, userIds, instantUserIds);
14677    }
14678
14679    private abstract class HandlerParams {
14680        private static final int MAX_RETRIES = 4;
14681
14682        /**
14683         * Number of times startCopy() has been attempted and had a non-fatal
14684         * error.
14685         */
14686        private int mRetries = 0;
14687
14688        /** User handle for the user requesting the information or installation. */
14689        private final UserHandle mUser;
14690        String traceMethod;
14691        int traceCookie;
14692
14693        HandlerParams(UserHandle user) {
14694            mUser = user;
14695        }
14696
14697        UserHandle getUser() {
14698            return mUser;
14699        }
14700
14701        HandlerParams setTraceMethod(String traceMethod) {
14702            this.traceMethod = traceMethod;
14703            return this;
14704        }
14705
14706        HandlerParams setTraceCookie(int traceCookie) {
14707            this.traceCookie = traceCookie;
14708            return this;
14709        }
14710
14711        final boolean startCopy() {
14712            boolean res;
14713            try {
14714                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14715
14716                if (++mRetries > MAX_RETRIES) {
14717                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14718                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14719                    handleServiceError();
14720                    return false;
14721                } else {
14722                    handleStartCopy();
14723                    res = true;
14724                }
14725            } catch (RemoteException e) {
14726                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14727                mHandler.sendEmptyMessage(MCS_RECONNECT);
14728                res = false;
14729            }
14730            handleReturnCode();
14731            return res;
14732        }
14733
14734        final void serviceError() {
14735            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14736            handleServiceError();
14737            handleReturnCode();
14738        }
14739
14740        abstract void handleStartCopy() throws RemoteException;
14741        abstract void handleServiceError();
14742        abstract void handleReturnCode();
14743    }
14744
14745    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14746        for (File path : paths) {
14747            try {
14748                mcs.clearDirectory(path.getAbsolutePath());
14749            } catch (RemoteException e) {
14750            }
14751        }
14752    }
14753
14754    static class OriginInfo {
14755        /**
14756         * Location where install is coming from, before it has been
14757         * copied/renamed into place. This could be a single monolithic APK
14758         * file, or a cluster directory. This location may be untrusted.
14759         */
14760        final File file;
14761
14762        /**
14763         * Flag indicating that {@link #file} or {@link #cid} has already been
14764         * staged, meaning downstream users don't need to defensively copy the
14765         * contents.
14766         */
14767        final boolean staged;
14768
14769        /**
14770         * Flag indicating that {@link #file} or {@link #cid} is an already
14771         * installed app that is being moved.
14772         */
14773        final boolean existing;
14774
14775        final String resolvedPath;
14776        final File resolvedFile;
14777
14778        static OriginInfo fromNothing() {
14779            return new OriginInfo(null, false, false);
14780        }
14781
14782        static OriginInfo fromUntrustedFile(File file) {
14783            return new OriginInfo(file, false, false);
14784        }
14785
14786        static OriginInfo fromExistingFile(File file) {
14787            return new OriginInfo(file, false, true);
14788        }
14789
14790        static OriginInfo fromStagedFile(File file) {
14791            return new OriginInfo(file, true, false);
14792        }
14793
14794        private OriginInfo(File file, boolean staged, boolean existing) {
14795            this.file = file;
14796            this.staged = staged;
14797            this.existing = existing;
14798
14799            if (file != null) {
14800                resolvedPath = file.getAbsolutePath();
14801                resolvedFile = file;
14802            } else {
14803                resolvedPath = null;
14804                resolvedFile = null;
14805            }
14806        }
14807    }
14808
14809    static class MoveInfo {
14810        final int moveId;
14811        final String fromUuid;
14812        final String toUuid;
14813        final String packageName;
14814        final String dataAppName;
14815        final int appId;
14816        final String seinfo;
14817        final int targetSdkVersion;
14818
14819        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14820                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14821            this.moveId = moveId;
14822            this.fromUuid = fromUuid;
14823            this.toUuid = toUuid;
14824            this.packageName = packageName;
14825            this.dataAppName = dataAppName;
14826            this.appId = appId;
14827            this.seinfo = seinfo;
14828            this.targetSdkVersion = targetSdkVersion;
14829        }
14830    }
14831
14832    static class VerificationInfo {
14833        /** A constant used to indicate that a uid value is not present. */
14834        public static final int NO_UID = -1;
14835
14836        /** URI referencing where the package was downloaded from. */
14837        final Uri originatingUri;
14838
14839        /** HTTP referrer URI associated with the originatingURI. */
14840        final Uri referrer;
14841
14842        /** UID of the application that the install request originated from. */
14843        final int originatingUid;
14844
14845        /** UID of application requesting the install */
14846        final int installerUid;
14847
14848        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14849            this.originatingUri = originatingUri;
14850            this.referrer = referrer;
14851            this.originatingUid = originatingUid;
14852            this.installerUid = installerUid;
14853        }
14854    }
14855
14856    class InstallParams extends HandlerParams {
14857        final OriginInfo origin;
14858        final MoveInfo move;
14859        final IPackageInstallObserver2 observer;
14860        int installFlags;
14861        final String installerPackageName;
14862        final String volumeUuid;
14863        private InstallArgs mArgs;
14864        private int mRet;
14865        final String packageAbiOverride;
14866        final String[] grantedRuntimePermissions;
14867        final VerificationInfo verificationInfo;
14868        final PackageParser.SigningDetails signingDetails;
14869        final int installReason;
14870
14871        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14872                int installFlags, String installerPackageName, String volumeUuid,
14873                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14874                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14875            super(user);
14876            this.origin = origin;
14877            this.move = move;
14878            this.observer = observer;
14879            this.installFlags = installFlags;
14880            this.installerPackageName = installerPackageName;
14881            this.volumeUuid = volumeUuid;
14882            this.verificationInfo = verificationInfo;
14883            this.packageAbiOverride = packageAbiOverride;
14884            this.grantedRuntimePermissions = grantedPermissions;
14885            this.signingDetails = signingDetails;
14886            this.installReason = installReason;
14887        }
14888
14889        @Override
14890        public String toString() {
14891            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14892                    + " file=" + origin.file + "}";
14893        }
14894
14895        private int installLocationPolicy(PackageInfoLite pkgLite) {
14896            String packageName = pkgLite.packageName;
14897            int installLocation = pkgLite.installLocation;
14898            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14899            // reader
14900            synchronized (mPackages) {
14901                // Currently installed package which the new package is attempting to replace or
14902                // null if no such package is installed.
14903                PackageParser.Package installedPkg = mPackages.get(packageName);
14904                // Package which currently owns the data which the new package will own if installed.
14905                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14906                // will be null whereas dataOwnerPkg will contain information about the package
14907                // which was uninstalled while keeping its data.
14908                PackageParser.Package dataOwnerPkg = installedPkg;
14909                if (dataOwnerPkg  == null) {
14910                    PackageSetting ps = mSettings.mPackages.get(packageName);
14911                    if (ps != null) {
14912                        dataOwnerPkg = ps.pkg;
14913                    }
14914                }
14915
14916                if (dataOwnerPkg != null) {
14917                    // If installed, the package will get access to data left on the device by its
14918                    // predecessor. As a security measure, this is permited only if this is not a
14919                    // version downgrade or if the predecessor package is marked as debuggable and
14920                    // a downgrade is explicitly requested.
14921                    //
14922                    // On debuggable platform builds, downgrades are permitted even for
14923                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14924                    // not offer security guarantees and thus it's OK to disable some security
14925                    // mechanisms to make debugging/testing easier on those builds. However, even on
14926                    // debuggable builds downgrades of packages are permitted only if requested via
14927                    // installFlags. This is because we aim to keep the behavior of debuggable
14928                    // platform builds as close as possible to the behavior of non-debuggable
14929                    // platform builds.
14930                    final boolean downgradeRequested =
14931                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14932                    final boolean packageDebuggable =
14933                                (dataOwnerPkg.applicationInfo.flags
14934                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14935                    final boolean downgradePermitted =
14936                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14937                    if (!downgradePermitted) {
14938                        try {
14939                            checkDowngrade(dataOwnerPkg, pkgLite);
14940                        } catch (PackageManagerException e) {
14941                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14942                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14943                        }
14944                    }
14945                }
14946
14947                if (installedPkg != null) {
14948                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14949                        // Check for updated system application.
14950                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14951                            if (onSd) {
14952                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14953                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14954                            }
14955                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14956                        } else {
14957                            if (onSd) {
14958                                // Install flag overrides everything.
14959                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14960                            }
14961                            // If current upgrade specifies particular preference
14962                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14963                                // Application explicitly specified internal.
14964                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14965                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14966                                // App explictly prefers external. Let policy decide
14967                            } else {
14968                                // Prefer previous location
14969                                if (isExternal(installedPkg)) {
14970                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14971                                }
14972                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14973                            }
14974                        }
14975                    } else {
14976                        // Invalid install. Return error code
14977                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14978                    }
14979                }
14980            }
14981            // All the special cases have been taken care of.
14982            // Return result based on recommended install location.
14983            if (onSd) {
14984                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14985            }
14986            return pkgLite.recommendedInstallLocation;
14987        }
14988
14989        /*
14990         * Invoke remote method to get package information and install
14991         * location values. Override install location based on default
14992         * policy if needed and then create install arguments based
14993         * on the install location.
14994         */
14995        public void handleStartCopy() throws RemoteException {
14996            int ret = PackageManager.INSTALL_SUCCEEDED;
14997
14998            // If we're already staged, we've firmly committed to an install location
14999            if (origin.staged) {
15000                if (origin.file != null) {
15001                    installFlags |= PackageManager.INSTALL_INTERNAL;
15002                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15003                } else {
15004                    throw new IllegalStateException("Invalid stage location");
15005                }
15006            }
15007
15008            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15009            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15010            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15011            PackageInfoLite pkgLite = null;
15012
15013            if (onInt && onSd) {
15014                // Check if both bits are set.
15015                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15016                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15017            } else if (onSd && ephemeral) {
15018                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15019                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15020            } else {
15021                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15022                        packageAbiOverride);
15023
15024                if (DEBUG_INSTANT && ephemeral) {
15025                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15026                }
15027
15028                /*
15029                 * If we have too little free space, try to free cache
15030                 * before giving up.
15031                 */
15032                if (!origin.staged && pkgLite.recommendedInstallLocation
15033                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15034                    // TODO: focus freeing disk space on the target device
15035                    final StorageManager storage = StorageManager.from(mContext);
15036                    final long lowThreshold = storage.getStorageLowBytes(
15037                            Environment.getDataDirectory());
15038
15039                    final long sizeBytes = mContainerService.calculateInstalledSize(
15040                            origin.resolvedPath, packageAbiOverride);
15041
15042                    try {
15043                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15044                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15045                                installFlags, packageAbiOverride);
15046                    } catch (InstallerException e) {
15047                        Slog.w(TAG, "Failed to free cache", e);
15048                    }
15049
15050                    /*
15051                     * The cache free must have deleted the file we
15052                     * downloaded to install.
15053                     *
15054                     * TODO: fix the "freeCache" call to not delete
15055                     *       the file we care about.
15056                     */
15057                    if (pkgLite.recommendedInstallLocation
15058                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15059                        pkgLite.recommendedInstallLocation
15060                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15061                    }
15062                }
15063            }
15064
15065            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15066                int loc = pkgLite.recommendedInstallLocation;
15067                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15068                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15069                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15070                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15071                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15072                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15073                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15074                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15075                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15076                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15077                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15078                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15079                } else {
15080                    // Override with defaults if needed.
15081                    loc = installLocationPolicy(pkgLite);
15082                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15083                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15084                    } else if (!onSd && !onInt) {
15085                        // Override install location with flags
15086                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15087                            // Set the flag to install on external media.
15088                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15089                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15090                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15091                            if (DEBUG_INSTANT) {
15092                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15093                            }
15094                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15095                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15096                                    |PackageManager.INSTALL_INTERNAL);
15097                        } else {
15098                            // Make sure the flag for installing on external
15099                            // media is unset
15100                            installFlags |= PackageManager.INSTALL_INTERNAL;
15101                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15102                        }
15103                    }
15104                }
15105            }
15106
15107            final InstallArgs args = createInstallArgs(this);
15108            mArgs = args;
15109
15110            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15111                // TODO: http://b/22976637
15112                // Apps installed for "all" users use the device owner to verify the app
15113                UserHandle verifierUser = getUser();
15114                if (verifierUser == UserHandle.ALL) {
15115                    verifierUser = UserHandle.SYSTEM;
15116                }
15117
15118                /*
15119                 * Determine if we have any installed package verifiers. If we
15120                 * do, then we'll defer to them to verify the packages.
15121                 */
15122                final int requiredUid = mRequiredVerifierPackage == null ? -1
15123                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15124                                verifierUser.getIdentifier());
15125                final int installerUid =
15126                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15127                if (!origin.existing && requiredUid != -1
15128                        && isVerificationEnabled(
15129                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15130                    final Intent verification = new Intent(
15131                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15132                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15133                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15134                            PACKAGE_MIME_TYPE);
15135                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15136
15137                    // Query all live verifiers based on current user state
15138                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15139                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15140                            false /*allowDynamicSplits*/);
15141
15142                    if (DEBUG_VERIFY) {
15143                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15144                                + verification.toString() + " with " + pkgLite.verifiers.length
15145                                + " optional verifiers");
15146                    }
15147
15148                    final int verificationId = mPendingVerificationToken++;
15149
15150                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15151
15152                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15153                            installerPackageName);
15154
15155                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15156                            installFlags);
15157
15158                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15159                            pkgLite.packageName);
15160
15161                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15162                            pkgLite.versionCode);
15163
15164                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15165                            pkgLite.getLongVersionCode());
15166
15167                    if (verificationInfo != null) {
15168                        if (verificationInfo.originatingUri != null) {
15169                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15170                                    verificationInfo.originatingUri);
15171                        }
15172                        if (verificationInfo.referrer != null) {
15173                            verification.putExtra(Intent.EXTRA_REFERRER,
15174                                    verificationInfo.referrer);
15175                        }
15176                        if (verificationInfo.originatingUid >= 0) {
15177                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15178                                    verificationInfo.originatingUid);
15179                        }
15180                        if (verificationInfo.installerUid >= 0) {
15181                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15182                                    verificationInfo.installerUid);
15183                        }
15184                    }
15185
15186                    final PackageVerificationState verificationState = new PackageVerificationState(
15187                            requiredUid, args);
15188
15189                    mPendingVerification.append(verificationId, verificationState);
15190
15191                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15192                            receivers, verificationState);
15193
15194                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15195                    final long idleDuration = getVerificationTimeout();
15196
15197                    /*
15198                     * If any sufficient verifiers were listed in the package
15199                     * manifest, attempt to ask them.
15200                     */
15201                    if (sufficientVerifiers != null) {
15202                        final int N = sufficientVerifiers.size();
15203                        if (N == 0) {
15204                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15205                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15206                        } else {
15207                            for (int i = 0; i < N; i++) {
15208                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15209                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15210                                        verifierComponent.getPackageName(), idleDuration,
15211                                        verifierUser.getIdentifier(), false, "package verifier");
15212
15213                                final Intent sufficientIntent = new Intent(verification);
15214                                sufficientIntent.setComponent(verifierComponent);
15215                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15216                            }
15217                        }
15218                    }
15219
15220                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15221                            mRequiredVerifierPackage, receivers);
15222                    if (ret == PackageManager.INSTALL_SUCCEEDED
15223                            && mRequiredVerifierPackage != null) {
15224                        Trace.asyncTraceBegin(
15225                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15226                        /*
15227                         * Send the intent to the required verification agent,
15228                         * but only start the verification timeout after the
15229                         * target BroadcastReceivers have run.
15230                         */
15231                        verification.setComponent(requiredVerifierComponent);
15232                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15233                                mRequiredVerifierPackage, idleDuration,
15234                                verifierUser.getIdentifier(), false, "package verifier");
15235                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15236                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15237                                new BroadcastReceiver() {
15238                                    @Override
15239                                    public void onReceive(Context context, Intent intent) {
15240                                        final Message msg = mHandler
15241                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15242                                        msg.arg1 = verificationId;
15243                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15244                                    }
15245                                }, null, 0, null, null);
15246
15247                        /*
15248                         * We don't want the copy to proceed until verification
15249                         * succeeds, so null out this field.
15250                         */
15251                        mArgs = null;
15252                    }
15253                } else {
15254                    /*
15255                     * No package verification is enabled, so immediately start
15256                     * the remote call to initiate copy using temporary file.
15257                     */
15258                    ret = args.copyApk(mContainerService, true);
15259                }
15260            }
15261
15262            mRet = ret;
15263        }
15264
15265        @Override
15266        void handleReturnCode() {
15267            // If mArgs is null, then MCS couldn't be reached. When it
15268            // reconnects, it will try again to install. At that point, this
15269            // will succeed.
15270            if (mArgs != null) {
15271                processPendingInstall(mArgs, mRet);
15272            }
15273        }
15274
15275        @Override
15276        void handleServiceError() {
15277            mArgs = createInstallArgs(this);
15278            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15279        }
15280    }
15281
15282    private InstallArgs createInstallArgs(InstallParams params) {
15283        if (params.move != null) {
15284            return new MoveInstallArgs(params);
15285        } else {
15286            return new FileInstallArgs(params);
15287        }
15288    }
15289
15290    /**
15291     * Create args that describe an existing installed package. Typically used
15292     * when cleaning up old installs, or used as a move source.
15293     */
15294    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15295            String resourcePath, String[] instructionSets) {
15296        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15297    }
15298
15299    static abstract class InstallArgs {
15300        /** @see InstallParams#origin */
15301        final OriginInfo origin;
15302        /** @see InstallParams#move */
15303        final MoveInfo move;
15304
15305        final IPackageInstallObserver2 observer;
15306        // Always refers to PackageManager flags only
15307        final int installFlags;
15308        final String installerPackageName;
15309        final String volumeUuid;
15310        final UserHandle user;
15311        final String abiOverride;
15312        final String[] installGrantPermissions;
15313        /** If non-null, drop an async trace when the install completes */
15314        final String traceMethod;
15315        final int traceCookie;
15316        final PackageParser.SigningDetails signingDetails;
15317        final int installReason;
15318
15319        // The list of instruction sets supported by this app. This is currently
15320        // only used during the rmdex() phase to clean up resources. We can get rid of this
15321        // if we move dex files under the common app path.
15322        /* nullable */ String[] instructionSets;
15323
15324        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15325                int installFlags, String installerPackageName, String volumeUuid,
15326                UserHandle user, String[] instructionSets,
15327                String abiOverride, String[] installGrantPermissions,
15328                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15329                int installReason) {
15330            this.origin = origin;
15331            this.move = move;
15332            this.installFlags = installFlags;
15333            this.observer = observer;
15334            this.installerPackageName = installerPackageName;
15335            this.volumeUuid = volumeUuid;
15336            this.user = user;
15337            this.instructionSets = instructionSets;
15338            this.abiOverride = abiOverride;
15339            this.installGrantPermissions = installGrantPermissions;
15340            this.traceMethod = traceMethod;
15341            this.traceCookie = traceCookie;
15342            this.signingDetails = signingDetails;
15343            this.installReason = installReason;
15344        }
15345
15346        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15347        abstract int doPreInstall(int status);
15348
15349        /**
15350         * Rename package into final resting place. All paths on the given
15351         * scanned package should be updated to reflect the rename.
15352         */
15353        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15354        abstract int doPostInstall(int status, int uid);
15355
15356        /** @see PackageSettingBase#codePathString */
15357        abstract String getCodePath();
15358        /** @see PackageSettingBase#resourcePathString */
15359        abstract String getResourcePath();
15360
15361        // Need installer lock especially for dex file removal.
15362        abstract void cleanUpResourcesLI();
15363        abstract boolean doPostDeleteLI(boolean delete);
15364
15365        /**
15366         * Called before the source arguments are copied. This is used mostly
15367         * for MoveParams when it needs to read the source file to put it in the
15368         * destination.
15369         */
15370        int doPreCopy() {
15371            return PackageManager.INSTALL_SUCCEEDED;
15372        }
15373
15374        /**
15375         * Called after the source arguments are copied. This is used mostly for
15376         * MoveParams when it needs to read the source file to put it in the
15377         * destination.
15378         */
15379        int doPostCopy(int uid) {
15380            return PackageManager.INSTALL_SUCCEEDED;
15381        }
15382
15383        protected boolean isFwdLocked() {
15384            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15385        }
15386
15387        protected boolean isExternalAsec() {
15388            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15389        }
15390
15391        protected boolean isEphemeral() {
15392            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15393        }
15394
15395        UserHandle getUser() {
15396            return user;
15397        }
15398    }
15399
15400    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15401        if (!allCodePaths.isEmpty()) {
15402            if (instructionSets == null) {
15403                throw new IllegalStateException("instructionSet == null");
15404            }
15405            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15406            for (String codePath : allCodePaths) {
15407                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15408                    try {
15409                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15410                    } catch (InstallerException ignored) {
15411                    }
15412                }
15413            }
15414        }
15415    }
15416
15417    /**
15418     * Logic to handle installation of non-ASEC applications, including copying
15419     * and renaming logic.
15420     */
15421    class FileInstallArgs extends InstallArgs {
15422        private File codeFile;
15423        private File resourceFile;
15424
15425        // Example topology:
15426        // /data/app/com.example/base.apk
15427        // /data/app/com.example/split_foo.apk
15428        // /data/app/com.example/lib/arm/libfoo.so
15429        // /data/app/com.example/lib/arm64/libfoo.so
15430        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15431
15432        /** New install */
15433        FileInstallArgs(InstallParams params) {
15434            super(params.origin, params.move, params.observer, params.installFlags,
15435                    params.installerPackageName, params.volumeUuid,
15436                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15437                    params.grantedRuntimePermissions,
15438                    params.traceMethod, params.traceCookie, params.signingDetails,
15439                    params.installReason);
15440            if (isFwdLocked()) {
15441                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15442            }
15443        }
15444
15445        /** Existing install */
15446        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15447            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15448                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15449                    PackageManager.INSTALL_REASON_UNKNOWN);
15450            this.codeFile = (codePath != null) ? new File(codePath) : null;
15451            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15452        }
15453
15454        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15455            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15456            try {
15457                return doCopyApk(imcs, temp);
15458            } finally {
15459                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15460            }
15461        }
15462
15463        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15464            if (origin.staged) {
15465                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15466                codeFile = origin.file;
15467                resourceFile = origin.file;
15468                return PackageManager.INSTALL_SUCCEEDED;
15469            }
15470
15471            try {
15472                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15473                final File tempDir =
15474                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15475                codeFile = tempDir;
15476                resourceFile = tempDir;
15477            } catch (IOException e) {
15478                Slog.w(TAG, "Failed to create copy file: " + e);
15479                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15480            }
15481
15482            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15483                @Override
15484                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15485                    if (!FileUtils.isValidExtFilename(name)) {
15486                        throw new IllegalArgumentException("Invalid filename: " + name);
15487                    }
15488                    try {
15489                        final File file = new File(codeFile, name);
15490                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15491                                O_RDWR | O_CREAT, 0644);
15492                        Os.chmod(file.getAbsolutePath(), 0644);
15493                        return new ParcelFileDescriptor(fd);
15494                    } catch (ErrnoException e) {
15495                        throw new RemoteException("Failed to open: " + e.getMessage());
15496                    }
15497                }
15498            };
15499
15500            int ret = PackageManager.INSTALL_SUCCEEDED;
15501            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15502            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15503                Slog.e(TAG, "Failed to copy package");
15504                return ret;
15505            }
15506
15507            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15508            NativeLibraryHelper.Handle handle = null;
15509            try {
15510                handle = NativeLibraryHelper.Handle.create(codeFile);
15511                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15512                        abiOverride);
15513            } catch (IOException e) {
15514                Slog.e(TAG, "Copying native libraries failed", e);
15515                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15516            } finally {
15517                IoUtils.closeQuietly(handle);
15518            }
15519
15520            return ret;
15521        }
15522
15523        int doPreInstall(int status) {
15524            if (status != PackageManager.INSTALL_SUCCEEDED) {
15525                cleanUp();
15526            }
15527            return status;
15528        }
15529
15530        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15531            if (status != PackageManager.INSTALL_SUCCEEDED) {
15532                cleanUp();
15533                return false;
15534            }
15535
15536            final File targetDir = codeFile.getParentFile();
15537            final File beforeCodeFile = codeFile;
15538            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15539
15540            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15541            try {
15542                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15543            } catch (ErrnoException e) {
15544                Slog.w(TAG, "Failed to rename", e);
15545                return false;
15546            }
15547
15548            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15549                Slog.w(TAG, "Failed to restorecon");
15550                return false;
15551            }
15552
15553            // Reflect the rename internally
15554            codeFile = afterCodeFile;
15555            resourceFile = afterCodeFile;
15556
15557            // Reflect the rename in scanned details
15558            try {
15559                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15560            } catch (IOException e) {
15561                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15562                return false;
15563            }
15564            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15565                    afterCodeFile, pkg.baseCodePath));
15566            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15567                    afterCodeFile, pkg.splitCodePaths));
15568
15569            // Reflect the rename in app info
15570            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15571            pkg.setApplicationInfoCodePath(pkg.codePath);
15572            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15573            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15574            pkg.setApplicationInfoResourcePath(pkg.codePath);
15575            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15576            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15577
15578            return true;
15579        }
15580
15581        int doPostInstall(int status, int uid) {
15582            if (status != PackageManager.INSTALL_SUCCEEDED) {
15583                cleanUp();
15584            }
15585            return status;
15586        }
15587
15588        @Override
15589        String getCodePath() {
15590            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15591        }
15592
15593        @Override
15594        String getResourcePath() {
15595            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15596        }
15597
15598        private boolean cleanUp() {
15599            if (codeFile == null || !codeFile.exists()) {
15600                return false;
15601            }
15602
15603            removeCodePathLI(codeFile);
15604
15605            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15606                resourceFile.delete();
15607            }
15608
15609            return true;
15610        }
15611
15612        void cleanUpResourcesLI() {
15613            // Try enumerating all code paths before deleting
15614            List<String> allCodePaths = Collections.EMPTY_LIST;
15615            if (codeFile != null && codeFile.exists()) {
15616                try {
15617                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15618                    allCodePaths = pkg.getAllCodePaths();
15619                } catch (PackageParserException e) {
15620                    // Ignored; we tried our best
15621                }
15622            }
15623
15624            cleanUp();
15625            removeDexFiles(allCodePaths, instructionSets);
15626        }
15627
15628        boolean doPostDeleteLI(boolean delete) {
15629            // XXX err, shouldn't we respect the delete flag?
15630            cleanUpResourcesLI();
15631            return true;
15632        }
15633    }
15634
15635    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15636            PackageManagerException {
15637        if (copyRet < 0) {
15638            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15639                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15640                throw new PackageManagerException(copyRet, message);
15641            }
15642        }
15643    }
15644
15645    /**
15646     * Extract the StorageManagerService "container ID" from the full code path of an
15647     * .apk.
15648     */
15649    static String cidFromCodePath(String fullCodePath) {
15650        int eidx = fullCodePath.lastIndexOf("/");
15651        String subStr1 = fullCodePath.substring(0, eidx);
15652        int sidx = subStr1.lastIndexOf("/");
15653        return subStr1.substring(sidx+1, eidx);
15654    }
15655
15656    /**
15657     * Logic to handle movement of existing installed applications.
15658     */
15659    class MoveInstallArgs extends InstallArgs {
15660        private File codeFile;
15661        private File resourceFile;
15662
15663        /** New install */
15664        MoveInstallArgs(InstallParams params) {
15665            super(params.origin, params.move, params.observer, params.installFlags,
15666                    params.installerPackageName, params.volumeUuid,
15667                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15668                    params.grantedRuntimePermissions,
15669                    params.traceMethod, params.traceCookie, params.signingDetails,
15670                    params.installReason);
15671        }
15672
15673        int copyApk(IMediaContainerService imcs, boolean temp) {
15674            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15675                    + move.fromUuid + " to " + move.toUuid);
15676            synchronized (mInstaller) {
15677                try {
15678                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15679                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15680                } catch (InstallerException e) {
15681                    Slog.w(TAG, "Failed to move app", e);
15682                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15683                }
15684            }
15685
15686            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15687            resourceFile = codeFile;
15688            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15689
15690            return PackageManager.INSTALL_SUCCEEDED;
15691        }
15692
15693        int doPreInstall(int status) {
15694            if (status != PackageManager.INSTALL_SUCCEEDED) {
15695                cleanUp(move.toUuid);
15696            }
15697            return status;
15698        }
15699
15700        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15701            if (status != PackageManager.INSTALL_SUCCEEDED) {
15702                cleanUp(move.toUuid);
15703                return false;
15704            }
15705
15706            // Reflect the move in app info
15707            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15708            pkg.setApplicationInfoCodePath(pkg.codePath);
15709            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15710            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15711            pkg.setApplicationInfoResourcePath(pkg.codePath);
15712            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15713            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15714
15715            return true;
15716        }
15717
15718        int doPostInstall(int status, int uid) {
15719            if (status == PackageManager.INSTALL_SUCCEEDED) {
15720                cleanUp(move.fromUuid);
15721            } else {
15722                cleanUp(move.toUuid);
15723            }
15724            return status;
15725        }
15726
15727        @Override
15728        String getCodePath() {
15729            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15730        }
15731
15732        @Override
15733        String getResourcePath() {
15734            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15735        }
15736
15737        private boolean cleanUp(String volumeUuid) {
15738            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15739                    move.dataAppName);
15740            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15741            final int[] userIds = sUserManager.getUserIds();
15742            synchronized (mInstallLock) {
15743                // Clean up both app data and code
15744                // All package moves are frozen until finished
15745                for (int userId : userIds) {
15746                    try {
15747                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15748                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15749                    } catch (InstallerException e) {
15750                        Slog.w(TAG, String.valueOf(e));
15751                    }
15752                }
15753                removeCodePathLI(codeFile);
15754            }
15755            return true;
15756        }
15757
15758        void cleanUpResourcesLI() {
15759            throw new UnsupportedOperationException();
15760        }
15761
15762        boolean doPostDeleteLI(boolean delete) {
15763            throw new UnsupportedOperationException();
15764        }
15765    }
15766
15767    static String getAsecPackageName(String packageCid) {
15768        int idx = packageCid.lastIndexOf("-");
15769        if (idx == -1) {
15770            return packageCid;
15771        }
15772        return packageCid.substring(0, idx);
15773    }
15774
15775    // Utility method used to create code paths based on package name and available index.
15776    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15777        String idxStr = "";
15778        int idx = 1;
15779        // Fall back to default value of idx=1 if prefix is not
15780        // part of oldCodePath
15781        if (oldCodePath != null) {
15782            String subStr = oldCodePath;
15783            // Drop the suffix right away
15784            if (suffix != null && subStr.endsWith(suffix)) {
15785                subStr = subStr.substring(0, subStr.length() - suffix.length());
15786            }
15787            // If oldCodePath already contains prefix find out the
15788            // ending index to either increment or decrement.
15789            int sidx = subStr.lastIndexOf(prefix);
15790            if (sidx != -1) {
15791                subStr = subStr.substring(sidx + prefix.length());
15792                if (subStr != null) {
15793                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15794                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15795                    }
15796                    try {
15797                        idx = Integer.parseInt(subStr);
15798                        if (idx <= 1) {
15799                            idx++;
15800                        } else {
15801                            idx--;
15802                        }
15803                    } catch(NumberFormatException e) {
15804                    }
15805                }
15806            }
15807        }
15808        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15809        return prefix + idxStr;
15810    }
15811
15812    private File getNextCodePath(File targetDir, String packageName) {
15813        File result;
15814        SecureRandom random = new SecureRandom();
15815        byte[] bytes = new byte[16];
15816        do {
15817            random.nextBytes(bytes);
15818            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15819            result = new File(targetDir, packageName + "-" + suffix);
15820        } while (result.exists());
15821        return result;
15822    }
15823
15824    // Utility method that returns the relative package path with respect
15825    // to the installation directory. Like say for /data/data/com.test-1.apk
15826    // string com.test-1 is returned.
15827    static String deriveCodePathName(String codePath) {
15828        if (codePath == null) {
15829            return null;
15830        }
15831        final File codeFile = new File(codePath);
15832        final String name = codeFile.getName();
15833        if (codeFile.isDirectory()) {
15834            return name;
15835        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15836            final int lastDot = name.lastIndexOf('.');
15837            return name.substring(0, lastDot);
15838        } else {
15839            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15840            return null;
15841        }
15842    }
15843
15844    static class PackageInstalledInfo {
15845        String name;
15846        int uid;
15847        // The set of users that originally had this package installed.
15848        int[] origUsers;
15849        // The set of users that now have this package installed.
15850        int[] newUsers;
15851        PackageParser.Package pkg;
15852        int returnCode;
15853        String returnMsg;
15854        String installerPackageName;
15855        PackageRemovedInfo removedInfo;
15856        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15857
15858        public void setError(int code, String msg) {
15859            setReturnCode(code);
15860            setReturnMessage(msg);
15861            Slog.w(TAG, msg);
15862        }
15863
15864        public void setError(String msg, PackageParserException e) {
15865            setReturnCode(e.error);
15866            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15867            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15868            for (int i = 0; i < childCount; i++) {
15869                addedChildPackages.valueAt(i).setError(msg, e);
15870            }
15871            Slog.w(TAG, msg, e);
15872        }
15873
15874        public void setError(String msg, PackageManagerException e) {
15875            returnCode = e.error;
15876            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15877            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15878            for (int i = 0; i < childCount; i++) {
15879                addedChildPackages.valueAt(i).setError(msg, e);
15880            }
15881            Slog.w(TAG, msg, e);
15882        }
15883
15884        public void setReturnCode(int returnCode) {
15885            this.returnCode = returnCode;
15886            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15887            for (int i = 0; i < childCount; i++) {
15888                addedChildPackages.valueAt(i).returnCode = returnCode;
15889            }
15890        }
15891
15892        private void setReturnMessage(String returnMsg) {
15893            this.returnMsg = returnMsg;
15894            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15895            for (int i = 0; i < childCount; i++) {
15896                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15897            }
15898        }
15899
15900        // In some error cases we want to convey more info back to the observer
15901        String origPackage;
15902        String origPermission;
15903    }
15904
15905    /*
15906     * Install a non-existing package.
15907     */
15908    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15909            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15910            String volumeUuid, PackageInstalledInfo res, int installReason) {
15911        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15912
15913        // Remember this for later, in case we need to rollback this install
15914        String pkgName = pkg.packageName;
15915
15916        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15917
15918        synchronized(mPackages) {
15919            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15920            if (renamedPackage != null) {
15921                // A package with the same name is already installed, though
15922                // it has been renamed to an older name.  The package we
15923                // are trying to install should be installed as an update to
15924                // the existing one, but that has not been requested, so bail.
15925                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15926                        + " without first uninstalling package running as "
15927                        + renamedPackage);
15928                return;
15929            }
15930            if (mPackages.containsKey(pkgName)) {
15931                // Don't allow installation over an existing package with the same name.
15932                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15933                        + " without first uninstalling.");
15934                return;
15935            }
15936        }
15937
15938        try {
15939            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15940                    System.currentTimeMillis(), user);
15941
15942            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15943
15944            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15945                prepareAppDataAfterInstallLIF(newPackage);
15946
15947            } else {
15948                // Remove package from internal structures, but keep around any
15949                // data that might have already existed
15950                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15951                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15952            }
15953        } catch (PackageManagerException e) {
15954            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15955        }
15956
15957        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15958    }
15959
15960    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15961        try (DigestInputStream digestStream =
15962                new DigestInputStream(new FileInputStream(file), digest)) {
15963            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15964        }
15965    }
15966
15967    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15968            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15969            PackageInstalledInfo res, int installReason) {
15970        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15971
15972        final PackageParser.Package oldPackage;
15973        final PackageSetting ps;
15974        final String pkgName = pkg.packageName;
15975        final int[] allUsers;
15976        final int[] installedUsers;
15977
15978        synchronized(mPackages) {
15979            oldPackage = mPackages.get(pkgName);
15980            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15981
15982            // don't allow upgrade to target a release SDK from a pre-release SDK
15983            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15984                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15985            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15986                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15987            if (oldTargetsPreRelease
15988                    && !newTargetsPreRelease
15989                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15990                Slog.w(TAG, "Can't install package targeting released sdk");
15991                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15992                return;
15993            }
15994
15995            ps = mSettings.mPackages.get(pkgName);
15996
15997            // verify signatures are valid
15998            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15999            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16000                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16001                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16002                            "New package not signed by keys specified by upgrade-keysets: "
16003                                    + pkgName);
16004                    return;
16005                }
16006            } else {
16007
16008                // default to original signature matching
16009                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16010                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16011                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16012                            "New package has a different signature: " + pkgName);
16013                    return;
16014                }
16015            }
16016
16017            // don't allow a system upgrade unless the upgrade hash matches
16018            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16019                byte[] digestBytes = null;
16020                try {
16021                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16022                    updateDigest(digest, new File(pkg.baseCodePath));
16023                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16024                        for (String path : pkg.splitCodePaths) {
16025                            updateDigest(digest, new File(path));
16026                        }
16027                    }
16028                    digestBytes = digest.digest();
16029                } catch (NoSuchAlgorithmException | IOException e) {
16030                    res.setError(INSTALL_FAILED_INVALID_APK,
16031                            "Could not compute hash: " + pkgName);
16032                    return;
16033                }
16034                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16035                    res.setError(INSTALL_FAILED_INVALID_APK,
16036                            "New package fails restrict-update check: " + pkgName);
16037                    return;
16038                }
16039                // retain upgrade restriction
16040                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16041            }
16042
16043            // Check for shared user id changes
16044            String invalidPackageName =
16045                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16046            if (invalidPackageName != null) {
16047                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16048                        "Package " + invalidPackageName + " tried to change user "
16049                                + oldPackage.mSharedUserId);
16050                return;
16051            }
16052
16053            // check if the new package supports all of the abis which the old package supports
16054            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16055            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16056            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16057                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16058                        "Update to package " + pkgName + " doesn't support multi arch");
16059                return;
16060            }
16061
16062            // In case of rollback, remember per-user/profile install state
16063            allUsers = sUserManager.getUserIds();
16064            installedUsers = ps.queryInstalledUsers(allUsers, true);
16065
16066            // don't allow an upgrade from full to ephemeral
16067            if (isInstantApp) {
16068                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16069                    for (int currentUser : allUsers) {
16070                        if (!ps.getInstantApp(currentUser)) {
16071                            // can't downgrade from full to instant
16072                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16073                                    + " for user: " + currentUser);
16074                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16075                            return;
16076                        }
16077                    }
16078                } else if (!ps.getInstantApp(user.getIdentifier())) {
16079                    // can't downgrade from full to instant
16080                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16081                            + " for user: " + user.getIdentifier());
16082                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16083                    return;
16084                }
16085            }
16086        }
16087
16088        // Update what is removed
16089        res.removedInfo = new PackageRemovedInfo(this);
16090        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16091        res.removedInfo.removedPackage = oldPackage.packageName;
16092        res.removedInfo.installerPackageName = ps.installerPackageName;
16093        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16094        res.removedInfo.isUpdate = true;
16095        res.removedInfo.origUsers = installedUsers;
16096        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16097        for (int i = 0; i < installedUsers.length; i++) {
16098            final int userId = installedUsers[i];
16099            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16100        }
16101
16102        final int childCount = (oldPackage.childPackages != null)
16103                ? oldPackage.childPackages.size() : 0;
16104        for (int i = 0; i < childCount; i++) {
16105            boolean childPackageUpdated = false;
16106            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16107            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16108            if (res.addedChildPackages != null) {
16109                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16110                if (childRes != null) {
16111                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16112                    childRes.removedInfo.removedPackage = childPkg.packageName;
16113                    if (childPs != null) {
16114                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16115                    }
16116                    childRes.removedInfo.isUpdate = true;
16117                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16118                    childPackageUpdated = true;
16119                }
16120            }
16121            if (!childPackageUpdated) {
16122                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16123                childRemovedRes.removedPackage = childPkg.packageName;
16124                if (childPs != null) {
16125                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16126                }
16127                childRemovedRes.isUpdate = false;
16128                childRemovedRes.dataRemoved = true;
16129                synchronized (mPackages) {
16130                    if (childPs != null) {
16131                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16132                    }
16133                }
16134                if (res.removedInfo.removedChildPackages == null) {
16135                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16136                }
16137                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16138            }
16139        }
16140
16141        boolean sysPkg = (isSystemApp(oldPackage));
16142        if (sysPkg) {
16143            // Set the system/privileged/oem/vendor/product flags as needed
16144            final boolean privileged =
16145                    (oldPackage.applicationInfo.privateFlags
16146                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16147            final boolean oem =
16148                    (oldPackage.applicationInfo.privateFlags
16149                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16150            final boolean vendor =
16151                    (oldPackage.applicationInfo.privateFlags
16152                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16153            final boolean product =
16154                    (oldPackage.applicationInfo.privateFlags
16155                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16156            final @ParseFlags int systemParseFlags = parseFlags;
16157            final @ScanFlags int systemScanFlags = scanFlags
16158                    | SCAN_AS_SYSTEM
16159                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16160                    | (oem ? SCAN_AS_OEM : 0)
16161                    | (vendor ? SCAN_AS_VENDOR : 0)
16162                    | (product ? SCAN_AS_PRODUCT : 0);
16163
16164            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16165                    user, allUsers, installerPackageName, res, installReason);
16166        } else {
16167            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16168                    user, allUsers, installerPackageName, res, installReason);
16169        }
16170    }
16171
16172    @Override
16173    public List<String> getPreviousCodePaths(String packageName) {
16174        final int callingUid = Binder.getCallingUid();
16175        final List<String> result = new ArrayList<>();
16176        if (getInstantAppPackageName(callingUid) != null) {
16177            return result;
16178        }
16179        final PackageSetting ps = mSettings.mPackages.get(packageName);
16180        if (ps != null
16181                && ps.oldCodePaths != null
16182                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16183            result.addAll(ps.oldCodePaths);
16184        }
16185        return result;
16186    }
16187
16188    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16189            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16190            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16191            String installerPackageName, PackageInstalledInfo res, int installReason) {
16192        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16193                + deletedPackage);
16194
16195        String pkgName = deletedPackage.packageName;
16196        boolean deletedPkg = true;
16197        boolean addedPkg = false;
16198        boolean updatedSettings = false;
16199        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16200        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16201                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16202
16203        final long origUpdateTime = (pkg.mExtras != null)
16204                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16205
16206        // First delete the existing package while retaining the data directory
16207        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16208                res.removedInfo, true, pkg)) {
16209            // If the existing package wasn't successfully deleted
16210            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16211            deletedPkg = false;
16212        } else {
16213            // Successfully deleted the old package; proceed with replace.
16214
16215            // If deleted package lived in a container, give users a chance to
16216            // relinquish resources before killing.
16217            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16218                if (DEBUG_INSTALL) {
16219                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16220                }
16221                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16222                final ArrayList<String> pkgList = new ArrayList<String>(1);
16223                pkgList.add(deletedPackage.applicationInfo.packageName);
16224                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16225            }
16226
16227            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16228                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16229
16230            try {
16231                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16232                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16233                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16234                        installReason);
16235
16236                // Update the in-memory copy of the previous code paths.
16237                PackageSetting ps = mSettings.mPackages.get(pkgName);
16238                if (!killApp) {
16239                    if (ps.oldCodePaths == null) {
16240                        ps.oldCodePaths = new ArraySet<>();
16241                    }
16242                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16243                    if (deletedPackage.splitCodePaths != null) {
16244                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16245                    }
16246                } else {
16247                    ps.oldCodePaths = null;
16248                }
16249                if (ps.childPackageNames != null) {
16250                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16251                        final String childPkgName = ps.childPackageNames.get(i);
16252                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16253                        childPs.oldCodePaths = ps.oldCodePaths;
16254                    }
16255                }
16256                // set instant app status, but, only if it's explicitly specified
16257                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16258                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16259                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16260                prepareAppDataAfterInstallLIF(newPackage);
16261                addedPkg = true;
16262                mDexManager.notifyPackageUpdated(newPackage.packageName,
16263                        newPackage.baseCodePath, newPackage.splitCodePaths);
16264            } catch (PackageManagerException e) {
16265                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16266            }
16267        }
16268
16269        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16270            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16271
16272            // Revert all internal state mutations and added folders for the failed install
16273            if (addedPkg) {
16274                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16275                        res.removedInfo, true, null);
16276            }
16277
16278            // Restore the old package
16279            if (deletedPkg) {
16280                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16281                File restoreFile = new File(deletedPackage.codePath);
16282                // Parse old package
16283                boolean oldExternal = isExternal(deletedPackage);
16284                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16285                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16286                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16287                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16288                try {
16289                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16290                            null);
16291                } catch (PackageManagerException e) {
16292                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16293                            + e.getMessage());
16294                    return;
16295                }
16296
16297                synchronized (mPackages) {
16298                    // Ensure the installer package name up to date
16299                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16300
16301                    // Update permissions for restored package
16302                    mPermissionManager.updatePermissions(
16303                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16304                            mPermissionCallback);
16305
16306                    mSettings.writeLPr();
16307                }
16308
16309                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16310            }
16311        } else {
16312            synchronized (mPackages) {
16313                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16314                if (ps != null) {
16315                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16316                    if (res.removedInfo.removedChildPackages != null) {
16317                        final int childCount = res.removedInfo.removedChildPackages.size();
16318                        // Iterate in reverse as we may modify the collection
16319                        for (int i = childCount - 1; i >= 0; i--) {
16320                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16321                            if (res.addedChildPackages.containsKey(childPackageName)) {
16322                                res.removedInfo.removedChildPackages.removeAt(i);
16323                            } else {
16324                                PackageRemovedInfo childInfo = res.removedInfo
16325                                        .removedChildPackages.valueAt(i);
16326                                childInfo.removedForAllUsers = mPackages.get(
16327                                        childInfo.removedPackage) == null;
16328                            }
16329                        }
16330                    }
16331                }
16332            }
16333        }
16334    }
16335
16336    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16337            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16338            final @ScanFlags int scanFlags, UserHandle user,
16339            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16340            int installReason) {
16341        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16342                + ", old=" + deletedPackage);
16343
16344        final boolean disabledSystem;
16345
16346        // Remove existing system package
16347        removePackageLI(deletedPackage, true);
16348
16349        synchronized (mPackages) {
16350            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16351        }
16352        if (!disabledSystem) {
16353            // We didn't need to disable the .apk as a current system package,
16354            // which means we are replacing another update that is already
16355            // installed.  We need to make sure to delete the older one's .apk.
16356            res.removedInfo.args = createInstallArgsForExisting(0,
16357                    deletedPackage.applicationInfo.getCodePath(),
16358                    deletedPackage.applicationInfo.getResourcePath(),
16359                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16360        } else {
16361            res.removedInfo.args = null;
16362        }
16363
16364        // Successfully disabled the old package. Now proceed with re-installation
16365        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16366                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16367
16368        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16369        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16370                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16371
16372        PackageParser.Package newPackage = null;
16373        try {
16374            // Add the package to the internal data structures
16375            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16376
16377            // Set the update and install times
16378            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16379            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16380                    System.currentTimeMillis());
16381
16382            // Update the package dynamic state if succeeded
16383            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16384                // Now that the install succeeded make sure we remove data
16385                // directories for any child package the update removed.
16386                final int deletedChildCount = (deletedPackage.childPackages != null)
16387                        ? deletedPackage.childPackages.size() : 0;
16388                final int newChildCount = (newPackage.childPackages != null)
16389                        ? newPackage.childPackages.size() : 0;
16390                for (int i = 0; i < deletedChildCount; i++) {
16391                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16392                    boolean childPackageDeleted = true;
16393                    for (int j = 0; j < newChildCount; j++) {
16394                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16395                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16396                            childPackageDeleted = false;
16397                            break;
16398                        }
16399                    }
16400                    if (childPackageDeleted) {
16401                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16402                                deletedChildPkg.packageName);
16403                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16404                            PackageRemovedInfo removedChildRes = res.removedInfo
16405                                    .removedChildPackages.get(deletedChildPkg.packageName);
16406                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16407                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16408                        }
16409                    }
16410                }
16411
16412                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16413                        installReason);
16414                prepareAppDataAfterInstallLIF(newPackage);
16415
16416                mDexManager.notifyPackageUpdated(newPackage.packageName,
16417                            newPackage.baseCodePath, newPackage.splitCodePaths);
16418            }
16419        } catch (PackageManagerException e) {
16420            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16421            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16422        }
16423
16424        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16425            // Re installation failed. Restore old information
16426            // Remove new pkg information
16427            if (newPackage != null) {
16428                removeInstalledPackageLI(newPackage, true);
16429            }
16430            // Add back the old system package
16431            try {
16432                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16433            } catch (PackageManagerException e) {
16434                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16435            }
16436
16437            synchronized (mPackages) {
16438                if (disabledSystem) {
16439                    enableSystemPackageLPw(deletedPackage);
16440                }
16441
16442                // Ensure the installer package name up to date
16443                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16444
16445                // Update permissions for restored package
16446                mPermissionManager.updatePermissions(
16447                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16448                        mPermissionCallback);
16449
16450                mSettings.writeLPr();
16451            }
16452
16453            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16454                    + " after failed upgrade");
16455        }
16456    }
16457
16458    /**
16459     * Checks whether the parent or any of the child packages have a change shared
16460     * user. For a package to be a valid update the shred users of the parent and
16461     * the children should match. We may later support changing child shared users.
16462     * @param oldPkg The updated package.
16463     * @param newPkg The update package.
16464     * @return The shared user that change between the versions.
16465     */
16466    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16467            PackageParser.Package newPkg) {
16468        // Check parent shared user
16469        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16470            return newPkg.packageName;
16471        }
16472        // Check child shared users
16473        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16474        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16475        for (int i = 0; i < newChildCount; i++) {
16476            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16477            // If this child was present, did it have the same shared user?
16478            for (int j = 0; j < oldChildCount; j++) {
16479                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16480                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16481                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16482                    return newChildPkg.packageName;
16483                }
16484            }
16485        }
16486        return null;
16487    }
16488
16489    private void removeNativeBinariesLI(PackageSetting ps) {
16490        // Remove the lib path for the parent package
16491        if (ps != null) {
16492            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16493            // Remove the lib path for the child packages
16494            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16495            for (int i = 0; i < childCount; i++) {
16496                PackageSetting childPs = null;
16497                synchronized (mPackages) {
16498                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16499                }
16500                if (childPs != null) {
16501                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16502                            .legacyNativeLibraryPathString);
16503                }
16504            }
16505        }
16506    }
16507
16508    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16509        // Enable the parent package
16510        mSettings.enableSystemPackageLPw(pkg.packageName);
16511        // Enable the child packages
16512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16513        for (int i = 0; i < childCount; i++) {
16514            PackageParser.Package childPkg = pkg.childPackages.get(i);
16515            mSettings.enableSystemPackageLPw(childPkg.packageName);
16516        }
16517    }
16518
16519    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16520            PackageParser.Package newPkg) {
16521        // Disable the parent package (parent always replaced)
16522        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16523        // Disable the child packages
16524        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16525        for (int i = 0; i < childCount; i++) {
16526            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16527            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16528            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16529        }
16530        return disabled;
16531    }
16532
16533    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16534            String installerPackageName) {
16535        // Enable the parent package
16536        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16537        // Enable the child packages
16538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16539        for (int i = 0; i < childCount; i++) {
16540            PackageParser.Package childPkg = pkg.childPackages.get(i);
16541            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16542        }
16543    }
16544
16545    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16546            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16547        // Update the parent package setting
16548        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16549                res, user, installReason);
16550        // Update the child packages setting
16551        final int childCount = (newPackage.childPackages != null)
16552                ? newPackage.childPackages.size() : 0;
16553        for (int i = 0; i < childCount; i++) {
16554            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16555            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16556            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16557                    childRes.origUsers, childRes, user, installReason);
16558        }
16559    }
16560
16561    private void updateSettingsInternalLI(PackageParser.Package pkg,
16562            String installerPackageName, int[] allUsers, int[] installedForUsers,
16563            PackageInstalledInfo res, UserHandle user, int installReason) {
16564        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16565
16566        final String pkgName = pkg.packageName;
16567
16568        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16569        synchronized (mPackages) {
16570// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16571            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16572                    mPermissionCallback);
16573            // For system-bundled packages, we assume that installing an upgraded version
16574            // of the package implies that the user actually wants to run that new code,
16575            // so we enable the package.
16576            PackageSetting ps = mSettings.mPackages.get(pkgName);
16577            final int userId = user.getIdentifier();
16578            if (ps != null) {
16579                if (isSystemApp(pkg)) {
16580                    if (DEBUG_INSTALL) {
16581                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16582                    }
16583                    // Enable system package for requested users
16584                    if (res.origUsers != null) {
16585                        for (int origUserId : res.origUsers) {
16586                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16587                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16588                                        origUserId, installerPackageName);
16589                            }
16590                        }
16591                    }
16592                    // Also convey the prior install/uninstall state
16593                    if (allUsers != null && installedForUsers != null) {
16594                        for (int currentUserId : allUsers) {
16595                            final boolean installed = ArrayUtils.contains(
16596                                    installedForUsers, currentUserId);
16597                            if (DEBUG_INSTALL) {
16598                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16599                            }
16600                            ps.setInstalled(installed, currentUserId);
16601                        }
16602                        // these install state changes will be persisted in the
16603                        // upcoming call to mSettings.writeLPr().
16604                    }
16605                }
16606                // It's implied that when a user requests installation, they want the app to be
16607                // installed and enabled.
16608                if (userId != UserHandle.USER_ALL) {
16609                    ps.setInstalled(true, userId);
16610                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16611                } else {
16612                    for (int currentUserId : sUserManager.getUserIds()) {
16613                        ps.setInstalled(true, currentUserId);
16614                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16615                                installerPackageName);
16616                    }
16617                }
16618
16619                // When replacing an existing package, preserve the original install reason for all
16620                // users that had the package installed before.
16621                final Set<Integer> previousUserIds = new ArraySet<>();
16622                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16623                    final int installReasonCount = res.removedInfo.installReasons.size();
16624                    for (int i = 0; i < installReasonCount; i++) {
16625                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16626                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16627                        ps.setInstallReason(previousInstallReason, previousUserId);
16628                        previousUserIds.add(previousUserId);
16629                    }
16630                }
16631
16632                // Set install reason for users that are having the package newly installed.
16633                if (userId == UserHandle.USER_ALL) {
16634                    for (int currentUserId : sUserManager.getUserIds()) {
16635                        if (!previousUserIds.contains(currentUserId)) {
16636                            ps.setInstallReason(installReason, currentUserId);
16637                        }
16638                    }
16639                } else if (!previousUserIds.contains(userId)) {
16640                    ps.setInstallReason(installReason, userId);
16641                }
16642                mSettings.writeKernelMappingLPr(ps);
16643            }
16644            res.name = pkgName;
16645            res.uid = pkg.applicationInfo.uid;
16646            res.pkg = pkg;
16647            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16648            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16649            //to update install status
16650            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16651            mSettings.writeLPr();
16652            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16653        }
16654
16655        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16656    }
16657
16658    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16659        try {
16660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16661            installPackageLI(args, res);
16662        } finally {
16663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16664        }
16665    }
16666
16667    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16668        final int installFlags = args.installFlags;
16669        final String installerPackageName = args.installerPackageName;
16670        final String volumeUuid = args.volumeUuid;
16671        final File tmpPackageFile = new File(args.getCodePath());
16672        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16673        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16674                || (args.volumeUuid != null));
16675        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16676        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16677        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16678        final boolean virtualPreload =
16679                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16680        boolean replace = false;
16681        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16682        if (args.move != null) {
16683            // moving a complete application; perform an initial scan on the new install location
16684            scanFlags |= SCAN_INITIAL;
16685        }
16686        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16687            scanFlags |= SCAN_DONT_KILL_APP;
16688        }
16689        if (instantApp) {
16690            scanFlags |= SCAN_AS_INSTANT_APP;
16691        }
16692        if (fullApp) {
16693            scanFlags |= SCAN_AS_FULL_APP;
16694        }
16695        if (virtualPreload) {
16696            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16697        }
16698
16699        // Result object to be returned
16700        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16701        res.installerPackageName = installerPackageName;
16702
16703        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16704
16705        // Sanity check
16706        if (instantApp && (forwardLocked || onExternal)) {
16707            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16708                    + " external=" + onExternal);
16709            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16710            return;
16711        }
16712
16713        // Retrieve PackageSettings and parse package
16714        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16715                | PackageParser.PARSE_ENFORCE_CODE
16716                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16717                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16718                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16719        PackageParser pp = new PackageParser();
16720        pp.setSeparateProcesses(mSeparateProcesses);
16721        pp.setDisplayMetrics(mMetrics);
16722        pp.setCallback(mPackageParserCallback);
16723
16724        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16725        final PackageParser.Package pkg;
16726        try {
16727            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16728            DexMetadataHelper.validatePackageDexMetadata(pkg);
16729        } catch (PackageParserException e) {
16730            res.setError("Failed parse during installPackageLI", e);
16731            return;
16732        } finally {
16733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16734        }
16735
16736        // Instant apps have several additional install-time checks.
16737        if (instantApp) {
16738            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16739                Slog.w(TAG,
16740                        "Instant app package " + pkg.packageName + " does not target at least O");
16741                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16742                        "Instant app package must target at least O");
16743                return;
16744            }
16745            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16746                Slog.w(TAG, "Instant app package " + pkg.packageName
16747                        + " does not target targetSandboxVersion 2");
16748                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16749                        "Instant app package must use targetSandboxVersion 2");
16750                return;
16751            }
16752            if (pkg.mSharedUserId != null) {
16753                Slog.w(TAG, "Instant app package " + pkg.packageName
16754                        + " may not declare sharedUserId.");
16755                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16756                        "Instant app package may not declare a sharedUserId");
16757                return;
16758            }
16759        }
16760
16761        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16762            // Static shared libraries have synthetic package names
16763            renameStaticSharedLibraryPackage(pkg);
16764
16765            // No static shared libs on external storage
16766            if (onExternal) {
16767                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16768                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16769                        "Packages declaring static-shared libs cannot be updated");
16770                return;
16771            }
16772        }
16773
16774        // If we are installing a clustered package add results for the children
16775        if (pkg.childPackages != null) {
16776            synchronized (mPackages) {
16777                final int childCount = pkg.childPackages.size();
16778                for (int i = 0; i < childCount; i++) {
16779                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16780                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16781                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16782                    childRes.pkg = childPkg;
16783                    childRes.name = childPkg.packageName;
16784                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16785                    if (childPs != null) {
16786                        childRes.origUsers = childPs.queryInstalledUsers(
16787                                sUserManager.getUserIds(), true);
16788                    }
16789                    if ((mPackages.containsKey(childPkg.packageName))) {
16790                        childRes.removedInfo = new PackageRemovedInfo(this);
16791                        childRes.removedInfo.removedPackage = childPkg.packageName;
16792                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16793                    }
16794                    if (res.addedChildPackages == null) {
16795                        res.addedChildPackages = new ArrayMap<>();
16796                    }
16797                    res.addedChildPackages.put(childPkg.packageName, childRes);
16798                }
16799            }
16800        }
16801
16802        // If package doesn't declare API override, mark that we have an install
16803        // time CPU ABI override.
16804        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16805            pkg.cpuAbiOverride = args.abiOverride;
16806        }
16807
16808        String pkgName = res.name = pkg.packageName;
16809        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16810            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16811                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16812                return;
16813            }
16814        }
16815
16816        try {
16817            // either use what we've been given or parse directly from the APK
16818            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16819                pkg.setSigningDetails(args.signingDetails);
16820            } else {
16821                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16822            }
16823        } catch (PackageParserException e) {
16824            res.setError("Failed collect during installPackageLI", e);
16825            return;
16826        }
16827
16828        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16829                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16830            Slog.w(TAG, "Instant app package " + pkg.packageName
16831                    + " is not signed with at least APK Signature Scheme v2");
16832            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16833                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16834            return;
16835        }
16836
16837        // Get rid of all references to package scan path via parser.
16838        pp = null;
16839        String oldCodePath = null;
16840        boolean systemApp = false;
16841        synchronized (mPackages) {
16842            // Check if installing already existing package
16843            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16844                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16845                if (pkg.mOriginalPackages != null
16846                        && pkg.mOriginalPackages.contains(oldName)
16847                        && mPackages.containsKey(oldName)) {
16848                    // This package is derived from an original package,
16849                    // and this device has been updating from that original
16850                    // name.  We must continue using the original name, so
16851                    // rename the new package here.
16852                    pkg.setPackageName(oldName);
16853                    pkgName = pkg.packageName;
16854                    replace = true;
16855                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16856                            + oldName + " pkgName=" + pkgName);
16857                } else if (mPackages.containsKey(pkgName)) {
16858                    // This package, under its official name, already exists
16859                    // on the device; we should replace it.
16860                    replace = true;
16861                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16862                }
16863
16864                // Child packages are installed through the parent package
16865                if (pkg.parentPackage != null) {
16866                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16867                            "Package " + pkg.packageName + " is child of package "
16868                                    + pkg.parentPackage.parentPackage + ". Child packages "
16869                                    + "can be updated only through the parent package.");
16870                    return;
16871                }
16872
16873                if (replace) {
16874                    // Prevent apps opting out from runtime permissions
16875                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16876                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16877                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16878                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16879                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16880                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16881                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16882                                        + " doesn't support runtime permissions but the old"
16883                                        + " target SDK " + oldTargetSdk + " does.");
16884                        return;
16885                    }
16886                    // Prevent persistent apps from being updated
16887                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16888                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16889                                "Package " + oldPackage.packageName + " is a persistent app. "
16890                                        + "Persistent apps are not updateable.");
16891                        return;
16892                    }
16893                    // Prevent apps from downgrading their targetSandbox.
16894                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16895                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16896                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16897                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16898                                "Package " + pkg.packageName + " new target sandbox "
16899                                + newTargetSandbox + " is incompatible with the previous value of"
16900                                + oldTargetSandbox + ".");
16901                        return;
16902                    }
16903
16904                    // Prevent installing of child packages
16905                    if (oldPackage.parentPackage != null) {
16906                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16907                                "Package " + pkg.packageName + " is child of package "
16908                                        + oldPackage.parentPackage + ". Child packages "
16909                                        + "can be updated only through the parent package.");
16910                        return;
16911                    }
16912                }
16913            }
16914
16915            PackageSetting ps = mSettings.mPackages.get(pkgName);
16916            if (ps != null) {
16917                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16918
16919                // Static shared libs have same package with different versions where
16920                // we internally use a synthetic package name to allow multiple versions
16921                // of the same package, therefore we need to compare signatures against
16922                // the package setting for the latest library version.
16923                PackageSetting signatureCheckPs = ps;
16924                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16925                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16926                    if (libraryEntry != null) {
16927                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16928                    }
16929                }
16930
16931                // Quick sanity check that we're signed correctly if updating;
16932                // we'll check this again later when scanning, but we want to
16933                // bail early here before tripping over redefined permissions.
16934                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16935                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16936                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16937                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16938                                + pkg.packageName + " upgrade keys do not match the "
16939                                + "previously installed version");
16940                        return;
16941                    }
16942                } else {
16943                    try {
16944                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16945                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16946                        // We don't care about disabledPkgSetting on install for now.
16947                        final boolean compatMatch = verifySignatures(
16948                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16949                                compareRecover);
16950                        // The new KeySets will be re-added later in the scanning process.
16951                        if (compatMatch) {
16952                            synchronized (mPackages) {
16953                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16954                            }
16955                        }
16956                    } catch (PackageManagerException e) {
16957                        res.setError(e.error, e.getMessage());
16958                        return;
16959                    }
16960                }
16961
16962                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16963                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16964                    systemApp = (ps.pkg.applicationInfo.flags &
16965                            ApplicationInfo.FLAG_SYSTEM) != 0;
16966                }
16967                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16968            }
16969
16970            int N = pkg.permissions.size();
16971            for (int i = N-1; i >= 0; i--) {
16972                final PackageParser.Permission perm = pkg.permissions.get(i);
16973                final BasePermission bp =
16974                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16975
16976                // Don't allow anyone but the system to define ephemeral permissions.
16977                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16978                        && !systemApp) {
16979                    Slog.w(TAG, "Non-System package " + pkg.packageName
16980                            + " attempting to delcare ephemeral permission "
16981                            + perm.info.name + "; Removing ephemeral.");
16982                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16983                }
16984
16985                // Check whether the newly-scanned package wants to define an already-defined perm
16986                if (bp != null) {
16987                    // If the defining package is signed with our cert, it's okay.  This
16988                    // also includes the "updating the same package" case, of course.
16989                    // "updating same package" could also involve key-rotation.
16990                    final boolean sigsOk;
16991                    final String sourcePackageName = bp.getSourcePackageName();
16992                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16993                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16994                    if (sourcePackageName.equals(pkg.packageName)
16995                            && (ksms.shouldCheckUpgradeKeySetLocked(
16996                                    sourcePackageSetting, scanFlags))) {
16997                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16998                    } else {
16999
17000                        // in the event of signing certificate rotation, we need to see if the
17001                        // package's certificate has rotated from the current one, or if it is an
17002                        // older certificate with which the current is ok with sharing permissions
17003                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17004                                        pkg.mSigningDetails,
17005                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17006                            sigsOk = true;
17007                        } else if (pkg.mSigningDetails.checkCapability(
17008                                        sourcePackageSetting.signatures.mSigningDetails,
17009                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17010
17011                            // the scanned package checks out, has signing certificate rotation
17012                            // history, and is newer; bring it over
17013                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17014                            sigsOk = true;
17015                        } else {
17016                            sigsOk = false;
17017                        }
17018                    }
17019                    if (!sigsOk) {
17020                        // If the owning package is the system itself, we log but allow
17021                        // install to proceed; we fail the install on all other permission
17022                        // redefinitions.
17023                        if (!sourcePackageName.equals("android")) {
17024                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17025                                    + pkg.packageName + " attempting to redeclare permission "
17026                                    + perm.info.name + " already owned by " + sourcePackageName);
17027                            res.origPermission = perm.info.name;
17028                            res.origPackage = sourcePackageName;
17029                            return;
17030                        } else {
17031                            Slog.w(TAG, "Package " + pkg.packageName
17032                                    + " attempting to redeclare system permission "
17033                                    + perm.info.name + "; ignoring new declaration");
17034                            pkg.permissions.remove(i);
17035                        }
17036                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17037                        // Prevent apps to change protection level to dangerous from any other
17038                        // type as this would allow a privilege escalation where an app adds a
17039                        // normal/signature permission in other app's group and later redefines
17040                        // it as dangerous leading to the group auto-grant.
17041                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17042                                == PermissionInfo.PROTECTION_DANGEROUS) {
17043                            if (bp != null && !bp.isRuntime()) {
17044                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17045                                        + "non-runtime permission " + perm.info.name
17046                                        + " to runtime; keeping old protection level");
17047                                perm.info.protectionLevel = bp.getProtectionLevel();
17048                            }
17049                        }
17050                    }
17051                }
17052            }
17053        }
17054
17055        if (systemApp) {
17056            if (onExternal) {
17057                // Abort update; system app can't be replaced with app on sdcard
17058                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17059                        "Cannot install updates to system apps on sdcard");
17060                return;
17061            } else if (instantApp) {
17062                // Abort update; system app can't be replaced with an instant app
17063                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17064                        "Cannot update a system app with an instant app");
17065                return;
17066            }
17067        }
17068
17069        if (args.move != null) {
17070            // We did an in-place move, so dex is ready to roll
17071            scanFlags |= SCAN_NO_DEX;
17072            scanFlags |= SCAN_MOVE;
17073
17074            synchronized (mPackages) {
17075                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17076                if (ps == null) {
17077                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17078                            "Missing settings for moved package " + pkgName);
17079                }
17080
17081                // We moved the entire application as-is, so bring over the
17082                // previously derived ABI information.
17083                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17084                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17085            }
17086
17087        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17088            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17089            scanFlags |= SCAN_NO_DEX;
17090
17091            try {
17092                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17093                    args.abiOverride : pkg.cpuAbiOverride);
17094                final boolean extractNativeLibs = !pkg.isLibrary();
17095                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17096            } catch (PackageManagerException pme) {
17097                Slog.e(TAG, "Error deriving application ABI", pme);
17098                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17099                return;
17100            }
17101
17102            // Shared libraries for the package need to be updated.
17103            synchronized (mPackages) {
17104                try {
17105                    updateSharedLibrariesLPr(pkg, null);
17106                } catch (PackageManagerException e) {
17107                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17108                }
17109            }
17110        }
17111
17112        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17113            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17114            return;
17115        }
17116
17117        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17118            String apkPath = null;
17119            synchronized (mPackages) {
17120                // Note that if the attacker managed to skip verify setup, for example by tampering
17121                // with the package settings, upon reboot we will do full apk verification when
17122                // verity is not detected.
17123                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17124                if (ps != null && ps.isPrivileged()) {
17125                    apkPath = pkg.baseCodePath;
17126                }
17127            }
17128
17129            if (apkPath != null) {
17130                final VerityUtils.SetupResult result =
17131                        VerityUtils.generateApkVeritySetupData(apkPath);
17132                if (result.isOk()) {
17133                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17134                    FileDescriptor fd = result.getUnownedFileDescriptor();
17135                    try {
17136                        mInstaller.installApkVerity(apkPath, fd);
17137                    } catch (InstallerException e) {
17138                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17139                                "Failed to set up verity: " + e);
17140                        return;
17141                    } finally {
17142                        IoUtils.closeQuietly(fd);
17143                    }
17144                } else if (result.isFailed()) {
17145                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17146                    return;
17147                } else {
17148                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17149                    // reboot.
17150                }
17151            }
17152        }
17153
17154        if (!instantApp) {
17155            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17156        } else {
17157            if (DEBUG_DOMAIN_VERIFICATION) {
17158                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17159            }
17160        }
17161
17162        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17163                "installPackageLI")) {
17164            if (replace) {
17165                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17166                    // Static libs have a synthetic package name containing the version
17167                    // and cannot be updated as an update would get a new package name,
17168                    // unless this is the exact same version code which is useful for
17169                    // development.
17170                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17171                    if (existingPkg != null &&
17172                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17173                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17174                                + "static-shared libs cannot be updated");
17175                        return;
17176                    }
17177                }
17178                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17179                        installerPackageName, res, args.installReason);
17180            } else {
17181                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17182                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17183            }
17184        }
17185
17186        // Prepare the application profiles for the new code paths.
17187        // This needs to be done before invoking dexopt so that any install-time profile
17188        // can be used for optimizations.
17189        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17190
17191        // Check whether we need to dexopt the app.
17192        //
17193        // NOTE: it is IMPORTANT to call dexopt:
17194        //   - after doRename which will sync the package data from PackageParser.Package and its
17195        //     corresponding ApplicationInfo.
17196        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17197        //     uid of the application (pkg.applicationInfo.uid).
17198        //     This update happens in place!
17199        //
17200        // We only need to dexopt if the package meets ALL of the following conditions:
17201        //   1) it is not forward locked.
17202        //   2) it is not on on an external ASEC container.
17203        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17204        //
17205        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17206        // complete, so we skip this step during installation. Instead, we'll take extra time
17207        // the first time the instant app starts. It's preferred to do it this way to provide
17208        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17209        // middle of running an instant app. The default behaviour can be overridden
17210        // via gservices.
17211        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17212                && !forwardLocked
17213                && !pkg.applicationInfo.isExternalAsec()
17214                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17215                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17216
17217        if (performDexopt) {
17218            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17219            // Do not run PackageDexOptimizer through the local performDexOpt
17220            // method because `pkg` may not be in `mPackages` yet.
17221            //
17222            // Also, don't fail application installs if the dexopt step fails.
17223            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17224                    REASON_INSTALL,
17225                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17226                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17227            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17228                    null /* instructionSets */,
17229                    getOrCreateCompilerPackageStats(pkg),
17230                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17231                    dexoptOptions);
17232            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17233        }
17234
17235        // Notify BackgroundDexOptService that the package has been changed.
17236        // If this is an update of a package which used to fail to compile,
17237        // BackgroundDexOptService will remove it from its blacklist.
17238        // TODO: Layering violation
17239        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17240
17241        synchronized (mPackages) {
17242            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17243            if (ps != null) {
17244                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17245                ps.setUpdateAvailable(false /*updateAvailable*/);
17246            }
17247
17248            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17249            for (int i = 0; i < childCount; i++) {
17250                PackageParser.Package childPkg = pkg.childPackages.get(i);
17251                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17252                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17253                if (childPs != null) {
17254                    childRes.newUsers = childPs.queryInstalledUsers(
17255                            sUserManager.getUserIds(), true);
17256                }
17257            }
17258
17259            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17260                updateSequenceNumberLP(ps, res.newUsers);
17261                updateInstantAppInstallerLocked(pkgName);
17262            }
17263        }
17264    }
17265
17266    private void startIntentFilterVerifications(int userId, boolean replacing,
17267            PackageParser.Package pkg) {
17268        if (mIntentFilterVerifierComponent == null) {
17269            Slog.w(TAG, "No IntentFilter verification will not be done as "
17270                    + "there is no IntentFilterVerifier available!");
17271            return;
17272        }
17273
17274        final int verifierUid = getPackageUid(
17275                mIntentFilterVerifierComponent.getPackageName(),
17276                MATCH_DEBUG_TRIAGED_MISSING,
17277                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17278
17279        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17280        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17281        mHandler.sendMessage(msg);
17282
17283        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17284        for (int i = 0; i < childCount; i++) {
17285            PackageParser.Package childPkg = pkg.childPackages.get(i);
17286            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17287            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17288            mHandler.sendMessage(msg);
17289        }
17290    }
17291
17292    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17293            PackageParser.Package pkg) {
17294        int size = pkg.activities.size();
17295        if (size == 0) {
17296            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17297                    "No activity, so no need to verify any IntentFilter!");
17298            return;
17299        }
17300
17301        final boolean hasDomainURLs = hasDomainURLs(pkg);
17302        if (!hasDomainURLs) {
17303            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17304                    "No domain URLs, so no need to verify any IntentFilter!");
17305            return;
17306        }
17307
17308        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17309                + " if any IntentFilter from the " + size
17310                + " Activities needs verification ...");
17311
17312        int count = 0;
17313        final String packageName = pkg.packageName;
17314
17315        synchronized (mPackages) {
17316            // If this is a new install and we see that we've already run verification for this
17317            // package, we have nothing to do: it means the state was restored from backup.
17318            if (!replacing) {
17319                IntentFilterVerificationInfo ivi =
17320                        mSettings.getIntentFilterVerificationLPr(packageName);
17321                if (ivi != null) {
17322                    if (DEBUG_DOMAIN_VERIFICATION) {
17323                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17324                                + ivi.getStatusString());
17325                    }
17326                    return;
17327                }
17328            }
17329
17330            // If any filters need to be verified, then all need to be.
17331            boolean needToVerify = false;
17332            for (PackageParser.Activity a : pkg.activities) {
17333                for (ActivityIntentInfo filter : a.intents) {
17334                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17335                        if (DEBUG_DOMAIN_VERIFICATION) {
17336                            Slog.d(TAG,
17337                                    "Intent filter needs verification, so processing all filters");
17338                        }
17339                        needToVerify = true;
17340                        break;
17341                    }
17342                }
17343            }
17344
17345            if (needToVerify) {
17346                final int verificationId = mIntentFilterVerificationToken++;
17347                for (PackageParser.Activity a : pkg.activities) {
17348                    for (ActivityIntentInfo filter : a.intents) {
17349                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17350                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17351                                    "Verification needed for IntentFilter:" + filter.toString());
17352                            mIntentFilterVerifier.addOneIntentFilterVerification(
17353                                    verifierUid, userId, verificationId, filter, packageName);
17354                            count++;
17355                        }
17356                    }
17357                }
17358            }
17359        }
17360
17361        if (count > 0) {
17362            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17363                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17364                    +  " for userId:" + userId);
17365            mIntentFilterVerifier.startVerifications(userId);
17366        } else {
17367            if (DEBUG_DOMAIN_VERIFICATION) {
17368                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17369            }
17370        }
17371    }
17372
17373    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17374        final ComponentName cn  = filter.activity.getComponentName();
17375        final String packageName = cn.getPackageName();
17376
17377        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17378                packageName);
17379        if (ivi == null) {
17380            return true;
17381        }
17382        int status = ivi.getStatus();
17383        switch (status) {
17384            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17385            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17386                return true;
17387
17388            default:
17389                // Nothing to do
17390                return false;
17391        }
17392    }
17393
17394    private static boolean isMultiArch(ApplicationInfo info) {
17395        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17396    }
17397
17398    private static boolean isExternal(PackageParser.Package pkg) {
17399        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17400    }
17401
17402    private static boolean isExternal(PackageSetting ps) {
17403        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17404    }
17405
17406    private static boolean isSystemApp(PackageParser.Package pkg) {
17407        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17408    }
17409
17410    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17411        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17412    }
17413
17414    private static boolean isOemApp(PackageParser.Package pkg) {
17415        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17416    }
17417
17418    private static boolean isVendorApp(PackageParser.Package pkg) {
17419        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17420    }
17421
17422    private static boolean isProductApp(PackageParser.Package pkg) {
17423        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17424    }
17425
17426    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17427        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17428    }
17429
17430    private static boolean isSystemApp(PackageSetting ps) {
17431        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17432    }
17433
17434    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17435        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17436    }
17437
17438    private int packageFlagsToInstallFlags(PackageSetting ps) {
17439        int installFlags = 0;
17440        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17441            // This existing package was an external ASEC install when we have
17442            // the external flag without a UUID
17443            installFlags |= PackageManager.INSTALL_EXTERNAL;
17444        }
17445        if (ps.isForwardLocked()) {
17446            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17447        }
17448        return installFlags;
17449    }
17450
17451    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17452        if (isExternal(pkg)) {
17453            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17454                return mSettings.getExternalVersion();
17455            } else {
17456                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17457            }
17458        } else {
17459            return mSettings.getInternalVersion();
17460        }
17461    }
17462
17463    private void deleteTempPackageFiles() {
17464        final FilenameFilter filter = new FilenameFilter() {
17465            public boolean accept(File dir, String name) {
17466                return name.startsWith("vmdl") && name.endsWith(".tmp");
17467            }
17468        };
17469        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17470            file.delete();
17471        }
17472    }
17473
17474    @Override
17475    public void deletePackageAsUser(String packageName, int versionCode,
17476            IPackageDeleteObserver observer, int userId, int flags) {
17477        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17478                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17479    }
17480
17481    @Override
17482    public void deletePackageVersioned(VersionedPackage versionedPackage,
17483            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17484        final int callingUid = Binder.getCallingUid();
17485        mContext.enforceCallingOrSelfPermission(
17486                android.Manifest.permission.DELETE_PACKAGES, null);
17487        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17488        Preconditions.checkNotNull(versionedPackage);
17489        Preconditions.checkNotNull(observer);
17490        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17491                PackageManager.VERSION_CODE_HIGHEST,
17492                Long.MAX_VALUE, "versionCode must be >= -1");
17493
17494        final String packageName = versionedPackage.getPackageName();
17495        final long versionCode = versionedPackage.getLongVersionCode();
17496        final String internalPackageName;
17497        synchronized (mPackages) {
17498            // Normalize package name to handle renamed packages and static libs
17499            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17500        }
17501
17502        final int uid = Binder.getCallingUid();
17503        if (!isOrphaned(internalPackageName)
17504                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17505            try {
17506                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17507                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17508                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17509                observer.onUserActionRequired(intent);
17510            } catch (RemoteException re) {
17511            }
17512            return;
17513        }
17514        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17515        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17516        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17517            mContext.enforceCallingOrSelfPermission(
17518                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17519                    "deletePackage for user " + userId);
17520        }
17521
17522        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17523            try {
17524                observer.onPackageDeleted(packageName,
17525                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17526            } catch (RemoteException re) {
17527            }
17528            return;
17529        }
17530
17531        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17532            try {
17533                observer.onPackageDeleted(packageName,
17534                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17535            } catch (RemoteException re) {
17536            }
17537            return;
17538        }
17539
17540        if (DEBUG_REMOVE) {
17541            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17542                    + " deleteAllUsers: " + deleteAllUsers + " version="
17543                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17544                    ? "VERSION_CODE_HIGHEST" : versionCode));
17545        }
17546        // Queue up an async operation since the package deletion may take a little while.
17547        mHandler.post(new Runnable() {
17548            public void run() {
17549                mHandler.removeCallbacks(this);
17550                int returnCode;
17551                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17552                boolean doDeletePackage = true;
17553                if (ps != null) {
17554                    final boolean targetIsInstantApp =
17555                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17556                    doDeletePackage = !targetIsInstantApp
17557                            || canViewInstantApps;
17558                }
17559                if (doDeletePackage) {
17560                    if (!deleteAllUsers) {
17561                        returnCode = deletePackageX(internalPackageName, versionCode,
17562                                userId, deleteFlags);
17563                    } else {
17564                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17565                                internalPackageName, users);
17566                        // If nobody is blocking uninstall, proceed with delete for all users
17567                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17568                            returnCode = deletePackageX(internalPackageName, versionCode,
17569                                    userId, deleteFlags);
17570                        } else {
17571                            // Otherwise uninstall individually for users with blockUninstalls=false
17572                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17573                            for (int userId : users) {
17574                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17575                                    returnCode = deletePackageX(internalPackageName, versionCode,
17576                                            userId, userFlags);
17577                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17578                                        Slog.w(TAG, "Package delete failed for user " + userId
17579                                                + ", returnCode " + returnCode);
17580                                    }
17581                                }
17582                            }
17583                            // The app has only been marked uninstalled for certain users.
17584                            // We still need to report that delete was blocked
17585                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17586                        }
17587                    }
17588                } else {
17589                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17590                }
17591                try {
17592                    observer.onPackageDeleted(packageName, returnCode, null);
17593                } catch (RemoteException e) {
17594                    Log.i(TAG, "Observer no longer exists.");
17595                } //end catch
17596            } //end run
17597        });
17598    }
17599
17600    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17601        if (pkg.staticSharedLibName != null) {
17602            return pkg.manifestPackageName;
17603        }
17604        return pkg.packageName;
17605    }
17606
17607    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17608        // Handle renamed packages
17609        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17610        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17611
17612        // Is this a static library?
17613        LongSparseArray<SharedLibraryEntry> versionedLib =
17614                mStaticLibsByDeclaringPackage.get(packageName);
17615        if (versionedLib == null || versionedLib.size() <= 0) {
17616            return packageName;
17617        }
17618
17619        // Figure out which lib versions the caller can see
17620        LongSparseLongArray versionsCallerCanSee = null;
17621        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17622        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17623                && callingAppId != Process.ROOT_UID) {
17624            versionsCallerCanSee = new LongSparseLongArray();
17625            String libName = versionedLib.valueAt(0).info.getName();
17626            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17627            if (uidPackages != null) {
17628                for (String uidPackage : uidPackages) {
17629                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17630                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17631                    if (libIdx >= 0) {
17632                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17633                        versionsCallerCanSee.append(libVersion, libVersion);
17634                    }
17635                }
17636            }
17637        }
17638
17639        // Caller can see nothing - done
17640        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17641            return packageName;
17642        }
17643
17644        // Find the version the caller can see and the app version code
17645        SharedLibraryEntry highestVersion = null;
17646        final int versionCount = versionedLib.size();
17647        for (int i = 0; i < versionCount; i++) {
17648            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17649            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17650                    libEntry.info.getLongVersion()) < 0) {
17651                continue;
17652            }
17653            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17654            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17655                if (libVersionCode == versionCode) {
17656                    return libEntry.apk;
17657                }
17658            } else if (highestVersion == null) {
17659                highestVersion = libEntry;
17660            } else if (libVersionCode  > highestVersion.info
17661                    .getDeclaringPackage().getLongVersionCode()) {
17662                highestVersion = libEntry;
17663            }
17664        }
17665
17666        if (highestVersion != null) {
17667            return highestVersion.apk;
17668        }
17669
17670        return packageName;
17671    }
17672
17673    boolean isCallerVerifier(int callingUid) {
17674        final int callingUserId = UserHandle.getUserId(callingUid);
17675        return mRequiredVerifierPackage != null &&
17676                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17677    }
17678
17679    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17680        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17681              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17682            return true;
17683        }
17684        final int callingUserId = UserHandle.getUserId(callingUid);
17685        // If the caller installed the pkgName, then allow it to silently uninstall.
17686        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17687            return true;
17688        }
17689
17690        // Allow package verifier to silently uninstall.
17691        if (mRequiredVerifierPackage != null &&
17692                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17693            return true;
17694        }
17695
17696        // Allow package uninstaller to silently uninstall.
17697        if (mRequiredUninstallerPackage != null &&
17698                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17699            return true;
17700        }
17701
17702        // Allow storage manager to silently uninstall.
17703        if (mStorageManagerPackage != null &&
17704                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17705            return true;
17706        }
17707
17708        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17709        // uninstall for device owner provisioning.
17710        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17711                == PERMISSION_GRANTED) {
17712            return true;
17713        }
17714
17715        return false;
17716    }
17717
17718    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17719        int[] result = EMPTY_INT_ARRAY;
17720        for (int userId : userIds) {
17721            if (getBlockUninstallForUser(packageName, userId)) {
17722                result = ArrayUtils.appendInt(result, userId);
17723            }
17724        }
17725        return result;
17726    }
17727
17728    @Override
17729    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17730        final int callingUid = Binder.getCallingUid();
17731        if (getInstantAppPackageName(callingUid) != null
17732                && !isCallerSameApp(packageName, callingUid)) {
17733            return false;
17734        }
17735        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17736    }
17737
17738    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17739        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17740                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17741        try {
17742            if (dpm != null) {
17743                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17744                        /* callingUserOnly =*/ false);
17745                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17746                        : deviceOwnerComponentName.getPackageName();
17747                // Does the package contains the device owner?
17748                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17749                // this check is probably not needed, since DO should be registered as a device
17750                // admin on some user too. (Original bug for this: b/17657954)
17751                if (packageName.equals(deviceOwnerPackageName)) {
17752                    return true;
17753                }
17754                // Does it contain a device admin for any user?
17755                int[] users;
17756                if (userId == UserHandle.USER_ALL) {
17757                    users = sUserManager.getUserIds();
17758                } else {
17759                    users = new int[]{userId};
17760                }
17761                for (int i = 0; i < users.length; ++i) {
17762                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17763                        return true;
17764                    }
17765                }
17766            }
17767        } catch (RemoteException e) {
17768        }
17769        return false;
17770    }
17771
17772    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17773        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17774    }
17775
17776    /**
17777     *  This method is an internal method that could be get invoked either
17778     *  to delete an installed package or to clean up a failed installation.
17779     *  After deleting an installed package, a broadcast is sent to notify any
17780     *  listeners that the package has been removed. For cleaning up a failed
17781     *  installation, the broadcast is not necessary since the package's
17782     *  installation wouldn't have sent the initial broadcast either
17783     *  The key steps in deleting a package are
17784     *  deleting the package information in internal structures like mPackages,
17785     *  deleting the packages base directories through installd
17786     *  updating mSettings to reflect current status
17787     *  persisting settings for later use
17788     *  sending a broadcast if necessary
17789     */
17790    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17791        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17792        final boolean res;
17793
17794        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17795                ? UserHandle.USER_ALL : userId;
17796
17797        if (isPackageDeviceAdmin(packageName, removeUser)) {
17798            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17799            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17800        }
17801
17802        PackageSetting uninstalledPs = null;
17803        PackageParser.Package pkg = null;
17804
17805        // for the uninstall-updates case and restricted profiles, remember the per-
17806        // user handle installed state
17807        int[] allUsers;
17808        synchronized (mPackages) {
17809            uninstalledPs = mSettings.mPackages.get(packageName);
17810            if (uninstalledPs == null) {
17811                Slog.w(TAG, "Not removing non-existent package " + packageName);
17812                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17813            }
17814
17815            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17816                    && uninstalledPs.versionCode != versionCode) {
17817                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17818                        + uninstalledPs.versionCode + " != " + versionCode);
17819                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17820            }
17821
17822            // Static shared libs can be declared by any package, so let us not
17823            // allow removing a package if it provides a lib others depend on.
17824            pkg = mPackages.get(packageName);
17825
17826            allUsers = sUserManager.getUserIds();
17827
17828            if (pkg != null && pkg.staticSharedLibName != null) {
17829                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17830                        pkg.staticSharedLibVersion);
17831                if (libEntry != null) {
17832                    for (int currUserId : allUsers) {
17833                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17834                            continue;
17835                        }
17836                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17837                                libEntry.info, 0, currUserId);
17838                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17839                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17840                                    + " hosting lib " + libEntry.info.getName() + " version "
17841                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17842                                    + " for user " + currUserId);
17843                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17844                        }
17845                    }
17846                }
17847            }
17848
17849            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17850        }
17851
17852        final int freezeUser;
17853        if (isUpdatedSystemApp(uninstalledPs)
17854                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17855            // We're downgrading a system app, which will apply to all users, so
17856            // freeze them all during the downgrade
17857            freezeUser = UserHandle.USER_ALL;
17858        } else {
17859            freezeUser = removeUser;
17860        }
17861
17862        synchronized (mInstallLock) {
17863            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17864            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17865                    deleteFlags, "deletePackageX")) {
17866                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17867                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17868            }
17869            synchronized (mPackages) {
17870                if (res) {
17871                    if (pkg != null) {
17872                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17873                    }
17874                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17875                    updateInstantAppInstallerLocked(packageName);
17876                }
17877            }
17878        }
17879
17880        if (res) {
17881            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17882            info.sendPackageRemovedBroadcasts(killApp);
17883            info.sendSystemPackageUpdatedBroadcasts();
17884            info.sendSystemPackageAppearedBroadcasts();
17885        }
17886        // Force a gc here.
17887        Runtime.getRuntime().gc();
17888        // Delete the resources here after sending the broadcast to let
17889        // other processes clean up before deleting resources.
17890        if (info.args != null) {
17891            synchronized (mInstallLock) {
17892                info.args.doPostDeleteLI(true);
17893            }
17894        }
17895
17896        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17897    }
17898
17899    static class PackageRemovedInfo {
17900        final PackageSender packageSender;
17901        String removedPackage;
17902        String installerPackageName;
17903        int uid = -1;
17904        int removedAppId = -1;
17905        int[] origUsers;
17906        int[] removedUsers = null;
17907        int[] broadcastUsers = null;
17908        int[] instantUserIds = null;
17909        SparseArray<Integer> installReasons;
17910        boolean isRemovedPackageSystemUpdate = false;
17911        boolean isUpdate;
17912        boolean dataRemoved;
17913        boolean removedForAllUsers;
17914        boolean isStaticSharedLib;
17915        // Clean up resources deleted packages.
17916        InstallArgs args = null;
17917        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17918        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17919
17920        PackageRemovedInfo(PackageSender packageSender) {
17921            this.packageSender = packageSender;
17922        }
17923
17924        void sendPackageRemovedBroadcasts(boolean killApp) {
17925            sendPackageRemovedBroadcastInternal(killApp);
17926            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17927            for (int i = 0; i < childCount; i++) {
17928                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17929                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17930            }
17931        }
17932
17933        void sendSystemPackageUpdatedBroadcasts() {
17934            if (isRemovedPackageSystemUpdate) {
17935                sendSystemPackageUpdatedBroadcastsInternal();
17936                final int childCount = (removedChildPackages != null)
17937                        ? removedChildPackages.size() : 0;
17938                for (int i = 0; i < childCount; i++) {
17939                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17940                    if (childInfo.isRemovedPackageSystemUpdate) {
17941                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17942                    }
17943                }
17944            }
17945        }
17946
17947        void sendSystemPackageAppearedBroadcasts() {
17948            final int packageCount = (appearedChildPackages != null)
17949                    ? appearedChildPackages.size() : 0;
17950            for (int i = 0; i < packageCount; i++) {
17951                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17952                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17953                    true /*sendBootCompleted*/, false /*startReceiver*/,
17954                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17955            }
17956        }
17957
17958        private void sendSystemPackageUpdatedBroadcastsInternal() {
17959            Bundle extras = new Bundle(2);
17960            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17961            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17962            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17963                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17964            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17965                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17966            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17967                null, null, 0, removedPackage, null, null, null);
17968            if (installerPackageName != null) {
17969                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17970                        removedPackage, extras, 0 /*flags*/,
17971                        installerPackageName, null, null, null);
17972                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17973                        removedPackage, extras, 0 /*flags*/,
17974                        installerPackageName, null, null, null);
17975            }
17976        }
17977
17978        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17979            // Don't send static shared library removal broadcasts as these
17980            // libs are visible only the the apps that depend on them an one
17981            // cannot remove the library if it has a dependency.
17982            if (isStaticSharedLib) {
17983                return;
17984            }
17985            Bundle extras = new Bundle(2);
17986            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17987            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17988            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17989            if (isUpdate || isRemovedPackageSystemUpdate) {
17990                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17991            }
17992            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17993            if (removedPackage != null) {
17994                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17995                    removedPackage, extras, 0, null /*targetPackage*/, null,
17996                    broadcastUsers, instantUserIds);
17997                if (installerPackageName != null) {
17998                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17999                            removedPackage, extras, 0 /*flags*/,
18000                            installerPackageName, null, broadcastUsers, instantUserIds);
18001                }
18002                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18003                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18004                        removedPackage, extras,
18005                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18006                        null, null, broadcastUsers, instantUserIds);
18007                    packageSender.notifyPackageRemoved(removedPackage);
18008                }
18009            }
18010            if (removedAppId >= 0) {
18011                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18012                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18013                    null, null, broadcastUsers, instantUserIds);
18014            }
18015        }
18016
18017        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18018            removedUsers = userIds;
18019            if (removedUsers == null) {
18020                broadcastUsers = null;
18021                return;
18022            }
18023
18024            broadcastUsers = EMPTY_INT_ARRAY;
18025            instantUserIds = EMPTY_INT_ARRAY;
18026            for (int i = userIds.length - 1; i >= 0; --i) {
18027                final int userId = userIds[i];
18028                if (deletedPackageSetting.getInstantApp(userId)) {
18029                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18030                } else {
18031                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18032                }
18033            }
18034        }
18035    }
18036
18037    /*
18038     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18039     * flag is not set, the data directory is removed as well.
18040     * make sure this flag is set for partially installed apps. If not its meaningless to
18041     * delete a partially installed application.
18042     */
18043    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18044            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18045        String packageName = ps.name;
18046        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18047        // Retrieve object to delete permissions for shared user later on
18048        final PackageParser.Package deletedPkg;
18049        final PackageSetting deletedPs;
18050        // reader
18051        synchronized (mPackages) {
18052            deletedPkg = mPackages.get(packageName);
18053            deletedPs = mSettings.mPackages.get(packageName);
18054            if (outInfo != null) {
18055                outInfo.removedPackage = packageName;
18056                outInfo.installerPackageName = ps.installerPackageName;
18057                outInfo.isStaticSharedLib = deletedPkg != null
18058                        && deletedPkg.staticSharedLibName != null;
18059                outInfo.populateUsers(deletedPs == null ? null
18060                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18061            }
18062        }
18063
18064        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18065
18066        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18067            final PackageParser.Package resolvedPkg;
18068            if (deletedPkg != null) {
18069                resolvedPkg = deletedPkg;
18070            } else {
18071                // We don't have a parsed package when it lives on an ejected
18072                // adopted storage device, so fake something together
18073                resolvedPkg = new PackageParser.Package(ps.name);
18074                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18075            }
18076            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18077                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18078            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18079            if (outInfo != null) {
18080                outInfo.dataRemoved = true;
18081            }
18082            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18083        }
18084
18085        int removedAppId = -1;
18086
18087        // writer
18088        synchronized (mPackages) {
18089            boolean installedStateChanged = false;
18090            if (deletedPs != null) {
18091                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18092                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18093                    clearDefaultBrowserIfNeeded(packageName);
18094                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18095                    removedAppId = mSettings.removePackageLPw(packageName);
18096                    if (outInfo != null) {
18097                        outInfo.removedAppId = removedAppId;
18098                    }
18099                    mPermissionManager.updatePermissions(
18100                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18101                    if (deletedPs.sharedUser != null) {
18102                        // Remove permissions associated with package. Since runtime
18103                        // permissions are per user we have to kill the removed package
18104                        // or packages running under the shared user of the removed
18105                        // package if revoking the permissions requested only by the removed
18106                        // package is successful and this causes a change in gids.
18107                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18108                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18109                                    userId);
18110                            if (userIdToKill == UserHandle.USER_ALL
18111                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18112                                // If gids changed for this user, kill all affected packages.
18113                                mHandler.post(new Runnable() {
18114                                    @Override
18115                                    public void run() {
18116                                        // This has to happen with no lock held.
18117                                        killApplication(deletedPs.name, deletedPs.appId,
18118                                                KILL_APP_REASON_GIDS_CHANGED);
18119                                    }
18120                                });
18121                                break;
18122                            }
18123                        }
18124                    }
18125                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18126                }
18127                // make sure to preserve per-user disabled state if this removal was just
18128                // a downgrade of a system app to the factory package
18129                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18130                    if (DEBUG_REMOVE) {
18131                        Slog.d(TAG, "Propagating install state across downgrade");
18132                    }
18133                    for (int userId : allUserHandles) {
18134                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18135                        if (DEBUG_REMOVE) {
18136                            Slog.d(TAG, "    user " + userId + " => " + installed);
18137                        }
18138                        if (installed != ps.getInstalled(userId)) {
18139                            installedStateChanged = true;
18140                        }
18141                        ps.setInstalled(installed, userId);
18142                    }
18143                }
18144            }
18145            // can downgrade to reader
18146            if (writeSettings) {
18147                // Save settings now
18148                mSettings.writeLPr();
18149            }
18150            if (installedStateChanged) {
18151                mSettings.writeKernelMappingLPr(ps);
18152            }
18153        }
18154        if (removedAppId != -1) {
18155            // A user ID was deleted here. Go through all users and remove it
18156            // from KeyStore.
18157            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18158        }
18159    }
18160
18161    static boolean locationIsPrivileged(String path) {
18162        try {
18163            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18164            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18165            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18166            return path.startsWith(privilegedAppDir.getCanonicalPath())
18167                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18168                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18169        } catch (IOException e) {
18170            Slog.e(TAG, "Unable to access code path " + path);
18171        }
18172        return false;
18173    }
18174
18175    static boolean locationIsOem(String path) {
18176        try {
18177            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18178        } catch (IOException e) {
18179            Slog.e(TAG, "Unable to access code path " + path);
18180        }
18181        return false;
18182    }
18183
18184    static boolean locationIsVendor(String path) {
18185        try {
18186            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18187        } catch (IOException e) {
18188            Slog.e(TAG, "Unable to access code path " + path);
18189        }
18190        return false;
18191    }
18192
18193    static boolean locationIsProduct(String path) {
18194        try {
18195            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18196        } catch (IOException e) {
18197            Slog.e(TAG, "Unable to access code path " + path);
18198        }
18199        return false;
18200    }
18201
18202    /*
18203     * Tries to delete system package.
18204     */
18205    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18206            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18207            boolean writeSettings) {
18208        if (deletedPs.parentPackageName != null) {
18209            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18210            return false;
18211        }
18212
18213        final boolean applyUserRestrictions
18214                = (allUserHandles != null) && (outInfo.origUsers != null);
18215        final PackageSetting disabledPs;
18216        // Confirm if the system package has been updated
18217        // An updated system app can be deleted. This will also have to restore
18218        // the system pkg from system partition
18219        // reader
18220        synchronized (mPackages) {
18221            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18222        }
18223
18224        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18225                + " disabledPs=" + disabledPs);
18226
18227        if (disabledPs == null) {
18228            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18229            return false;
18230        } else if (DEBUG_REMOVE) {
18231            Slog.d(TAG, "Deleting system pkg from data partition");
18232        }
18233
18234        if (DEBUG_REMOVE) {
18235            if (applyUserRestrictions) {
18236                Slog.d(TAG, "Remembering install states:");
18237                for (int userId : allUserHandles) {
18238                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18239                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18240                }
18241            }
18242        }
18243
18244        // Delete the updated package
18245        outInfo.isRemovedPackageSystemUpdate = true;
18246        if (outInfo.removedChildPackages != null) {
18247            final int childCount = (deletedPs.childPackageNames != null)
18248                    ? deletedPs.childPackageNames.size() : 0;
18249            for (int i = 0; i < childCount; i++) {
18250                String childPackageName = deletedPs.childPackageNames.get(i);
18251                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18252                        .contains(childPackageName)) {
18253                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18254                            childPackageName);
18255                    if (childInfo != null) {
18256                        childInfo.isRemovedPackageSystemUpdate = true;
18257                    }
18258                }
18259            }
18260        }
18261
18262        if (disabledPs.versionCode < deletedPs.versionCode) {
18263            // Delete data for downgrades
18264            flags &= ~PackageManager.DELETE_KEEP_DATA;
18265        } else {
18266            // Preserve data by setting flag
18267            flags |= PackageManager.DELETE_KEEP_DATA;
18268        }
18269
18270        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18271                outInfo, writeSettings, disabledPs.pkg);
18272        if (!ret) {
18273            return false;
18274        }
18275
18276        // writer
18277        synchronized (mPackages) {
18278            // NOTE: The system package always needs to be enabled; even if it's for
18279            // a compressed stub. If we don't, installing the system package fails
18280            // during scan [scanning checks the disabled packages]. We will reverse
18281            // this later, after we've "installed" the stub.
18282            // Reinstate the old system package
18283            enableSystemPackageLPw(disabledPs.pkg);
18284            // Remove any native libraries from the upgraded package.
18285            removeNativeBinariesLI(deletedPs);
18286        }
18287
18288        // Install the system package
18289        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18290        try {
18291            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18292                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18293        } catch (PackageManagerException e) {
18294            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18295                    + e.getMessage());
18296            return false;
18297        } finally {
18298            if (disabledPs.pkg.isStub) {
18299                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18300            }
18301        }
18302        return true;
18303    }
18304
18305    /**
18306     * Installs a package that's already on the system partition.
18307     */
18308    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18309            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18310            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18311                    throws PackageManagerException {
18312        @ParseFlags int parseFlags =
18313                mDefParseFlags
18314                | PackageParser.PARSE_MUST_BE_APK
18315                | PackageParser.PARSE_IS_SYSTEM_DIR;
18316        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18317        if (isPrivileged || locationIsPrivileged(codePathString)) {
18318            scanFlags |= SCAN_AS_PRIVILEGED;
18319        }
18320        if (locationIsOem(codePathString)) {
18321            scanFlags |= SCAN_AS_OEM;
18322        }
18323        if (locationIsVendor(codePathString)) {
18324            scanFlags |= SCAN_AS_VENDOR;
18325        }
18326        if (locationIsProduct(codePathString)) {
18327            scanFlags |= SCAN_AS_PRODUCT;
18328        }
18329
18330        final File codePath = new File(codePathString);
18331        final PackageParser.Package pkg =
18332                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18333
18334        try {
18335            // update shared libraries for the newly re-installed system package
18336            updateSharedLibrariesLPr(pkg, null);
18337        } catch (PackageManagerException e) {
18338            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18339        }
18340
18341        prepareAppDataAfterInstallLIF(pkg);
18342
18343        // writer
18344        synchronized (mPackages) {
18345            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18346
18347            // Propagate the permissions state as we do not want to drop on the floor
18348            // runtime permissions. The update permissions method below will take
18349            // care of removing obsolete permissions and grant install permissions.
18350            if (origPermissionState != null) {
18351                ps.getPermissionsState().copyFrom(origPermissionState);
18352            }
18353            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18354                    mPermissionCallback);
18355
18356            final boolean applyUserRestrictions
18357                    = (allUserHandles != null) && (origUserHandles != null);
18358            if (applyUserRestrictions) {
18359                boolean installedStateChanged = false;
18360                if (DEBUG_REMOVE) {
18361                    Slog.d(TAG, "Propagating install state across reinstall");
18362                }
18363                for (int userId : allUserHandles) {
18364                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18365                    if (DEBUG_REMOVE) {
18366                        Slog.d(TAG, "    user " + userId + " => " + installed);
18367                    }
18368                    if (installed != ps.getInstalled(userId)) {
18369                        installedStateChanged = true;
18370                    }
18371                    ps.setInstalled(installed, userId);
18372
18373                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18374                }
18375                // Regardless of writeSettings we need to ensure that this restriction
18376                // state propagation is persisted
18377                mSettings.writeAllUsersPackageRestrictionsLPr();
18378                if (installedStateChanged) {
18379                    mSettings.writeKernelMappingLPr(ps);
18380                }
18381            }
18382            // can downgrade to reader here
18383            if (writeSettings) {
18384                mSettings.writeLPr();
18385            }
18386        }
18387        return pkg;
18388    }
18389
18390    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18391            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18392            PackageRemovedInfo outInfo, boolean writeSettings,
18393            PackageParser.Package replacingPackage) {
18394        synchronized (mPackages) {
18395            if (outInfo != null) {
18396                outInfo.uid = ps.appId;
18397            }
18398
18399            if (outInfo != null && outInfo.removedChildPackages != null) {
18400                final int childCount = (ps.childPackageNames != null)
18401                        ? ps.childPackageNames.size() : 0;
18402                for (int i = 0; i < childCount; i++) {
18403                    String childPackageName = ps.childPackageNames.get(i);
18404                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18405                    if (childPs == null) {
18406                        return false;
18407                    }
18408                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18409                            childPackageName);
18410                    if (childInfo != null) {
18411                        childInfo.uid = childPs.appId;
18412                    }
18413                }
18414            }
18415        }
18416
18417        // Delete package data from internal structures and also remove data if flag is set
18418        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18419
18420        // Delete the child packages data
18421        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18422        for (int i = 0; i < childCount; i++) {
18423            PackageSetting childPs;
18424            synchronized (mPackages) {
18425                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18426            }
18427            if (childPs != null) {
18428                PackageRemovedInfo childOutInfo = (outInfo != null
18429                        && outInfo.removedChildPackages != null)
18430                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18431                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18432                        && (replacingPackage != null
18433                        && !replacingPackage.hasChildPackage(childPs.name))
18434                        ? flags & ~DELETE_KEEP_DATA : flags;
18435                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18436                        deleteFlags, writeSettings);
18437            }
18438        }
18439
18440        // Delete application code and resources only for parent packages
18441        if (ps.parentPackageName == null) {
18442            if (deleteCodeAndResources && (outInfo != null)) {
18443                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18444                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18445                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18446            }
18447        }
18448
18449        return true;
18450    }
18451
18452    @Override
18453    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18454            int userId) {
18455        mContext.enforceCallingOrSelfPermission(
18456                android.Manifest.permission.DELETE_PACKAGES, null);
18457        synchronized (mPackages) {
18458            // Cannot block uninstall of static shared libs as they are
18459            // considered a part of the using app (emulating static linking).
18460            // Also static libs are installed always on internal storage.
18461            PackageParser.Package pkg = mPackages.get(packageName);
18462            if (pkg != null && pkg.staticSharedLibName != null) {
18463                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18464                        + " providing static shared library: " + pkg.staticSharedLibName);
18465                return false;
18466            }
18467            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18468            mSettings.writePackageRestrictionsLPr(userId);
18469        }
18470        return true;
18471    }
18472
18473    @Override
18474    public boolean getBlockUninstallForUser(String packageName, int userId) {
18475        synchronized (mPackages) {
18476            final PackageSetting ps = mSettings.mPackages.get(packageName);
18477            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18478                return false;
18479            }
18480            return mSettings.getBlockUninstallLPr(userId, packageName);
18481        }
18482    }
18483
18484    @Override
18485    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18486        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18487        synchronized (mPackages) {
18488            PackageSetting ps = mSettings.mPackages.get(packageName);
18489            if (ps == null) {
18490                Log.w(TAG, "Package doesn't exist: " + packageName);
18491                return false;
18492            }
18493            if (systemUserApp) {
18494                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18495            } else {
18496                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18497            }
18498            mSettings.writeLPr();
18499        }
18500        return true;
18501    }
18502
18503    /*
18504     * This method handles package deletion in general
18505     */
18506    private boolean deletePackageLIF(String packageName, UserHandle user,
18507            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18508            PackageRemovedInfo outInfo, boolean writeSettings,
18509            PackageParser.Package replacingPackage) {
18510        if (packageName == null) {
18511            Slog.w(TAG, "Attempt to delete null packageName.");
18512            return false;
18513        }
18514
18515        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18516
18517        PackageSetting ps;
18518        synchronized (mPackages) {
18519            ps = mSettings.mPackages.get(packageName);
18520            if (ps == null) {
18521                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18522                return false;
18523            }
18524
18525            if (ps.parentPackageName != null && (!isSystemApp(ps)
18526                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18527                if (DEBUG_REMOVE) {
18528                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18529                            + ((user == null) ? UserHandle.USER_ALL : user));
18530                }
18531                final int removedUserId = (user != null) ? user.getIdentifier()
18532                        : UserHandle.USER_ALL;
18533                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18534                    return false;
18535                }
18536                markPackageUninstalledForUserLPw(ps, user);
18537                scheduleWritePackageRestrictionsLocked(user);
18538                return true;
18539            }
18540        }
18541
18542        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18543                && user.getIdentifier() != UserHandle.USER_ALL)) {
18544            // The caller is asking that the package only be deleted for a single
18545            // user.  To do this, we just mark its uninstalled state and delete
18546            // its data. If this is a system app, we only allow this to happen if
18547            // they have set the special DELETE_SYSTEM_APP which requests different
18548            // semantics than normal for uninstalling system apps.
18549            markPackageUninstalledForUserLPw(ps, user);
18550
18551            if (!isSystemApp(ps)) {
18552                // Do not uninstall the APK if an app should be cached
18553                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18554                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18555                    // Other user still have this package installed, so all
18556                    // we need to do is clear this user's data and save that
18557                    // it is uninstalled.
18558                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18559                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18560                        return false;
18561                    }
18562                    scheduleWritePackageRestrictionsLocked(user);
18563                    return true;
18564                } else {
18565                    // We need to set it back to 'installed' so the uninstall
18566                    // broadcasts will be sent correctly.
18567                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18568                    ps.setInstalled(true, user.getIdentifier());
18569                    mSettings.writeKernelMappingLPr(ps);
18570                }
18571            } else {
18572                // This is a system app, so we assume that the
18573                // other users still have this package installed, so all
18574                // we need to do is clear this user's data and save that
18575                // it is uninstalled.
18576                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18577                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18578                    return false;
18579                }
18580                scheduleWritePackageRestrictionsLocked(user);
18581                return true;
18582            }
18583        }
18584
18585        // If we are deleting a composite package for all users, keep track
18586        // of result for each child.
18587        if (ps.childPackageNames != null && outInfo != null) {
18588            synchronized (mPackages) {
18589                final int childCount = ps.childPackageNames.size();
18590                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18591                for (int i = 0; i < childCount; i++) {
18592                    String childPackageName = ps.childPackageNames.get(i);
18593                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18594                    childInfo.removedPackage = childPackageName;
18595                    childInfo.installerPackageName = ps.installerPackageName;
18596                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18597                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18598                    if (childPs != null) {
18599                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18600                    }
18601                }
18602            }
18603        }
18604
18605        boolean ret = false;
18606        if (isSystemApp(ps)) {
18607            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18608            // When an updated system application is deleted we delete the existing resources
18609            // as well and fall back to existing code in system partition
18610            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18611        } else {
18612            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18613            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18614                    outInfo, writeSettings, replacingPackage);
18615        }
18616
18617        // Take a note whether we deleted the package for all users
18618        if (outInfo != null) {
18619            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18620            if (outInfo.removedChildPackages != null) {
18621                synchronized (mPackages) {
18622                    final int childCount = outInfo.removedChildPackages.size();
18623                    for (int i = 0; i < childCount; i++) {
18624                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18625                        if (childInfo != null) {
18626                            childInfo.removedForAllUsers = mPackages.get(
18627                                    childInfo.removedPackage) == null;
18628                        }
18629                    }
18630                }
18631            }
18632            // If we uninstalled an update to a system app there may be some
18633            // child packages that appeared as they are declared in the system
18634            // app but were not declared in the update.
18635            if (isSystemApp(ps)) {
18636                synchronized (mPackages) {
18637                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18638                    final int childCount = (updatedPs.childPackageNames != null)
18639                            ? updatedPs.childPackageNames.size() : 0;
18640                    for (int i = 0; i < childCount; i++) {
18641                        String childPackageName = updatedPs.childPackageNames.get(i);
18642                        if (outInfo.removedChildPackages == null
18643                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18644                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18645                            if (childPs == null) {
18646                                continue;
18647                            }
18648                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18649                            installRes.name = childPackageName;
18650                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18651                            installRes.pkg = mPackages.get(childPackageName);
18652                            installRes.uid = childPs.pkg.applicationInfo.uid;
18653                            if (outInfo.appearedChildPackages == null) {
18654                                outInfo.appearedChildPackages = new ArrayMap<>();
18655                            }
18656                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18657                        }
18658                    }
18659                }
18660            }
18661        }
18662
18663        return ret;
18664    }
18665
18666    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18667        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18668                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18669        for (int nextUserId : userIds) {
18670            if (DEBUG_REMOVE) {
18671                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18672            }
18673            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18674                    false /*installed*/,
18675                    true /*stopped*/,
18676                    true /*notLaunched*/,
18677                    false /*hidden*/,
18678                    false /*suspended*/,
18679                    false /*instantApp*/,
18680                    false /*virtualPreload*/,
18681                    null /*lastDisableAppCaller*/,
18682                    null /*enabledComponents*/,
18683                    null /*disabledComponents*/,
18684                    ps.readUserState(nextUserId).domainVerificationStatus,
18685                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18686                    null /*harmfulAppWarning*/);
18687        }
18688        mSettings.writeKernelMappingLPr(ps);
18689    }
18690
18691    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18692            PackageRemovedInfo outInfo) {
18693        final PackageParser.Package pkg;
18694        synchronized (mPackages) {
18695            pkg = mPackages.get(ps.name);
18696        }
18697
18698        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18699                : new int[] {userId};
18700        for (int nextUserId : userIds) {
18701            if (DEBUG_REMOVE) {
18702                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18703                        + nextUserId);
18704            }
18705
18706            destroyAppDataLIF(pkg, userId,
18707                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18708            destroyAppProfilesLIF(pkg, userId);
18709            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18710            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18711            schedulePackageCleaning(ps.name, nextUserId, false);
18712            synchronized (mPackages) {
18713                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18714                    scheduleWritePackageRestrictionsLocked(nextUserId);
18715                }
18716                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18717            }
18718        }
18719
18720        if (outInfo != null) {
18721            outInfo.removedPackage = ps.name;
18722            outInfo.installerPackageName = ps.installerPackageName;
18723            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18724            outInfo.removedAppId = ps.appId;
18725            outInfo.removedUsers = userIds;
18726            outInfo.broadcastUsers = userIds;
18727        }
18728
18729        return true;
18730    }
18731
18732    private static final class ClearStorageConnection implements ServiceConnection {
18733        IMediaContainerService mContainerService;
18734
18735        @Override
18736        public void onServiceConnected(ComponentName name, IBinder service) {
18737            synchronized (this) {
18738                mContainerService = IMediaContainerService.Stub
18739                        .asInterface(Binder.allowBlocking(service));
18740                notifyAll();
18741            }
18742        }
18743
18744        @Override
18745        public void onServiceDisconnected(ComponentName name) {
18746        }
18747    }
18748
18749    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18750        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18751
18752        final boolean mounted;
18753        if (Environment.isExternalStorageEmulated()) {
18754            mounted = true;
18755        } else {
18756            final String status = Environment.getExternalStorageState();
18757
18758            mounted = status.equals(Environment.MEDIA_MOUNTED)
18759                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18760        }
18761
18762        if (!mounted) {
18763            return;
18764        }
18765
18766        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18767        int[] users;
18768        if (userId == UserHandle.USER_ALL) {
18769            users = sUserManager.getUserIds();
18770        } else {
18771            users = new int[] { userId };
18772        }
18773        final ClearStorageConnection conn = new ClearStorageConnection();
18774        if (mContext.bindServiceAsUser(
18775                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18776            try {
18777                for (int curUser : users) {
18778                    long timeout = SystemClock.uptimeMillis() + 5000;
18779                    synchronized (conn) {
18780                        long now;
18781                        while (conn.mContainerService == null &&
18782                                (now = SystemClock.uptimeMillis()) < timeout) {
18783                            try {
18784                                conn.wait(timeout - now);
18785                            } catch (InterruptedException e) {
18786                            }
18787                        }
18788                    }
18789                    if (conn.mContainerService == null) {
18790                        return;
18791                    }
18792
18793                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18794                    clearDirectory(conn.mContainerService,
18795                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18796                    if (allData) {
18797                        clearDirectory(conn.mContainerService,
18798                                userEnv.buildExternalStorageAppDataDirs(packageName));
18799                        clearDirectory(conn.mContainerService,
18800                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18801                    }
18802                }
18803            } finally {
18804                mContext.unbindService(conn);
18805            }
18806        }
18807    }
18808
18809    @Override
18810    public void clearApplicationProfileData(String packageName) {
18811        enforceSystemOrRoot("Only the system can clear all profile data");
18812
18813        final PackageParser.Package pkg;
18814        synchronized (mPackages) {
18815            pkg = mPackages.get(packageName);
18816        }
18817
18818        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18819            synchronized (mInstallLock) {
18820                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18821            }
18822        }
18823    }
18824
18825    @Override
18826    public void clearApplicationUserData(final String packageName,
18827            final IPackageDataObserver observer, final int userId) {
18828        mContext.enforceCallingOrSelfPermission(
18829                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18830
18831        final int callingUid = Binder.getCallingUid();
18832        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18833                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18834
18835        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18836        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18837        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18838            throw new SecurityException("Cannot clear data for a protected package: "
18839                    + packageName);
18840        }
18841        // Queue up an async operation since the package deletion may take a little while.
18842        mHandler.post(new Runnable() {
18843            public void run() {
18844                mHandler.removeCallbacks(this);
18845                final boolean succeeded;
18846                if (!filterApp) {
18847                    try (PackageFreezer freezer = freezePackage(packageName,
18848                            "clearApplicationUserData")) {
18849                        synchronized (mInstallLock) {
18850                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18851                        }
18852                        clearExternalStorageDataSync(packageName, userId, true);
18853                        synchronized (mPackages) {
18854                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18855                                    packageName, userId);
18856                        }
18857                    }
18858                    if (succeeded) {
18859                        // invoke DeviceStorageMonitor's update method to clear any notifications
18860                        DeviceStorageMonitorInternal dsm = LocalServices
18861                                .getService(DeviceStorageMonitorInternal.class);
18862                        if (dsm != null) {
18863                            dsm.checkMemory();
18864                        }
18865                    }
18866                } else {
18867                    succeeded = false;
18868                }
18869                if (observer != null) {
18870                    try {
18871                        observer.onRemoveCompleted(packageName, succeeded);
18872                    } catch (RemoteException e) {
18873                        Log.i(TAG, "Observer no longer exists.");
18874                    }
18875                } //end if observer
18876            } //end run
18877        });
18878    }
18879
18880    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18881        if (packageName == null) {
18882            Slog.w(TAG, "Attempt to delete null packageName.");
18883            return false;
18884        }
18885
18886        // Try finding details about the requested package
18887        PackageParser.Package pkg;
18888        synchronized (mPackages) {
18889            pkg = mPackages.get(packageName);
18890            if (pkg == null) {
18891                final PackageSetting ps = mSettings.mPackages.get(packageName);
18892                if (ps != null) {
18893                    pkg = ps.pkg;
18894                }
18895            }
18896
18897            if (pkg == null) {
18898                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18899                return false;
18900            }
18901
18902            PackageSetting ps = (PackageSetting) pkg.mExtras;
18903            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18904        }
18905
18906        clearAppDataLIF(pkg, userId,
18907                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18908
18909        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18910        removeKeystoreDataIfNeeded(userId, appId);
18911
18912        UserManagerInternal umInternal = getUserManagerInternal();
18913        final int flags;
18914        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18915            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18916        } else if (umInternal.isUserRunning(userId)) {
18917            flags = StorageManager.FLAG_STORAGE_DE;
18918        } else {
18919            flags = 0;
18920        }
18921        prepareAppDataContentsLIF(pkg, userId, flags);
18922
18923        return true;
18924    }
18925
18926    /**
18927     * Reverts user permission state changes (permissions and flags) in
18928     * all packages for a given user.
18929     *
18930     * @param userId The device user for which to do a reset.
18931     */
18932    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18933        final int packageCount = mPackages.size();
18934        for (int i = 0; i < packageCount; i++) {
18935            PackageParser.Package pkg = mPackages.valueAt(i);
18936            PackageSetting ps = (PackageSetting) pkg.mExtras;
18937            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18938        }
18939    }
18940
18941    private void resetNetworkPolicies(int userId) {
18942        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18943    }
18944
18945    /**
18946     * Reverts user permission state changes (permissions and flags).
18947     *
18948     * @param ps The package for which to reset.
18949     * @param userId The device user for which to do a reset.
18950     */
18951    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18952            final PackageSetting ps, final int userId) {
18953        if (ps.pkg == null) {
18954            return;
18955        }
18956
18957        // These are flags that can change base on user actions.
18958        final int userSettableMask = FLAG_PERMISSION_USER_SET
18959                | FLAG_PERMISSION_USER_FIXED
18960                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18961                | FLAG_PERMISSION_REVIEW_REQUIRED;
18962
18963        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18964                | FLAG_PERMISSION_POLICY_FIXED;
18965
18966        boolean writeInstallPermissions = false;
18967        boolean writeRuntimePermissions = false;
18968
18969        final int permissionCount = ps.pkg.requestedPermissions.size();
18970        for (int i = 0; i < permissionCount; i++) {
18971            final String permName = ps.pkg.requestedPermissions.get(i);
18972            final BasePermission bp =
18973                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18974            if (bp == null) {
18975                continue;
18976            }
18977
18978            // If shared user we just reset the state to which only this app contributed.
18979            if (ps.sharedUser != null) {
18980                boolean used = false;
18981                final int packageCount = ps.sharedUser.packages.size();
18982                for (int j = 0; j < packageCount; j++) {
18983                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18984                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18985                            && pkg.pkg.requestedPermissions.contains(permName)) {
18986                        used = true;
18987                        break;
18988                    }
18989                }
18990                if (used) {
18991                    continue;
18992                }
18993            }
18994
18995            final PermissionsState permissionsState = ps.getPermissionsState();
18996
18997            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18998
18999            // Always clear the user settable flags.
19000            final boolean hasInstallState =
19001                    permissionsState.getInstallPermissionState(permName) != null;
19002            // If permission review is enabled and this is a legacy app, mark the
19003            // permission as requiring a review as this is the initial state.
19004            int flags = 0;
19005            if (mSettings.mPermissions.mPermissionReviewRequired
19006                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19007                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19008            }
19009            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19010                if (hasInstallState) {
19011                    writeInstallPermissions = true;
19012                } else {
19013                    writeRuntimePermissions = true;
19014                }
19015            }
19016
19017            // Below is only runtime permission handling.
19018            if (!bp.isRuntime()) {
19019                continue;
19020            }
19021
19022            // Never clobber system or policy.
19023            if ((oldFlags & policyOrSystemFlags) != 0) {
19024                continue;
19025            }
19026
19027            // If this permission was granted by default, make sure it is.
19028            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19029                if (permissionsState.grantRuntimePermission(bp, userId)
19030                        != PERMISSION_OPERATION_FAILURE) {
19031                    writeRuntimePermissions = true;
19032                }
19033            // If permission review is enabled the permissions for a legacy apps
19034            // are represented as constantly granted runtime ones, so don't revoke.
19035            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19036                // Otherwise, reset the permission.
19037                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19038                switch (revokeResult) {
19039                    case PERMISSION_OPERATION_SUCCESS:
19040                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19041                        writeRuntimePermissions = true;
19042                        final int appId = ps.appId;
19043                        mHandler.post(new Runnable() {
19044                            @Override
19045                            public void run() {
19046                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19047                            }
19048                        });
19049                    } break;
19050                }
19051            }
19052        }
19053
19054        // Synchronously write as we are taking permissions away.
19055        if (writeRuntimePermissions) {
19056            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19057        }
19058
19059        // Synchronously write as we are taking permissions away.
19060        if (writeInstallPermissions) {
19061            mSettings.writeLPr();
19062        }
19063    }
19064
19065    /**
19066     * Remove entries from the keystore daemon. Will only remove it if the
19067     * {@code appId} is valid.
19068     */
19069    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19070        if (appId < 0) {
19071            return;
19072        }
19073
19074        final KeyStore keyStore = KeyStore.getInstance();
19075        if (keyStore != null) {
19076            if (userId == UserHandle.USER_ALL) {
19077                for (final int individual : sUserManager.getUserIds()) {
19078                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19079                }
19080            } else {
19081                keyStore.clearUid(UserHandle.getUid(userId, appId));
19082            }
19083        } else {
19084            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19085        }
19086    }
19087
19088    @Override
19089    public void deleteApplicationCacheFiles(final String packageName,
19090            final IPackageDataObserver observer) {
19091        final int userId = UserHandle.getCallingUserId();
19092        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19093    }
19094
19095    @Override
19096    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19097            final IPackageDataObserver observer) {
19098        final int callingUid = Binder.getCallingUid();
19099        if (mContext.checkCallingOrSelfPermission(
19100                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19101                != PackageManager.PERMISSION_GRANTED) {
19102            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19103            if (mContext.checkCallingOrSelfPermission(
19104                    android.Manifest.permission.DELETE_CACHE_FILES)
19105                    == PackageManager.PERMISSION_GRANTED) {
19106                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19107                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19108                        ", silently ignoring");
19109                return;
19110            }
19111            mContext.enforceCallingOrSelfPermission(
19112                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19113        }
19114        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19115                /* requireFullPermission= */ true, /* checkShell= */ false,
19116                "delete application cache files");
19117        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19118                android.Manifest.permission.ACCESS_INSTANT_APPS);
19119
19120        final PackageParser.Package pkg;
19121        synchronized (mPackages) {
19122            pkg = mPackages.get(packageName);
19123        }
19124
19125        // Queue up an async operation since the package deletion may take a little while.
19126        mHandler.post(new Runnable() {
19127            public void run() {
19128                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19129                boolean doClearData = true;
19130                if (ps != null) {
19131                    final boolean targetIsInstantApp =
19132                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19133                    doClearData = !targetIsInstantApp
19134                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19135                }
19136                if (doClearData) {
19137                    synchronized (mInstallLock) {
19138                        final int flags = StorageManager.FLAG_STORAGE_DE
19139                                | StorageManager.FLAG_STORAGE_CE;
19140                        // We're only clearing cache files, so we don't care if the
19141                        // app is unfrozen and still able to run
19142                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19143                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19144                    }
19145                    clearExternalStorageDataSync(packageName, userId, false);
19146                }
19147                if (observer != null) {
19148                    try {
19149                        observer.onRemoveCompleted(packageName, true);
19150                    } catch (RemoteException e) {
19151                        Log.i(TAG, "Observer no longer exists.");
19152                    }
19153                }
19154            }
19155        });
19156    }
19157
19158    @Override
19159    public void getPackageSizeInfo(final String packageName, int userHandle,
19160            final IPackageStatsObserver observer) {
19161        throw new UnsupportedOperationException(
19162                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19163    }
19164
19165    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19166        final PackageSetting ps;
19167        synchronized (mPackages) {
19168            ps = mSettings.mPackages.get(packageName);
19169            if (ps == null) {
19170                Slog.w(TAG, "Failed to find settings for " + packageName);
19171                return false;
19172            }
19173        }
19174
19175        final String[] packageNames = { packageName };
19176        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19177        final String[] codePaths = { ps.codePathString };
19178
19179        try {
19180            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19181                    ps.appId, ceDataInodes, codePaths, stats);
19182
19183            // For now, ignore code size of packages on system partition
19184            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19185                stats.codeSize = 0;
19186            }
19187
19188            // External clients expect these to be tracked separately
19189            stats.dataSize -= stats.cacheSize;
19190
19191        } catch (InstallerException e) {
19192            Slog.w(TAG, String.valueOf(e));
19193            return false;
19194        }
19195
19196        return true;
19197    }
19198
19199    private int getUidTargetSdkVersionLockedLPr(int uid) {
19200        Object obj = mSettings.getUserIdLPr(uid);
19201        if (obj instanceof SharedUserSetting) {
19202            final SharedUserSetting sus = (SharedUserSetting) obj;
19203            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19204            final Iterator<PackageSetting> it = sus.packages.iterator();
19205            while (it.hasNext()) {
19206                final PackageSetting ps = it.next();
19207                if (ps.pkg != null) {
19208                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19209                    if (v < vers) vers = v;
19210                }
19211            }
19212            return vers;
19213        } else if (obj instanceof PackageSetting) {
19214            final PackageSetting ps = (PackageSetting) obj;
19215            if (ps.pkg != null) {
19216                return ps.pkg.applicationInfo.targetSdkVersion;
19217            }
19218        }
19219        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19220    }
19221
19222    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19223        final PackageParser.Package p = mPackages.get(packageName);
19224        if (p != null) {
19225            return p.applicationInfo.targetSdkVersion;
19226        }
19227        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19228    }
19229
19230    @Override
19231    public void addPreferredActivity(IntentFilter filter, int match,
19232            ComponentName[] set, ComponentName activity, int userId) {
19233        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19234                "Adding preferred");
19235    }
19236
19237    private void addPreferredActivityInternal(IntentFilter filter, int match,
19238            ComponentName[] set, ComponentName activity, boolean always, int userId,
19239            String opname) {
19240        // writer
19241        int callingUid = Binder.getCallingUid();
19242        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19243                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19244        if (filter.countActions() == 0) {
19245            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19246            return;
19247        }
19248        synchronized (mPackages) {
19249            if (mContext.checkCallingOrSelfPermission(
19250                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19251                    != PackageManager.PERMISSION_GRANTED) {
19252                if (getUidTargetSdkVersionLockedLPr(callingUid)
19253                        < Build.VERSION_CODES.FROYO) {
19254                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19255                            + callingUid);
19256                    return;
19257                }
19258                mContext.enforceCallingOrSelfPermission(
19259                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19260            }
19261
19262            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19263            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19264                    + userId + ":");
19265            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19266            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19267            scheduleWritePackageRestrictionsLocked(userId);
19268            postPreferredActivityChangedBroadcast(userId);
19269        }
19270    }
19271
19272    private void postPreferredActivityChangedBroadcast(int userId) {
19273        mHandler.post(() -> {
19274            final IActivityManager am = ActivityManager.getService();
19275            if (am == null) {
19276                return;
19277            }
19278
19279            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19280            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19281            try {
19282                am.broadcastIntent(null, intent, null, null,
19283                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19284                        null, false, false, userId);
19285            } catch (RemoteException e) {
19286            }
19287        });
19288    }
19289
19290    @Override
19291    public void replacePreferredActivity(IntentFilter filter, int match,
19292            ComponentName[] set, ComponentName activity, int userId) {
19293        if (filter.countActions() != 1) {
19294            throw new IllegalArgumentException(
19295                    "replacePreferredActivity expects filter to have only 1 action.");
19296        }
19297        if (filter.countDataAuthorities() != 0
19298                || filter.countDataPaths() != 0
19299                || filter.countDataSchemes() > 1
19300                || filter.countDataTypes() != 0) {
19301            throw new IllegalArgumentException(
19302                    "replacePreferredActivity expects filter to have no data authorities, " +
19303                    "paths, or types; and at most one scheme.");
19304        }
19305
19306        final int callingUid = Binder.getCallingUid();
19307        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19308                true /* requireFullPermission */, false /* checkShell */,
19309                "replace preferred activity");
19310        synchronized (mPackages) {
19311            if (mContext.checkCallingOrSelfPermission(
19312                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19313                    != PackageManager.PERMISSION_GRANTED) {
19314                if (getUidTargetSdkVersionLockedLPr(callingUid)
19315                        < Build.VERSION_CODES.FROYO) {
19316                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19317                            + Binder.getCallingUid());
19318                    return;
19319                }
19320                mContext.enforceCallingOrSelfPermission(
19321                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19322            }
19323
19324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19325            if (pir != null) {
19326                // Get all of the existing entries that exactly match this filter.
19327                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19328                if (existing != null && existing.size() == 1) {
19329                    PreferredActivity cur = existing.get(0);
19330                    if (DEBUG_PREFERRED) {
19331                        Slog.i(TAG, "Checking replace of preferred:");
19332                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19333                        if (!cur.mPref.mAlways) {
19334                            Slog.i(TAG, "  -- CUR; not mAlways!");
19335                        } else {
19336                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19337                            Slog.i(TAG, "  -- CUR: mSet="
19338                                    + Arrays.toString(cur.mPref.mSetComponents));
19339                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19340                            Slog.i(TAG, "  -- NEW: mMatch="
19341                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19342                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19343                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19344                        }
19345                    }
19346                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19347                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19348                            && cur.mPref.sameSet(set)) {
19349                        // Setting the preferred activity to what it happens to be already
19350                        if (DEBUG_PREFERRED) {
19351                            Slog.i(TAG, "Replacing with same preferred activity "
19352                                    + cur.mPref.mShortComponent + " for user "
19353                                    + userId + ":");
19354                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19355                        }
19356                        return;
19357                    }
19358                }
19359
19360                if (existing != null) {
19361                    if (DEBUG_PREFERRED) {
19362                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19363                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19364                    }
19365                    for (int i = 0; i < existing.size(); i++) {
19366                        PreferredActivity pa = existing.get(i);
19367                        if (DEBUG_PREFERRED) {
19368                            Slog.i(TAG, "Removing existing preferred activity "
19369                                    + pa.mPref.mComponent + ":");
19370                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19371                        }
19372                        pir.removeFilter(pa);
19373                    }
19374                }
19375            }
19376            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19377                    "Replacing preferred");
19378        }
19379    }
19380
19381    @Override
19382    public void clearPackagePreferredActivities(String packageName) {
19383        final int callingUid = Binder.getCallingUid();
19384        if (getInstantAppPackageName(callingUid) != null) {
19385            return;
19386        }
19387        // writer
19388        synchronized (mPackages) {
19389            PackageParser.Package pkg = mPackages.get(packageName);
19390            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19391                if (mContext.checkCallingOrSelfPermission(
19392                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19393                        != PackageManager.PERMISSION_GRANTED) {
19394                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19395                            < Build.VERSION_CODES.FROYO) {
19396                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19397                                + callingUid);
19398                        return;
19399                    }
19400                    mContext.enforceCallingOrSelfPermission(
19401                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19402                }
19403            }
19404            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19405            if (ps != null
19406                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19407                return;
19408            }
19409            int user = UserHandle.getCallingUserId();
19410            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19411                scheduleWritePackageRestrictionsLocked(user);
19412            }
19413        }
19414    }
19415
19416    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19417    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19418        ArrayList<PreferredActivity> removed = null;
19419        boolean changed = false;
19420        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19421            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19422            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19423            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19424                continue;
19425            }
19426            Iterator<PreferredActivity> it = pir.filterIterator();
19427            while (it.hasNext()) {
19428                PreferredActivity pa = it.next();
19429                // Mark entry for removal only if it matches the package name
19430                // and the entry is of type "always".
19431                if (packageName == null ||
19432                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19433                                && pa.mPref.mAlways)) {
19434                    if (removed == null) {
19435                        removed = new ArrayList<PreferredActivity>();
19436                    }
19437                    removed.add(pa);
19438                }
19439            }
19440            if (removed != null) {
19441                for (int j=0; j<removed.size(); j++) {
19442                    PreferredActivity pa = removed.get(j);
19443                    pir.removeFilter(pa);
19444                }
19445                changed = true;
19446            }
19447        }
19448        if (changed) {
19449            postPreferredActivityChangedBroadcast(userId);
19450        }
19451        return changed;
19452    }
19453
19454    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19455    private void clearIntentFilterVerificationsLPw(int userId) {
19456        final int packageCount = mPackages.size();
19457        for (int i = 0; i < packageCount; i++) {
19458            PackageParser.Package pkg = mPackages.valueAt(i);
19459            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19460        }
19461    }
19462
19463    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19464    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19465        if (userId == UserHandle.USER_ALL) {
19466            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19467                    sUserManager.getUserIds())) {
19468                for (int oneUserId : sUserManager.getUserIds()) {
19469                    scheduleWritePackageRestrictionsLocked(oneUserId);
19470                }
19471            }
19472        } else {
19473            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19474                scheduleWritePackageRestrictionsLocked(userId);
19475            }
19476        }
19477    }
19478
19479    /** Clears state for all users, and touches intent filter verification policy */
19480    void clearDefaultBrowserIfNeeded(String packageName) {
19481        for (int oneUserId : sUserManager.getUserIds()) {
19482            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19483        }
19484    }
19485
19486    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19487        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19488        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19489            if (packageName.equals(defaultBrowserPackageName)) {
19490                setDefaultBrowserPackageName(null, userId);
19491            }
19492        }
19493    }
19494
19495    @Override
19496    public void resetApplicationPreferences(int userId) {
19497        mContext.enforceCallingOrSelfPermission(
19498                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19499        final long identity = Binder.clearCallingIdentity();
19500        // writer
19501        try {
19502            synchronized (mPackages) {
19503                clearPackagePreferredActivitiesLPw(null, userId);
19504                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19505                // TODO: We have to reset the default SMS and Phone. This requires
19506                // significant refactoring to keep all default apps in the package
19507                // manager (cleaner but more work) or have the services provide
19508                // callbacks to the package manager to request a default app reset.
19509                applyFactoryDefaultBrowserLPw(userId);
19510                clearIntentFilterVerificationsLPw(userId);
19511                primeDomainVerificationsLPw(userId);
19512                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19513                scheduleWritePackageRestrictionsLocked(userId);
19514            }
19515            resetNetworkPolicies(userId);
19516        } finally {
19517            Binder.restoreCallingIdentity(identity);
19518        }
19519    }
19520
19521    @Override
19522    public int getPreferredActivities(List<IntentFilter> outFilters,
19523            List<ComponentName> outActivities, String packageName) {
19524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19525            return 0;
19526        }
19527        int num = 0;
19528        final int userId = UserHandle.getCallingUserId();
19529        // reader
19530        synchronized (mPackages) {
19531            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19532            if (pir != null) {
19533                final Iterator<PreferredActivity> it = pir.filterIterator();
19534                while (it.hasNext()) {
19535                    final PreferredActivity pa = it.next();
19536                    if (packageName == null
19537                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19538                                    && pa.mPref.mAlways)) {
19539                        if (outFilters != null) {
19540                            outFilters.add(new IntentFilter(pa));
19541                        }
19542                        if (outActivities != null) {
19543                            outActivities.add(pa.mPref.mComponent);
19544                        }
19545                    }
19546                }
19547            }
19548        }
19549
19550        return num;
19551    }
19552
19553    @Override
19554    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19555            int userId) {
19556        int callingUid = Binder.getCallingUid();
19557        if (callingUid != Process.SYSTEM_UID) {
19558            throw new SecurityException(
19559                    "addPersistentPreferredActivity can only be run by the system");
19560        }
19561        if (filter.countActions() == 0) {
19562            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19563            return;
19564        }
19565        synchronized (mPackages) {
19566            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19567                    ":");
19568            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19569            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19570                    new PersistentPreferredActivity(filter, activity));
19571            scheduleWritePackageRestrictionsLocked(userId);
19572            postPreferredActivityChangedBroadcast(userId);
19573        }
19574    }
19575
19576    @Override
19577    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19578        int callingUid = Binder.getCallingUid();
19579        if (callingUid != Process.SYSTEM_UID) {
19580            throw new SecurityException(
19581                    "clearPackagePersistentPreferredActivities can only be run by the system");
19582        }
19583        ArrayList<PersistentPreferredActivity> removed = null;
19584        boolean changed = false;
19585        synchronized (mPackages) {
19586            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19587                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19588                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19589                        .valueAt(i);
19590                if (userId != thisUserId) {
19591                    continue;
19592                }
19593                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19594                while (it.hasNext()) {
19595                    PersistentPreferredActivity ppa = it.next();
19596                    // Mark entry for removal only if it matches the package name.
19597                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19598                        if (removed == null) {
19599                            removed = new ArrayList<PersistentPreferredActivity>();
19600                        }
19601                        removed.add(ppa);
19602                    }
19603                }
19604                if (removed != null) {
19605                    for (int j=0; j<removed.size(); j++) {
19606                        PersistentPreferredActivity ppa = removed.get(j);
19607                        ppir.removeFilter(ppa);
19608                    }
19609                    changed = true;
19610                }
19611            }
19612
19613            if (changed) {
19614                scheduleWritePackageRestrictionsLocked(userId);
19615                postPreferredActivityChangedBroadcast(userId);
19616            }
19617        }
19618    }
19619
19620    /**
19621     * Common machinery for picking apart a restored XML blob and passing
19622     * it to a caller-supplied functor to be applied to the running system.
19623     */
19624    private void restoreFromXml(XmlPullParser parser, int userId,
19625            String expectedStartTag, BlobXmlRestorer functor)
19626            throws IOException, XmlPullParserException {
19627        int type;
19628        while ((type = parser.next()) != XmlPullParser.START_TAG
19629                && type != XmlPullParser.END_DOCUMENT) {
19630        }
19631        if (type != XmlPullParser.START_TAG) {
19632            // oops didn't find a start tag?!
19633            if (DEBUG_BACKUP) {
19634                Slog.e(TAG, "Didn't find start tag during restore");
19635            }
19636            return;
19637        }
19638Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19639        // this is supposed to be TAG_PREFERRED_BACKUP
19640        if (!expectedStartTag.equals(parser.getName())) {
19641            if (DEBUG_BACKUP) {
19642                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19643            }
19644            return;
19645        }
19646
19647        // skip interfering stuff, then we're aligned with the backing implementation
19648        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19649Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19650        functor.apply(parser, userId);
19651    }
19652
19653    private interface BlobXmlRestorer {
19654        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19655    }
19656
19657    /**
19658     * Non-Binder method, support for the backup/restore mechanism: write the
19659     * full set of preferred activities in its canonical XML format.  Returns the
19660     * XML output as a byte array, or null if there is none.
19661     */
19662    @Override
19663    public byte[] getPreferredActivityBackup(int userId) {
19664        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19665            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19666        }
19667
19668        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19669        try {
19670            final XmlSerializer serializer = new FastXmlSerializer();
19671            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19672            serializer.startDocument(null, true);
19673            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19674
19675            synchronized (mPackages) {
19676                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19677            }
19678
19679            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19680            serializer.endDocument();
19681            serializer.flush();
19682        } catch (Exception e) {
19683            if (DEBUG_BACKUP) {
19684                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19685            }
19686            return null;
19687        }
19688
19689        return dataStream.toByteArray();
19690    }
19691
19692    @Override
19693    public void restorePreferredActivities(byte[] backup, int userId) {
19694        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19695            throw new SecurityException("Only the system may call restorePreferredActivities()");
19696        }
19697
19698        try {
19699            final XmlPullParser parser = Xml.newPullParser();
19700            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19701            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19702                    new BlobXmlRestorer() {
19703                        @Override
19704                        public void apply(XmlPullParser parser, int userId)
19705                                throws XmlPullParserException, IOException {
19706                            synchronized (mPackages) {
19707                                mSettings.readPreferredActivitiesLPw(parser, userId);
19708                            }
19709                        }
19710                    } );
19711        } catch (Exception e) {
19712            if (DEBUG_BACKUP) {
19713                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19714            }
19715        }
19716    }
19717
19718    /**
19719     * Non-Binder method, support for the backup/restore mechanism: write the
19720     * default browser (etc) settings in its canonical XML format.  Returns the default
19721     * browser XML representation as a byte array, or null if there is none.
19722     */
19723    @Override
19724    public byte[] getDefaultAppsBackup(int userId) {
19725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19726            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19727        }
19728
19729        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19730        try {
19731            final XmlSerializer serializer = new FastXmlSerializer();
19732            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19733            serializer.startDocument(null, true);
19734            serializer.startTag(null, TAG_DEFAULT_APPS);
19735
19736            synchronized (mPackages) {
19737                mSettings.writeDefaultAppsLPr(serializer, userId);
19738            }
19739
19740            serializer.endTag(null, TAG_DEFAULT_APPS);
19741            serializer.endDocument();
19742            serializer.flush();
19743        } catch (Exception e) {
19744            if (DEBUG_BACKUP) {
19745                Slog.e(TAG, "Unable to write default apps for backup", e);
19746            }
19747            return null;
19748        }
19749
19750        return dataStream.toByteArray();
19751    }
19752
19753    @Override
19754    public void restoreDefaultApps(byte[] backup, int userId) {
19755        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19756            throw new SecurityException("Only the system may call restoreDefaultApps()");
19757        }
19758
19759        try {
19760            final XmlPullParser parser = Xml.newPullParser();
19761            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19762            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19763                    new BlobXmlRestorer() {
19764                        @Override
19765                        public void apply(XmlPullParser parser, int userId)
19766                                throws XmlPullParserException, IOException {
19767                            synchronized (mPackages) {
19768                                mSettings.readDefaultAppsLPw(parser, userId);
19769                            }
19770                        }
19771                    } );
19772        } catch (Exception e) {
19773            if (DEBUG_BACKUP) {
19774                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19775            }
19776        }
19777    }
19778
19779    @Override
19780    public byte[] getIntentFilterVerificationBackup(int userId) {
19781        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19782            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19783        }
19784
19785        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19786        try {
19787            final XmlSerializer serializer = new FastXmlSerializer();
19788            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19789            serializer.startDocument(null, true);
19790            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19791
19792            synchronized (mPackages) {
19793                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19794            }
19795
19796            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19797            serializer.endDocument();
19798            serializer.flush();
19799        } catch (Exception e) {
19800            if (DEBUG_BACKUP) {
19801                Slog.e(TAG, "Unable to write default apps for backup", e);
19802            }
19803            return null;
19804        }
19805
19806        return dataStream.toByteArray();
19807    }
19808
19809    @Override
19810    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19812            throw new SecurityException("Only the system may call restorePreferredActivities()");
19813        }
19814
19815        try {
19816            final XmlPullParser parser = Xml.newPullParser();
19817            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19818            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19819                    new BlobXmlRestorer() {
19820                        @Override
19821                        public void apply(XmlPullParser parser, int userId)
19822                                throws XmlPullParserException, IOException {
19823                            synchronized (mPackages) {
19824                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19825                                mSettings.writeLPr();
19826                            }
19827                        }
19828                    } );
19829        } catch (Exception e) {
19830            if (DEBUG_BACKUP) {
19831                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19832            }
19833        }
19834    }
19835
19836    @Override
19837    public byte[] getPermissionGrantBackup(int userId) {
19838        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19839            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19840        }
19841
19842        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19843        try {
19844            final XmlSerializer serializer = new FastXmlSerializer();
19845            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19846            serializer.startDocument(null, true);
19847            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19848
19849            synchronized (mPackages) {
19850                serializeRuntimePermissionGrantsLPr(serializer, userId);
19851            }
19852
19853            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19854            serializer.endDocument();
19855            serializer.flush();
19856        } catch (Exception e) {
19857            if (DEBUG_BACKUP) {
19858                Slog.e(TAG, "Unable to write default apps for backup", e);
19859            }
19860            return null;
19861        }
19862
19863        return dataStream.toByteArray();
19864    }
19865
19866    @Override
19867    public void restorePermissionGrants(byte[] backup, int userId) {
19868        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19869            throw new SecurityException("Only the system may call restorePermissionGrants()");
19870        }
19871
19872        try {
19873            final XmlPullParser parser = Xml.newPullParser();
19874            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19875            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19876                    new BlobXmlRestorer() {
19877                        @Override
19878                        public void apply(XmlPullParser parser, int userId)
19879                                throws XmlPullParserException, IOException {
19880                            synchronized (mPackages) {
19881                                processRestoredPermissionGrantsLPr(parser, userId);
19882                            }
19883                        }
19884                    } );
19885        } catch (Exception e) {
19886            if (DEBUG_BACKUP) {
19887                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19888            }
19889        }
19890    }
19891
19892    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19893            throws IOException {
19894        serializer.startTag(null, TAG_ALL_GRANTS);
19895
19896        final int N = mSettings.mPackages.size();
19897        for (int i = 0; i < N; i++) {
19898            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19899            boolean pkgGrantsKnown = false;
19900
19901            PermissionsState packagePerms = ps.getPermissionsState();
19902
19903            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19904                final int grantFlags = state.getFlags();
19905                // only look at grants that are not system/policy fixed
19906                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19907                    final boolean isGranted = state.isGranted();
19908                    // And only back up the user-twiddled state bits
19909                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19910                        final String packageName = mSettings.mPackages.keyAt(i);
19911                        if (!pkgGrantsKnown) {
19912                            serializer.startTag(null, TAG_GRANT);
19913                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19914                            pkgGrantsKnown = true;
19915                        }
19916
19917                        final boolean userSet =
19918                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19919                        final boolean userFixed =
19920                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19921                        final boolean revoke =
19922                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19923
19924                        serializer.startTag(null, TAG_PERMISSION);
19925                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19926                        if (isGranted) {
19927                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19928                        }
19929                        if (userSet) {
19930                            serializer.attribute(null, ATTR_USER_SET, "true");
19931                        }
19932                        if (userFixed) {
19933                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19934                        }
19935                        if (revoke) {
19936                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19937                        }
19938                        serializer.endTag(null, TAG_PERMISSION);
19939                    }
19940                }
19941            }
19942
19943            if (pkgGrantsKnown) {
19944                serializer.endTag(null, TAG_GRANT);
19945            }
19946        }
19947
19948        serializer.endTag(null, TAG_ALL_GRANTS);
19949    }
19950
19951    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19952            throws XmlPullParserException, IOException {
19953        String pkgName = null;
19954        int outerDepth = parser.getDepth();
19955        int type;
19956        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19957                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19958            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19959                continue;
19960            }
19961
19962            final String tagName = parser.getName();
19963            if (tagName.equals(TAG_GRANT)) {
19964                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19965                if (DEBUG_BACKUP) {
19966                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19967                }
19968            } else if (tagName.equals(TAG_PERMISSION)) {
19969
19970                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19971                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19972
19973                int newFlagSet = 0;
19974                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19975                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19976                }
19977                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19978                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19979                }
19980                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19981                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19982                }
19983                if (DEBUG_BACKUP) {
19984                    Slog.v(TAG, "  + Restoring grant:"
19985                            + " pkg=" + pkgName
19986                            + " perm=" + permName
19987                            + " granted=" + isGranted
19988                            + " bits=0x" + Integer.toHexString(newFlagSet));
19989                }
19990                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19991                if (ps != null) {
19992                    // Already installed so we apply the grant immediately
19993                    if (DEBUG_BACKUP) {
19994                        Slog.v(TAG, "        + already installed; applying");
19995                    }
19996                    PermissionsState perms = ps.getPermissionsState();
19997                    BasePermission bp =
19998                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19999                    if (bp != null) {
20000                        if (isGranted) {
20001                            perms.grantRuntimePermission(bp, userId);
20002                        }
20003                        if (newFlagSet != 0) {
20004                            perms.updatePermissionFlags(
20005                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20006                        }
20007                    }
20008                } else {
20009                    // Need to wait for post-restore install to apply the grant
20010                    if (DEBUG_BACKUP) {
20011                        Slog.v(TAG, "        - not yet installed; saving for later");
20012                    }
20013                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20014                            isGranted, newFlagSet, userId);
20015                }
20016            } else {
20017                PackageManagerService.reportSettingsProblem(Log.WARN,
20018                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20019                XmlUtils.skipCurrentTag(parser);
20020            }
20021        }
20022
20023        scheduleWriteSettingsLocked();
20024        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20025    }
20026
20027    @Override
20028    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20029            int sourceUserId, int targetUserId, int flags) {
20030        mContext.enforceCallingOrSelfPermission(
20031                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20032        int callingUid = Binder.getCallingUid();
20033        enforceOwnerRights(ownerPackage, callingUid);
20034        PackageManagerServiceUtils.enforceShellRestriction(
20035                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20036        if (intentFilter.countActions() == 0) {
20037            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20038            return;
20039        }
20040        synchronized (mPackages) {
20041            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20042                    ownerPackage, targetUserId, flags);
20043            CrossProfileIntentResolver resolver =
20044                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20045            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20046            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20047            if (existing != null) {
20048                int size = existing.size();
20049                for (int i = 0; i < size; i++) {
20050                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20051                        return;
20052                    }
20053                }
20054            }
20055            resolver.addFilter(newFilter);
20056            scheduleWritePackageRestrictionsLocked(sourceUserId);
20057        }
20058    }
20059
20060    @Override
20061    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20062        mContext.enforceCallingOrSelfPermission(
20063                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20064        final int callingUid = Binder.getCallingUid();
20065        enforceOwnerRights(ownerPackage, callingUid);
20066        PackageManagerServiceUtils.enforceShellRestriction(
20067                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20068        synchronized (mPackages) {
20069            CrossProfileIntentResolver resolver =
20070                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20071            ArraySet<CrossProfileIntentFilter> set =
20072                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20073            for (CrossProfileIntentFilter filter : set) {
20074                if (filter.getOwnerPackage().equals(ownerPackage)) {
20075                    resolver.removeFilter(filter);
20076                }
20077            }
20078            scheduleWritePackageRestrictionsLocked(sourceUserId);
20079        }
20080    }
20081
20082    // Enforcing that callingUid is owning pkg on userId
20083    private void enforceOwnerRights(String pkg, int callingUid) {
20084        // The system owns everything.
20085        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20086            return;
20087        }
20088        final int callingUserId = UserHandle.getUserId(callingUid);
20089        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20090        if (pi == null) {
20091            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20092                    + callingUserId);
20093        }
20094        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20095            throw new SecurityException("Calling uid " + callingUid
20096                    + " does not own package " + pkg);
20097        }
20098    }
20099
20100    @Override
20101    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20102        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20103            return null;
20104        }
20105        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20106    }
20107
20108    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20109        UserManagerService ums = UserManagerService.getInstance();
20110        if (ums != null) {
20111            final UserInfo parent = ums.getProfileParent(userId);
20112            final int launcherUid = (parent != null) ? parent.id : userId;
20113            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20114            if (launcherComponent != null) {
20115                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20116                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20117                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20118                        .setPackage(launcherComponent.getPackageName());
20119                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20120            }
20121        }
20122    }
20123
20124    /**
20125     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20126     * then reports the most likely home activity or null if there are more than one.
20127     */
20128    private ComponentName getDefaultHomeActivity(int userId) {
20129        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20130        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20131        if (cn != null) {
20132            return cn;
20133        }
20134
20135        // Find the launcher with the highest priority and return that component if there are no
20136        // other home activity with the same priority.
20137        int lastPriority = Integer.MIN_VALUE;
20138        ComponentName lastComponent = null;
20139        final int size = allHomeCandidates.size();
20140        for (int i = 0; i < size; i++) {
20141            final ResolveInfo ri = allHomeCandidates.get(i);
20142            if (ri.priority > lastPriority) {
20143                lastComponent = ri.activityInfo.getComponentName();
20144                lastPriority = ri.priority;
20145            } else if (ri.priority == lastPriority) {
20146                // Two components found with same priority.
20147                lastComponent = null;
20148            }
20149        }
20150        return lastComponent;
20151    }
20152
20153    private Intent getHomeIntent() {
20154        Intent intent = new Intent(Intent.ACTION_MAIN);
20155        intent.addCategory(Intent.CATEGORY_HOME);
20156        intent.addCategory(Intent.CATEGORY_DEFAULT);
20157        return intent;
20158    }
20159
20160    private IntentFilter getHomeFilter() {
20161        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20162        filter.addCategory(Intent.CATEGORY_HOME);
20163        filter.addCategory(Intent.CATEGORY_DEFAULT);
20164        return filter;
20165    }
20166
20167    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20168            int userId) {
20169        Intent intent  = getHomeIntent();
20170        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20171                PackageManager.GET_META_DATA, userId);
20172        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20173                true, false, false, userId);
20174
20175        allHomeCandidates.clear();
20176        if (list != null) {
20177            for (ResolveInfo ri : list) {
20178                allHomeCandidates.add(ri);
20179            }
20180        }
20181        return (preferred == null || preferred.activityInfo == null)
20182                ? null
20183                : new ComponentName(preferred.activityInfo.packageName,
20184                        preferred.activityInfo.name);
20185    }
20186
20187    @Override
20188    public void setHomeActivity(ComponentName comp, int userId) {
20189        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20190            return;
20191        }
20192        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20193        getHomeActivitiesAsUser(homeActivities, userId);
20194
20195        boolean found = false;
20196
20197        final int size = homeActivities.size();
20198        final ComponentName[] set = new ComponentName[size];
20199        for (int i = 0; i < size; i++) {
20200            final ResolveInfo candidate = homeActivities.get(i);
20201            final ActivityInfo info = candidate.activityInfo;
20202            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20203            set[i] = activityName;
20204            if (!found && activityName.equals(comp)) {
20205                found = true;
20206            }
20207        }
20208        if (!found) {
20209            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20210                    + userId);
20211        }
20212        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20213                set, comp, userId);
20214    }
20215
20216    private @Nullable String getSetupWizardPackageName() {
20217        final Intent intent = new Intent(Intent.ACTION_MAIN);
20218        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20219
20220        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20221                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20222                        | MATCH_DISABLED_COMPONENTS,
20223                UserHandle.myUserId());
20224        if (matches.size() == 1) {
20225            return matches.get(0).getComponentInfo().packageName;
20226        } else {
20227            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20228                    + ": matches=" + matches);
20229            return null;
20230        }
20231    }
20232
20233    private @Nullable String getStorageManagerPackageName() {
20234        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20235
20236        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20237                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20238                        | MATCH_DISABLED_COMPONENTS,
20239                UserHandle.myUserId());
20240        if (matches.size() == 1) {
20241            return matches.get(0).getComponentInfo().packageName;
20242        } else {
20243            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20244                    + matches.size() + ": matches=" + matches);
20245            return null;
20246        }
20247    }
20248
20249    @Override
20250    public void setApplicationEnabledSetting(String appPackageName,
20251            int newState, int flags, int userId, String callingPackage) {
20252        if (!sUserManager.exists(userId)) return;
20253        if (callingPackage == null) {
20254            callingPackage = Integer.toString(Binder.getCallingUid());
20255        }
20256        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20257    }
20258
20259    @Override
20260    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20261        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20262        synchronized (mPackages) {
20263            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20264            if (pkgSetting != null) {
20265                pkgSetting.setUpdateAvailable(updateAvailable);
20266            }
20267        }
20268    }
20269
20270    @Override
20271    public void setComponentEnabledSetting(ComponentName componentName,
20272            int newState, int flags, int userId) {
20273        if (!sUserManager.exists(userId)) return;
20274        setEnabledSetting(componentName.getPackageName(),
20275                componentName.getClassName(), newState, flags, userId, null);
20276    }
20277
20278    private void setEnabledSetting(final String packageName, String className, int newState,
20279            final int flags, int userId, String callingPackage) {
20280        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20281              || newState == COMPONENT_ENABLED_STATE_ENABLED
20282              || newState == COMPONENT_ENABLED_STATE_DISABLED
20283              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20284              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20285            throw new IllegalArgumentException("Invalid new component state: "
20286                    + newState);
20287        }
20288        PackageSetting pkgSetting;
20289        final int callingUid = Binder.getCallingUid();
20290        final int permission;
20291        if (callingUid == Process.SYSTEM_UID) {
20292            permission = PackageManager.PERMISSION_GRANTED;
20293        } else {
20294            permission = mContext.checkCallingOrSelfPermission(
20295                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20296        }
20297        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20298                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20299        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20300        boolean sendNow = false;
20301        boolean isApp = (className == null);
20302        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20303        String componentName = isApp ? packageName : className;
20304        int packageUid = -1;
20305        ArrayList<String> components;
20306
20307        // reader
20308        synchronized (mPackages) {
20309            pkgSetting = mSettings.mPackages.get(packageName);
20310            if (pkgSetting == null) {
20311                if (!isCallerInstantApp) {
20312                    if (className == null) {
20313                        throw new IllegalArgumentException("Unknown package: " + packageName);
20314                    }
20315                    throw new IllegalArgumentException(
20316                            "Unknown component: " + packageName + "/" + className);
20317                } else {
20318                    // throw SecurityException to prevent leaking package information
20319                    throw new SecurityException(
20320                            "Attempt to change component state; "
20321                            + "pid=" + Binder.getCallingPid()
20322                            + ", uid=" + callingUid
20323                            + (className == null
20324                                    ? ", package=" + packageName
20325                                    : ", component=" + packageName + "/" + className));
20326                }
20327            }
20328        }
20329
20330        // Limit who can change which apps
20331        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20332            // Don't allow apps that don't have permission to modify other apps
20333            if (!allowedByPermission
20334                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20335                throw new SecurityException(
20336                        "Attempt to change component state; "
20337                        + "pid=" + Binder.getCallingPid()
20338                        + ", uid=" + callingUid
20339                        + (className == null
20340                                ? ", package=" + packageName
20341                                : ", component=" + packageName + "/" + className));
20342            }
20343            // Don't allow changing protected packages.
20344            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20345                throw new SecurityException("Cannot disable a protected package: " + packageName);
20346            }
20347        }
20348
20349        synchronized (mPackages) {
20350            if (callingUid == Process.SHELL_UID
20351                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20352                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20353                // unless it is a test package.
20354                int oldState = pkgSetting.getEnabled(userId);
20355                if (className == null
20356                        &&
20357                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20358                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20359                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20360                        &&
20361                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20362                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20363                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20364                    // ok
20365                } else {
20366                    throw new SecurityException(
20367                            "Shell cannot change component state for " + packageName + "/"
20368                                    + className + " to " + newState);
20369                }
20370            }
20371        }
20372        if (className == null) {
20373            // We're dealing with an application/package level state change
20374            synchronized (mPackages) {
20375                if (pkgSetting.getEnabled(userId) == newState) {
20376                    // Nothing to do
20377                    return;
20378                }
20379            }
20380            // If we're enabling a system stub, there's a little more work to do.
20381            // Prior to enabling the package, we need to decompress the APK(s) to the
20382            // data partition and then replace the version on the system partition.
20383            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20384            final boolean isSystemStub = deletedPkg.isStub
20385                    && deletedPkg.isSystem();
20386            if (isSystemStub
20387                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20388                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20389                final File codePath = decompressPackage(deletedPkg);
20390                if (codePath == null) {
20391                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20392                    return;
20393                }
20394                // TODO remove direct parsing of the package object during internal cleanup
20395                // of scan package
20396                // We need to call parse directly here for no other reason than we need
20397                // the new package in order to disable the old one [we use the information
20398                // for some internal optimization to optionally create a new package setting
20399                // object on replace]. However, we can't get the package from the scan
20400                // because the scan modifies live structures and we need to remove the
20401                // old [system] package from the system before a scan can be attempted.
20402                // Once scan is indempotent we can remove this parse and use the package
20403                // object we scanned, prior to adding it to package settings.
20404                final PackageParser pp = new PackageParser();
20405                pp.setSeparateProcesses(mSeparateProcesses);
20406                pp.setDisplayMetrics(mMetrics);
20407                pp.setCallback(mPackageParserCallback);
20408                final PackageParser.Package tmpPkg;
20409                try {
20410                    final @ParseFlags int parseFlags = mDefParseFlags
20411                            | PackageParser.PARSE_MUST_BE_APK
20412                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20413                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20414                } catch (PackageParserException e) {
20415                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20416                    return;
20417                }
20418                synchronized (mInstallLock) {
20419                    // Disable the stub and remove any package entries
20420                    removePackageLI(deletedPkg, true);
20421                    synchronized (mPackages) {
20422                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20423                    }
20424                    final PackageParser.Package pkg;
20425                    try (PackageFreezer freezer =
20426                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20427                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20428                                | PackageParser.PARSE_ENFORCE_CODE;
20429                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20430                                0 /*currentTime*/, null /*user*/);
20431                        prepareAppDataAfterInstallLIF(pkg);
20432                        synchronized (mPackages) {
20433                            try {
20434                                updateSharedLibrariesLPr(pkg, null);
20435                            } catch (PackageManagerException e) {
20436                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20437                            }
20438                            mPermissionManager.updatePermissions(
20439                                    pkg.packageName, pkg, true, mPackages.values(),
20440                                    mPermissionCallback);
20441                            mSettings.writeLPr();
20442                        }
20443                    } catch (PackageManagerException e) {
20444                        // Whoops! Something went wrong; try to roll back to the stub
20445                        Slog.w(TAG, "Failed to install compressed system package:"
20446                                + pkgSetting.name, e);
20447                        // Remove the failed install
20448                        removeCodePathLI(codePath);
20449
20450                        // Install the system package
20451                        try (PackageFreezer freezer =
20452                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20453                            synchronized (mPackages) {
20454                                // NOTE: The system package always needs to be enabled; even
20455                                // if it's for a compressed stub. If we don't, installing the
20456                                // system package fails during scan [scanning checks the disabled
20457                                // packages]. We will reverse this later, after we've "installed"
20458                                // the stub.
20459                                // This leaves us in a fragile state; the stub should never be
20460                                // enabled, so, cross your fingers and hope nothing goes wrong
20461                                // until we can disable the package later.
20462                                enableSystemPackageLPw(deletedPkg);
20463                            }
20464                            installPackageFromSystemLIF(deletedPkg.codePath,
20465                                    false /*isPrivileged*/, null /*allUserHandles*/,
20466                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20467                                    true /*writeSettings*/);
20468                        } catch (PackageManagerException pme) {
20469                            Slog.w(TAG, "Failed to restore system package:"
20470                                    + deletedPkg.packageName, pme);
20471                        } finally {
20472                            synchronized (mPackages) {
20473                                mSettings.disableSystemPackageLPw(
20474                                        deletedPkg.packageName, true /*replaced*/);
20475                                mSettings.writeLPr();
20476                            }
20477                        }
20478                        return;
20479                    }
20480                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20481                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20482                    mDexManager.notifyPackageUpdated(pkg.packageName,
20483                            pkg.baseCodePath, pkg.splitCodePaths);
20484                }
20485            }
20486            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20487                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20488                // Don't care about who enables an app.
20489                callingPackage = null;
20490            }
20491            synchronized (mPackages) {
20492                pkgSetting.setEnabled(newState, userId, callingPackage);
20493            }
20494        } else {
20495            synchronized (mPackages) {
20496                // We're dealing with a component level state change
20497                // First, verify that this is a valid class name.
20498                PackageParser.Package pkg = pkgSetting.pkg;
20499                if (pkg == null || !pkg.hasComponentClassName(className)) {
20500                    if (pkg != null &&
20501                            pkg.applicationInfo.targetSdkVersion >=
20502                                    Build.VERSION_CODES.JELLY_BEAN) {
20503                        throw new IllegalArgumentException("Component class " + className
20504                                + " does not exist in " + packageName);
20505                    } else {
20506                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20507                                + className + " does not exist in " + packageName);
20508                    }
20509                }
20510                switch (newState) {
20511                    case COMPONENT_ENABLED_STATE_ENABLED:
20512                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20513                            return;
20514                        }
20515                        break;
20516                    case COMPONENT_ENABLED_STATE_DISABLED:
20517                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20518                            return;
20519                        }
20520                        break;
20521                    case COMPONENT_ENABLED_STATE_DEFAULT:
20522                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20523                            return;
20524                        }
20525                        break;
20526                    default:
20527                        Slog.e(TAG, "Invalid new component state: " + newState);
20528                        return;
20529                }
20530            }
20531        }
20532        synchronized (mPackages) {
20533            scheduleWritePackageRestrictionsLocked(userId);
20534            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20535            final long callingId = Binder.clearCallingIdentity();
20536            try {
20537                updateInstantAppInstallerLocked(packageName);
20538            } finally {
20539                Binder.restoreCallingIdentity(callingId);
20540            }
20541            components = mPendingBroadcasts.get(userId, packageName);
20542            final boolean newPackage = components == null;
20543            if (newPackage) {
20544                components = new ArrayList<String>();
20545            }
20546            if (!components.contains(componentName)) {
20547                components.add(componentName);
20548            }
20549            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20550                sendNow = true;
20551                // Purge entry from pending broadcast list if another one exists already
20552                // since we are sending one right away.
20553                mPendingBroadcasts.remove(userId, packageName);
20554            } else {
20555                if (newPackage) {
20556                    mPendingBroadcasts.put(userId, packageName, components);
20557                }
20558                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20559                    // Schedule a message
20560                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20561                }
20562            }
20563        }
20564
20565        long callingId = Binder.clearCallingIdentity();
20566        try {
20567            if (sendNow) {
20568                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20569                sendPackageChangedBroadcast(packageName,
20570                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20571            }
20572        } finally {
20573            Binder.restoreCallingIdentity(callingId);
20574        }
20575    }
20576
20577    @Override
20578    public void flushPackageRestrictionsAsUser(int userId) {
20579        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20580            return;
20581        }
20582        if (!sUserManager.exists(userId)) {
20583            return;
20584        }
20585        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20586                false /* checkShell */, "flushPackageRestrictions");
20587        synchronized (mPackages) {
20588            mSettings.writePackageRestrictionsLPr(userId);
20589            mDirtyUsers.remove(userId);
20590            if (mDirtyUsers.isEmpty()) {
20591                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20592            }
20593        }
20594    }
20595
20596    private void sendPackageChangedBroadcast(String packageName,
20597            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20598        if (DEBUG_INSTALL)
20599            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20600                    + componentNames);
20601        Bundle extras = new Bundle(4);
20602        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20603        String nameList[] = new String[componentNames.size()];
20604        componentNames.toArray(nameList);
20605        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20606        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20607        extras.putInt(Intent.EXTRA_UID, packageUid);
20608        // If this is not reporting a change of the overall package, then only send it
20609        // to registered receivers.  We don't want to launch a swath of apps for every
20610        // little component state change.
20611        final int flags = !componentNames.contains(packageName)
20612                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20613        final int userId = UserHandle.getUserId(packageUid);
20614        final boolean isInstantApp = isInstantApp(packageName, userId);
20615        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20616        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20617        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20618                userIds, instantUserIds);
20619    }
20620
20621    @Override
20622    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20623        if (!sUserManager.exists(userId)) return;
20624        final int callingUid = Binder.getCallingUid();
20625        if (getInstantAppPackageName(callingUid) != null) {
20626            return;
20627        }
20628        final int permission = mContext.checkCallingOrSelfPermission(
20629                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20630        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20631        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20632                true /* requireFullPermission */, true /* checkShell */, "stop package");
20633        // writer
20634        synchronized (mPackages) {
20635            final PackageSetting ps = mSettings.mPackages.get(packageName);
20636            if (!filterAppAccessLPr(ps, callingUid, userId)
20637                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20638                            allowedByPermission, callingUid, userId)) {
20639                scheduleWritePackageRestrictionsLocked(userId);
20640            }
20641        }
20642    }
20643
20644    @Override
20645    public String getInstallerPackageName(String packageName) {
20646        final int callingUid = Binder.getCallingUid();
20647        synchronized (mPackages) {
20648            final PackageSetting ps = mSettings.mPackages.get(packageName);
20649            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20650                return null;
20651            }
20652            return mSettings.getInstallerPackageNameLPr(packageName);
20653        }
20654    }
20655
20656    public boolean isOrphaned(String packageName) {
20657        // reader
20658        synchronized (mPackages) {
20659            return mSettings.isOrphaned(packageName);
20660        }
20661    }
20662
20663    @Override
20664    public int getApplicationEnabledSetting(String packageName, int userId) {
20665        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20666        int callingUid = Binder.getCallingUid();
20667        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20668                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20669        // reader
20670        synchronized (mPackages) {
20671            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20672                return COMPONENT_ENABLED_STATE_DISABLED;
20673            }
20674            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20675        }
20676    }
20677
20678    @Override
20679    public int getComponentEnabledSetting(ComponentName component, int userId) {
20680        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20681        int callingUid = Binder.getCallingUid();
20682        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20683                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20684        synchronized (mPackages) {
20685            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20686                    component, TYPE_UNKNOWN, userId)) {
20687                return COMPONENT_ENABLED_STATE_DISABLED;
20688            }
20689            return mSettings.getComponentEnabledSettingLPr(component, userId);
20690        }
20691    }
20692
20693    @Override
20694    public void enterSafeMode() {
20695        enforceSystemOrRoot("Only the system can request entering safe mode");
20696
20697        if (!mSystemReady) {
20698            mSafeMode = true;
20699        }
20700    }
20701
20702    @Override
20703    public void systemReady() {
20704        enforceSystemOrRoot("Only the system can claim the system is ready");
20705
20706        mSystemReady = true;
20707        final ContentResolver resolver = mContext.getContentResolver();
20708        ContentObserver co = new ContentObserver(mHandler) {
20709            @Override
20710            public void onChange(boolean selfChange) {
20711                mWebInstantAppsDisabled =
20712                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20713                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20714            }
20715        };
20716        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20717                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20718                false, co, UserHandle.USER_SYSTEM);
20719        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20720                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20721        co.onChange(true);
20722
20723        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20724        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20725        // it is done.
20726        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20727            @Override
20728            public void onChange(boolean selfChange) {
20729                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20730                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20731                        oobEnabled == 1 ? "true" : "false");
20732            }
20733        };
20734        mContext.getContentResolver().registerContentObserver(
20735                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20736                UserHandle.USER_SYSTEM);
20737        // At boot, restore the value from the setting, which persists across reboot.
20738        privAppOobObserver.onChange(true);
20739
20740        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20741        // disabled after already being started.
20742        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20743                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20744
20745        // Read the compatibilty setting when the system is ready.
20746        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20747                mContext.getContentResolver(),
20748                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20749        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20750        if (DEBUG_SETTINGS) {
20751            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20752        }
20753
20754        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20755
20756        synchronized (mPackages) {
20757            // Verify that all of the preferred activity components actually
20758            // exist.  It is possible for applications to be updated and at
20759            // that point remove a previously declared activity component that
20760            // had been set as a preferred activity.  We try to clean this up
20761            // the next time we encounter that preferred activity, but it is
20762            // possible for the user flow to never be able to return to that
20763            // situation so here we do a sanity check to make sure we haven't
20764            // left any junk around.
20765            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20766            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20767                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20768                removed.clear();
20769                for (PreferredActivity pa : pir.filterSet()) {
20770                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20771                        removed.add(pa);
20772                    }
20773                }
20774                if (removed.size() > 0) {
20775                    for (int r=0; r<removed.size(); r++) {
20776                        PreferredActivity pa = removed.get(r);
20777                        Slog.w(TAG, "Removing dangling preferred activity: "
20778                                + pa.mPref.mComponent);
20779                        pir.removeFilter(pa);
20780                    }
20781                    mSettings.writePackageRestrictionsLPr(
20782                            mSettings.mPreferredActivities.keyAt(i));
20783                }
20784            }
20785
20786            for (int userId : UserManagerService.getInstance().getUserIds()) {
20787                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20788                    grantPermissionsUserIds = ArrayUtils.appendInt(
20789                            grantPermissionsUserIds, userId);
20790                }
20791            }
20792        }
20793        sUserManager.systemReady();
20794        // If we upgraded grant all default permissions before kicking off.
20795        for (int userId : grantPermissionsUserIds) {
20796            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20797        }
20798
20799        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20800            // If we did not grant default permissions, we preload from this the
20801            // default permission exceptions lazily to ensure we don't hit the
20802            // disk on a new user creation.
20803            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20804        }
20805
20806        // Now that we've scanned all packages, and granted any default
20807        // permissions, ensure permissions are updated. Beware of dragons if you
20808        // try optimizing this.
20809        synchronized (mPackages) {
20810            mPermissionManager.updateAllPermissions(
20811                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20812                    mPermissionCallback);
20813        }
20814
20815        // Kick off any messages waiting for system ready
20816        if (mPostSystemReadyMessages != null) {
20817            for (Message msg : mPostSystemReadyMessages) {
20818                msg.sendToTarget();
20819            }
20820            mPostSystemReadyMessages = null;
20821        }
20822
20823        // Watch for external volumes that come and go over time
20824        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20825        storage.registerListener(mStorageListener);
20826
20827        mInstallerService.systemReady();
20828        mPackageDexOptimizer.systemReady();
20829
20830        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20831                StorageManagerInternal.class);
20832        StorageManagerInternal.addExternalStoragePolicy(
20833                new StorageManagerInternal.ExternalStorageMountPolicy() {
20834            @Override
20835            public int getMountMode(int uid, String packageName) {
20836                if (Process.isIsolated(uid)) {
20837                    return Zygote.MOUNT_EXTERNAL_NONE;
20838                }
20839                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20840                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20841                }
20842                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20843                    return Zygote.MOUNT_EXTERNAL_READ;
20844                }
20845                return Zygote.MOUNT_EXTERNAL_WRITE;
20846            }
20847
20848            @Override
20849            public boolean hasExternalStorage(int uid, String packageName) {
20850                return true;
20851            }
20852        });
20853
20854        // Now that we're mostly running, clean up stale users and apps
20855        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20856        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20857
20858        mPermissionManager.systemReady();
20859    }
20860
20861    public void waitForAppDataPrepared() {
20862        if (mPrepareAppDataFuture == null) {
20863            return;
20864        }
20865        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20866        mPrepareAppDataFuture = null;
20867    }
20868
20869    @Override
20870    public boolean isSafeMode() {
20871        // allow instant applications
20872        return mSafeMode;
20873    }
20874
20875    @Override
20876    public boolean hasSystemUidErrors() {
20877        // allow instant applications
20878        return mHasSystemUidErrors;
20879    }
20880
20881    static String arrayToString(int[] array) {
20882        StringBuffer buf = new StringBuffer(128);
20883        buf.append('[');
20884        if (array != null) {
20885            for (int i=0; i<array.length; i++) {
20886                if (i > 0) buf.append(", ");
20887                buf.append(array[i]);
20888            }
20889        }
20890        buf.append(']');
20891        return buf.toString();
20892    }
20893
20894    @Override
20895    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20896            FileDescriptor err, String[] args, ShellCallback callback,
20897            ResultReceiver resultReceiver) {
20898        (new PackageManagerShellCommand(this)).exec(
20899                this, in, out, err, args, callback, resultReceiver);
20900    }
20901
20902    @Override
20903    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20904        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20905
20906        DumpState dumpState = new DumpState();
20907        boolean fullPreferred = false;
20908        boolean checkin = false;
20909
20910        String packageName = null;
20911        ArraySet<String> permissionNames = null;
20912
20913        int opti = 0;
20914        while (opti < args.length) {
20915            String opt = args[opti];
20916            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20917                break;
20918            }
20919            opti++;
20920
20921            if ("-a".equals(opt)) {
20922                // Right now we only know how to print all.
20923            } else if ("-h".equals(opt)) {
20924                pw.println("Package manager dump options:");
20925                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20926                pw.println("    --checkin: dump for a checkin");
20927                pw.println("    -f: print details of intent filters");
20928                pw.println("    -h: print this help");
20929                pw.println("  cmd may be one of:");
20930                pw.println("    l[ibraries]: list known shared libraries");
20931                pw.println("    f[eatures]: list device features");
20932                pw.println("    k[eysets]: print known keysets");
20933                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20934                pw.println("    perm[issions]: dump permissions");
20935                pw.println("    permission [name ...]: dump declaration and use of given permission");
20936                pw.println("    pref[erred]: print preferred package settings");
20937                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20938                pw.println("    prov[iders]: dump content providers");
20939                pw.println("    p[ackages]: dump installed packages");
20940                pw.println("    s[hared-users]: dump shared user IDs");
20941                pw.println("    m[essages]: print collected runtime messages");
20942                pw.println("    v[erifiers]: print package verifier info");
20943                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20944                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20945                pw.println("    version: print database version info");
20946                pw.println("    write: write current settings now");
20947                pw.println("    installs: details about install sessions");
20948                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20949                pw.println("    dexopt: dump dexopt state");
20950                pw.println("    compiler-stats: dump compiler statistics");
20951                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20952                pw.println("    service-permissions: dump permissions required by services");
20953                pw.println("    <package.name>: info about given package");
20954                return;
20955            } else if ("--checkin".equals(opt)) {
20956                checkin = true;
20957            } else if ("-f".equals(opt)) {
20958                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20959            } else if ("--proto".equals(opt)) {
20960                dumpProto(fd);
20961                return;
20962            } else {
20963                pw.println("Unknown argument: " + opt + "; use -h for help");
20964            }
20965        }
20966
20967        // Is the caller requesting to dump a particular piece of data?
20968        if (opti < args.length) {
20969            String cmd = args[opti];
20970            opti++;
20971            // Is this a package name?
20972            if ("android".equals(cmd) || cmd.contains(".")) {
20973                packageName = cmd;
20974                // When dumping a single package, we always dump all of its
20975                // filter information since the amount of data will be reasonable.
20976                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20977            } else if ("check-permission".equals(cmd)) {
20978                if (opti >= args.length) {
20979                    pw.println("Error: check-permission missing permission argument");
20980                    return;
20981                }
20982                String perm = args[opti];
20983                opti++;
20984                if (opti >= args.length) {
20985                    pw.println("Error: check-permission missing package argument");
20986                    return;
20987                }
20988
20989                String pkg = args[opti];
20990                opti++;
20991                int user = UserHandle.getUserId(Binder.getCallingUid());
20992                if (opti < args.length) {
20993                    try {
20994                        user = Integer.parseInt(args[opti]);
20995                    } catch (NumberFormatException e) {
20996                        pw.println("Error: check-permission user argument is not a number: "
20997                                + args[opti]);
20998                        return;
20999                    }
21000                }
21001
21002                // Normalize package name to handle renamed packages and static libs
21003                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21004
21005                pw.println(checkPermission(perm, pkg, user));
21006                return;
21007            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21008                dumpState.setDump(DumpState.DUMP_LIBS);
21009            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21010                dumpState.setDump(DumpState.DUMP_FEATURES);
21011            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21012                if (opti >= args.length) {
21013                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21014                            | DumpState.DUMP_SERVICE_RESOLVERS
21015                            | DumpState.DUMP_RECEIVER_RESOLVERS
21016                            | DumpState.DUMP_CONTENT_RESOLVERS);
21017                } else {
21018                    while (opti < args.length) {
21019                        String name = args[opti];
21020                        if ("a".equals(name) || "activity".equals(name)) {
21021                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21022                        } else if ("s".equals(name) || "service".equals(name)) {
21023                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21024                        } else if ("r".equals(name) || "receiver".equals(name)) {
21025                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21026                        } else if ("c".equals(name) || "content".equals(name)) {
21027                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21028                        } else {
21029                            pw.println("Error: unknown resolver table type: " + name);
21030                            return;
21031                        }
21032                        opti++;
21033                    }
21034                }
21035            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21036                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21037            } else if ("permission".equals(cmd)) {
21038                if (opti >= args.length) {
21039                    pw.println("Error: permission requires permission name");
21040                    return;
21041                }
21042                permissionNames = new ArraySet<>();
21043                while (opti < args.length) {
21044                    permissionNames.add(args[opti]);
21045                    opti++;
21046                }
21047                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21048                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21049            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21050                dumpState.setDump(DumpState.DUMP_PREFERRED);
21051            } else if ("preferred-xml".equals(cmd)) {
21052                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21053                if (opti < args.length && "--full".equals(args[opti])) {
21054                    fullPreferred = true;
21055                    opti++;
21056                }
21057            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21058                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21059            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21060                dumpState.setDump(DumpState.DUMP_PACKAGES);
21061            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21062                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21063            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21064                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21065            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21066                dumpState.setDump(DumpState.DUMP_MESSAGES);
21067            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21068                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21069            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21070                    || "intent-filter-verifiers".equals(cmd)) {
21071                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21072            } else if ("version".equals(cmd)) {
21073                dumpState.setDump(DumpState.DUMP_VERSION);
21074            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21075                dumpState.setDump(DumpState.DUMP_KEYSETS);
21076            } else if ("installs".equals(cmd)) {
21077                dumpState.setDump(DumpState.DUMP_INSTALLS);
21078            } else if ("frozen".equals(cmd)) {
21079                dumpState.setDump(DumpState.DUMP_FROZEN);
21080            } else if ("volumes".equals(cmd)) {
21081                dumpState.setDump(DumpState.DUMP_VOLUMES);
21082            } else if ("dexopt".equals(cmd)) {
21083                dumpState.setDump(DumpState.DUMP_DEXOPT);
21084            } else if ("compiler-stats".equals(cmd)) {
21085                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21086            } else if ("changes".equals(cmd)) {
21087                dumpState.setDump(DumpState.DUMP_CHANGES);
21088            } else if ("service-permissions".equals(cmd)) {
21089                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21090            } else if ("write".equals(cmd)) {
21091                synchronized (mPackages) {
21092                    mSettings.writeLPr();
21093                    pw.println("Settings written.");
21094                    return;
21095                }
21096            }
21097        }
21098
21099        if (checkin) {
21100            pw.println("vers,1");
21101        }
21102
21103        // reader
21104        synchronized (mPackages) {
21105            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21106                if (!checkin) {
21107                    if (dumpState.onTitlePrinted())
21108                        pw.println();
21109                    pw.println("Database versions:");
21110                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21111                }
21112            }
21113
21114            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21115                if (!checkin) {
21116                    if (dumpState.onTitlePrinted())
21117                        pw.println();
21118                    pw.println("Verifiers:");
21119                    pw.print("  Required: ");
21120                    pw.print(mRequiredVerifierPackage);
21121                    pw.print(" (uid=");
21122                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21123                            UserHandle.USER_SYSTEM));
21124                    pw.println(")");
21125                } else if (mRequiredVerifierPackage != null) {
21126                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21127                    pw.print(",");
21128                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21129                            UserHandle.USER_SYSTEM));
21130                }
21131            }
21132
21133            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21134                    packageName == null) {
21135                if (mIntentFilterVerifierComponent != null) {
21136                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21137                    if (!checkin) {
21138                        if (dumpState.onTitlePrinted())
21139                            pw.println();
21140                        pw.println("Intent Filter Verifier:");
21141                        pw.print("  Using: ");
21142                        pw.print(verifierPackageName);
21143                        pw.print(" (uid=");
21144                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21145                                UserHandle.USER_SYSTEM));
21146                        pw.println(")");
21147                    } else if (verifierPackageName != null) {
21148                        pw.print("ifv,"); pw.print(verifierPackageName);
21149                        pw.print(",");
21150                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21151                                UserHandle.USER_SYSTEM));
21152                    }
21153                } else {
21154                    pw.println();
21155                    pw.println("No Intent Filter Verifier available!");
21156                }
21157            }
21158
21159            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21160                boolean printedHeader = false;
21161                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21162                while (it.hasNext()) {
21163                    String libName = it.next();
21164                    LongSparseArray<SharedLibraryEntry> versionedLib
21165                            = mSharedLibraries.get(libName);
21166                    if (versionedLib == null) {
21167                        continue;
21168                    }
21169                    final int versionCount = versionedLib.size();
21170                    for (int i = 0; i < versionCount; i++) {
21171                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21172                        if (!checkin) {
21173                            if (!printedHeader) {
21174                                if (dumpState.onTitlePrinted())
21175                                    pw.println();
21176                                pw.println("Libraries:");
21177                                printedHeader = true;
21178                            }
21179                            pw.print("  ");
21180                        } else {
21181                            pw.print("lib,");
21182                        }
21183                        pw.print(libEntry.info.getName());
21184                        if (libEntry.info.isStatic()) {
21185                            pw.print(" version=" + libEntry.info.getLongVersion());
21186                        }
21187                        if (!checkin) {
21188                            pw.print(" -> ");
21189                        }
21190                        if (libEntry.path != null) {
21191                            pw.print(" (jar) ");
21192                            pw.print(libEntry.path);
21193                        } else {
21194                            pw.print(" (apk) ");
21195                            pw.print(libEntry.apk);
21196                        }
21197                        pw.println();
21198                    }
21199                }
21200            }
21201
21202            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21203                if (dumpState.onTitlePrinted())
21204                    pw.println();
21205                if (!checkin) {
21206                    pw.println("Features:");
21207                }
21208
21209                synchronized (mAvailableFeatures) {
21210                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21211                        if (checkin) {
21212                            pw.print("feat,");
21213                            pw.print(feat.name);
21214                            pw.print(",");
21215                            pw.println(feat.version);
21216                        } else {
21217                            pw.print("  ");
21218                            pw.print(feat.name);
21219                            if (feat.version > 0) {
21220                                pw.print(" version=");
21221                                pw.print(feat.version);
21222                            }
21223                            pw.println();
21224                        }
21225                    }
21226                }
21227            }
21228
21229            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21230                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21231                        : "Activity Resolver Table:", "  ", packageName,
21232                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21233                    dumpState.setTitlePrinted(true);
21234                }
21235            }
21236            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21237                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21238                        : "Receiver Resolver Table:", "  ", packageName,
21239                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21240                    dumpState.setTitlePrinted(true);
21241                }
21242            }
21243            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21244                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21245                        : "Service Resolver Table:", "  ", packageName,
21246                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21247                    dumpState.setTitlePrinted(true);
21248                }
21249            }
21250            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21251                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21252                        : "Provider Resolver Table:", "  ", packageName,
21253                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21254                    dumpState.setTitlePrinted(true);
21255                }
21256            }
21257
21258            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21259                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21260                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21261                    int user = mSettings.mPreferredActivities.keyAt(i);
21262                    if (pir.dump(pw,
21263                            dumpState.getTitlePrinted()
21264                                ? "\nPreferred Activities User " + user + ":"
21265                                : "Preferred Activities User " + user + ":", "  ",
21266                            packageName, true, false)) {
21267                        dumpState.setTitlePrinted(true);
21268                    }
21269                }
21270            }
21271
21272            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21273                pw.flush();
21274                FileOutputStream fout = new FileOutputStream(fd);
21275                BufferedOutputStream str = new BufferedOutputStream(fout);
21276                XmlSerializer serializer = new FastXmlSerializer();
21277                try {
21278                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21279                    serializer.startDocument(null, true);
21280                    serializer.setFeature(
21281                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21282                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21283                    serializer.endDocument();
21284                    serializer.flush();
21285                } catch (IllegalArgumentException e) {
21286                    pw.println("Failed writing: " + e);
21287                } catch (IllegalStateException e) {
21288                    pw.println("Failed writing: " + e);
21289                } catch (IOException e) {
21290                    pw.println("Failed writing: " + e);
21291                }
21292            }
21293
21294            if (!checkin
21295                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21296                    && packageName == null) {
21297                pw.println();
21298                int count = mSettings.mPackages.size();
21299                if (count == 0) {
21300                    pw.println("No applications!");
21301                    pw.println();
21302                } else {
21303                    final String prefix = "  ";
21304                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21305                    if (allPackageSettings.size() == 0) {
21306                        pw.println("No domain preferred apps!");
21307                        pw.println();
21308                    } else {
21309                        pw.println("App verification status:");
21310                        pw.println();
21311                        count = 0;
21312                        for (PackageSetting ps : allPackageSettings) {
21313                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21314                            if (ivi == null || ivi.getPackageName() == null) continue;
21315                            pw.println(prefix + "Package: " + ivi.getPackageName());
21316                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21317                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21318                            pw.println();
21319                            count++;
21320                        }
21321                        if (count == 0) {
21322                            pw.println(prefix + "No app verification established.");
21323                            pw.println();
21324                        }
21325                        for (int userId : sUserManager.getUserIds()) {
21326                            pw.println("App linkages for user " + userId + ":");
21327                            pw.println();
21328                            count = 0;
21329                            for (PackageSetting ps : allPackageSettings) {
21330                                final long status = ps.getDomainVerificationStatusForUser(userId);
21331                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21332                                        && !DEBUG_DOMAIN_VERIFICATION) {
21333                                    continue;
21334                                }
21335                                pw.println(prefix + "Package: " + ps.name);
21336                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21337                                String statusStr = IntentFilterVerificationInfo.
21338                                        getStatusStringFromValue(status);
21339                                pw.println(prefix + "Status:  " + statusStr);
21340                                pw.println();
21341                                count++;
21342                            }
21343                            if (count == 0) {
21344                                pw.println(prefix + "No configured app linkages.");
21345                                pw.println();
21346                            }
21347                        }
21348                    }
21349                }
21350            }
21351
21352            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21353                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21354            }
21355
21356            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21357                boolean printedSomething = false;
21358                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21359                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21360                        continue;
21361                    }
21362                    if (!printedSomething) {
21363                        if (dumpState.onTitlePrinted())
21364                            pw.println();
21365                        pw.println("Registered ContentProviders:");
21366                        printedSomething = true;
21367                    }
21368                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21369                    pw.print("    "); pw.println(p.toString());
21370                }
21371                printedSomething = false;
21372                for (Map.Entry<String, PackageParser.Provider> entry :
21373                        mProvidersByAuthority.entrySet()) {
21374                    PackageParser.Provider p = entry.getValue();
21375                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21376                        continue;
21377                    }
21378                    if (!printedSomething) {
21379                        if (dumpState.onTitlePrinted())
21380                            pw.println();
21381                        pw.println("ContentProvider Authorities:");
21382                        printedSomething = true;
21383                    }
21384                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21385                    pw.print("    "); pw.println(p.toString());
21386                    if (p.info != null && p.info.applicationInfo != null) {
21387                        final String appInfo = p.info.applicationInfo.toString();
21388                        pw.print("      applicationInfo="); pw.println(appInfo);
21389                    }
21390                }
21391            }
21392
21393            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21394                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21395            }
21396
21397            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21398                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21399            }
21400
21401            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21402                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21403            }
21404
21405            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21406                if (dumpState.onTitlePrinted()) pw.println();
21407                pw.println("Package Changes:");
21408                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21409                final int K = mChangedPackages.size();
21410                for (int i = 0; i < K; i++) {
21411                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21412                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21413                    final int N = changes.size();
21414                    if (N == 0) {
21415                        pw.print("    "); pw.println("No packages changed");
21416                    } else {
21417                        for (int j = 0; j < N; j++) {
21418                            final String pkgName = changes.valueAt(j);
21419                            final int sequenceNumber = changes.keyAt(j);
21420                            pw.print("    ");
21421                            pw.print("seq=");
21422                            pw.print(sequenceNumber);
21423                            pw.print(", package=");
21424                            pw.println(pkgName);
21425                        }
21426                    }
21427                }
21428            }
21429
21430            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21431                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21432            }
21433
21434            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21435                // XXX should handle packageName != null by dumping only install data that
21436                // the given package is involved with.
21437                if (dumpState.onTitlePrinted()) pw.println();
21438
21439                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21440                    ipw.println();
21441                    ipw.println("Frozen packages:");
21442                    ipw.increaseIndent();
21443                    if (mFrozenPackages.size() == 0) {
21444                        ipw.println("(none)");
21445                    } else {
21446                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21447                            ipw.println(mFrozenPackages.valueAt(i));
21448                        }
21449                    }
21450                    ipw.decreaseIndent();
21451                }
21452            }
21453
21454            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21455                if (dumpState.onTitlePrinted()) pw.println();
21456
21457                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21458                    ipw.println();
21459                    ipw.println("Loaded volumes:");
21460                    ipw.increaseIndent();
21461                    if (mLoadedVolumes.size() == 0) {
21462                        ipw.println("(none)");
21463                    } else {
21464                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21465                            ipw.println(mLoadedVolumes.valueAt(i));
21466                        }
21467                    }
21468                    ipw.decreaseIndent();
21469                }
21470            }
21471
21472            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21473                    && packageName == null) {
21474                if (dumpState.onTitlePrinted()) pw.println();
21475                pw.println("Service permissions:");
21476
21477                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21478                while (filterIterator.hasNext()) {
21479                    final ServiceIntentInfo info = filterIterator.next();
21480                    final ServiceInfo serviceInfo = info.service.info;
21481                    final String permission = serviceInfo.permission;
21482                    if (permission != null) {
21483                        pw.print("    ");
21484                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21485                        pw.print(": ");
21486                        pw.println(permission);
21487                    }
21488                }
21489            }
21490
21491            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21492                if (dumpState.onTitlePrinted()) pw.println();
21493                dumpDexoptStateLPr(pw, packageName);
21494            }
21495
21496            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21497                if (dumpState.onTitlePrinted()) pw.println();
21498                dumpCompilerStatsLPr(pw, packageName);
21499            }
21500
21501            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21502                if (dumpState.onTitlePrinted()) pw.println();
21503                mSettings.dumpReadMessagesLPr(pw, dumpState);
21504
21505                pw.println();
21506                pw.println("Package warning messages:");
21507                dumpCriticalInfo(pw, null);
21508            }
21509
21510            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21511                dumpCriticalInfo(pw, "msg,");
21512            }
21513        }
21514
21515        // PackageInstaller should be called outside of mPackages lock
21516        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21517            // XXX should handle packageName != null by dumping only install data that
21518            // the given package is involved with.
21519            if (dumpState.onTitlePrinted()) pw.println();
21520            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21521        }
21522    }
21523
21524    private void dumpProto(FileDescriptor fd) {
21525        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21526
21527        synchronized (mPackages) {
21528            final long requiredVerifierPackageToken =
21529                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21530            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21531            proto.write(
21532                    PackageServiceDumpProto.PackageShortProto.UID,
21533                    getPackageUid(
21534                            mRequiredVerifierPackage,
21535                            MATCH_DEBUG_TRIAGED_MISSING,
21536                            UserHandle.USER_SYSTEM));
21537            proto.end(requiredVerifierPackageToken);
21538
21539            if (mIntentFilterVerifierComponent != null) {
21540                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21541                final long verifierPackageToken =
21542                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21543                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21544                proto.write(
21545                        PackageServiceDumpProto.PackageShortProto.UID,
21546                        getPackageUid(
21547                                verifierPackageName,
21548                                MATCH_DEBUG_TRIAGED_MISSING,
21549                                UserHandle.USER_SYSTEM));
21550                proto.end(verifierPackageToken);
21551            }
21552
21553            dumpSharedLibrariesProto(proto);
21554            dumpFeaturesProto(proto);
21555            mSettings.dumpPackagesProto(proto);
21556            mSettings.dumpSharedUsersProto(proto);
21557            dumpCriticalInfo(proto);
21558        }
21559        proto.flush();
21560    }
21561
21562    private void dumpFeaturesProto(ProtoOutputStream proto) {
21563        synchronized (mAvailableFeatures) {
21564            final int count = mAvailableFeatures.size();
21565            for (int i = 0; i < count; i++) {
21566                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21567            }
21568        }
21569    }
21570
21571    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21572        final int count = mSharedLibraries.size();
21573        for (int i = 0; i < count; i++) {
21574            final String libName = mSharedLibraries.keyAt(i);
21575            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21576            if (versionedLib == null) {
21577                continue;
21578            }
21579            final int versionCount = versionedLib.size();
21580            for (int j = 0; j < versionCount; j++) {
21581                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21582                final long sharedLibraryToken =
21583                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21584                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21585                final boolean isJar = (libEntry.path != null);
21586                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21587                if (isJar) {
21588                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21589                } else {
21590                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21591                }
21592                proto.end(sharedLibraryToken);
21593            }
21594        }
21595    }
21596
21597    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21598        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21599            ipw.println();
21600            ipw.println("Dexopt state:");
21601            ipw.increaseIndent();
21602            Collection<PackageParser.Package> packages = null;
21603            if (packageName != null) {
21604                PackageParser.Package targetPackage = mPackages.get(packageName);
21605                if (targetPackage != null) {
21606                    packages = Collections.singletonList(targetPackage);
21607                } else {
21608                    ipw.println("Unable to find package: " + packageName);
21609                    return;
21610                }
21611            } else {
21612                packages = mPackages.values();
21613            }
21614
21615            for (PackageParser.Package pkg : packages) {
21616                ipw.println("[" + pkg.packageName + "]");
21617                ipw.increaseIndent();
21618                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21619                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21620                ipw.decreaseIndent();
21621            }
21622        }
21623    }
21624
21625    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21626        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21627            ipw.println();
21628            ipw.println("Compiler stats:");
21629            ipw.increaseIndent();
21630            Collection<PackageParser.Package> packages = null;
21631            if (packageName != null) {
21632                PackageParser.Package targetPackage = mPackages.get(packageName);
21633                if (targetPackage != null) {
21634                    packages = Collections.singletonList(targetPackage);
21635                } else {
21636                    ipw.println("Unable to find package: " + packageName);
21637                    return;
21638                }
21639            } else {
21640                packages = mPackages.values();
21641            }
21642
21643            for (PackageParser.Package pkg : packages) {
21644                ipw.println("[" + pkg.packageName + "]");
21645                ipw.increaseIndent();
21646
21647                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21648                if (stats == null) {
21649                    ipw.println("(No recorded stats)");
21650                } else {
21651                    stats.dump(ipw);
21652                }
21653                ipw.decreaseIndent();
21654            }
21655        }
21656    }
21657
21658    private String dumpDomainString(String packageName) {
21659        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21660                .getList();
21661        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21662
21663        ArraySet<String> result = new ArraySet<>();
21664        if (iviList.size() > 0) {
21665            for (IntentFilterVerificationInfo ivi : iviList) {
21666                for (String host : ivi.getDomains()) {
21667                    result.add(host);
21668                }
21669            }
21670        }
21671        if (filters != null && filters.size() > 0) {
21672            for (IntentFilter filter : filters) {
21673                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21674                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21675                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21676                    result.addAll(filter.getHostsList());
21677                }
21678            }
21679        }
21680
21681        StringBuilder sb = new StringBuilder(result.size() * 16);
21682        for (String domain : result) {
21683            if (sb.length() > 0) sb.append(" ");
21684            sb.append(domain);
21685        }
21686        return sb.toString();
21687    }
21688
21689    // ------- apps on sdcard specific code -------
21690    static final boolean DEBUG_SD_INSTALL = false;
21691
21692    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21693
21694    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21695
21696    private boolean mMediaMounted = false;
21697
21698    static String getEncryptKey() {
21699        try {
21700            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21701                    SD_ENCRYPTION_KEYSTORE_NAME);
21702            if (sdEncKey == null) {
21703                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21704                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21705                if (sdEncKey == null) {
21706                    Slog.e(TAG, "Failed to create encryption keys");
21707                    return null;
21708                }
21709            }
21710            return sdEncKey;
21711        } catch (NoSuchAlgorithmException nsae) {
21712            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21713            return null;
21714        } catch (IOException ioe) {
21715            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21716            return null;
21717        }
21718    }
21719
21720    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21721            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21722        final int size = infos.size();
21723        final String[] packageNames = new String[size];
21724        final int[] packageUids = new int[size];
21725        for (int i = 0; i < size; i++) {
21726            final ApplicationInfo info = infos.get(i);
21727            packageNames[i] = info.packageName;
21728            packageUids[i] = info.uid;
21729        }
21730        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21731                finishedReceiver);
21732    }
21733
21734    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21735            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21736        sendResourcesChangedBroadcast(mediaStatus, replacing,
21737                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21738    }
21739
21740    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21741            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21742        int size = pkgList.length;
21743        if (size > 0) {
21744            // Send broadcasts here
21745            Bundle extras = new Bundle();
21746            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21747            if (uidArr != null) {
21748                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21749            }
21750            if (replacing) {
21751                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21752            }
21753            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21754                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21755            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21756        }
21757    }
21758
21759    private void loadPrivatePackages(final VolumeInfo vol) {
21760        mHandler.post(new Runnable() {
21761            @Override
21762            public void run() {
21763                loadPrivatePackagesInner(vol);
21764            }
21765        });
21766    }
21767
21768    private void loadPrivatePackagesInner(VolumeInfo vol) {
21769        final String volumeUuid = vol.fsUuid;
21770        if (TextUtils.isEmpty(volumeUuid)) {
21771            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21772            return;
21773        }
21774
21775        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21776        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21777        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21778
21779        final VersionInfo ver;
21780        final List<PackageSetting> packages;
21781        synchronized (mPackages) {
21782            ver = mSettings.findOrCreateVersion(volumeUuid);
21783            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21784        }
21785
21786        for (PackageSetting ps : packages) {
21787            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21788            synchronized (mInstallLock) {
21789                final PackageParser.Package pkg;
21790                try {
21791                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21792                    loaded.add(pkg.applicationInfo);
21793
21794                } catch (PackageManagerException e) {
21795                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21796                }
21797
21798                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21799                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21800                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21801                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21802                }
21803            }
21804        }
21805
21806        // Reconcile app data for all started/unlocked users
21807        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21808        final UserManager um = mContext.getSystemService(UserManager.class);
21809        UserManagerInternal umInternal = getUserManagerInternal();
21810        for (UserInfo user : um.getUsers()) {
21811            final int flags;
21812            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21813                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21814            } else if (umInternal.isUserRunning(user.id)) {
21815                flags = StorageManager.FLAG_STORAGE_DE;
21816            } else {
21817                continue;
21818            }
21819
21820            try {
21821                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21822                synchronized (mInstallLock) {
21823                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21824                }
21825            } catch (IllegalStateException e) {
21826                // Device was probably ejected, and we'll process that event momentarily
21827                Slog.w(TAG, "Failed to prepare storage: " + e);
21828            }
21829        }
21830
21831        synchronized (mPackages) {
21832            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21833            if (sdkUpdated) {
21834                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21835                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21836            }
21837            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21838                    mPermissionCallback);
21839
21840            // Yay, everything is now upgraded
21841            ver.forceCurrent();
21842
21843            mSettings.writeLPr();
21844        }
21845
21846        for (PackageFreezer freezer : freezers) {
21847            freezer.close();
21848        }
21849
21850        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21851        sendResourcesChangedBroadcast(true, false, loaded, null);
21852        mLoadedVolumes.add(vol.getId());
21853    }
21854
21855    private void unloadPrivatePackages(final VolumeInfo vol) {
21856        mHandler.post(new Runnable() {
21857            @Override
21858            public void run() {
21859                unloadPrivatePackagesInner(vol);
21860            }
21861        });
21862    }
21863
21864    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21865        final String volumeUuid = vol.fsUuid;
21866        if (TextUtils.isEmpty(volumeUuid)) {
21867            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21868            return;
21869        }
21870
21871        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21872        synchronized (mInstallLock) {
21873        synchronized (mPackages) {
21874            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21875            for (PackageSetting ps : packages) {
21876                if (ps.pkg == null) continue;
21877
21878                final ApplicationInfo info = ps.pkg.applicationInfo;
21879                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21880                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21881
21882                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21883                        "unloadPrivatePackagesInner")) {
21884                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21885                            false, null)) {
21886                        unloaded.add(info);
21887                    } else {
21888                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21889                    }
21890                }
21891
21892                // Try very hard to release any references to this package
21893                // so we don't risk the system server being killed due to
21894                // open FDs
21895                AttributeCache.instance().removePackage(ps.name);
21896            }
21897
21898            mSettings.writeLPr();
21899        }
21900        }
21901
21902        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21903        sendResourcesChangedBroadcast(false, false, unloaded, null);
21904        mLoadedVolumes.remove(vol.getId());
21905
21906        // Try very hard to release any references to this path so we don't risk
21907        // the system server being killed due to open FDs
21908        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21909
21910        for (int i = 0; i < 3; i++) {
21911            System.gc();
21912            System.runFinalization();
21913        }
21914    }
21915
21916    private void assertPackageKnown(String volumeUuid, String packageName)
21917            throws PackageManagerException {
21918        synchronized (mPackages) {
21919            // Normalize package name to handle renamed packages
21920            packageName = normalizePackageNameLPr(packageName);
21921
21922            final PackageSetting ps = mSettings.mPackages.get(packageName);
21923            if (ps == null) {
21924                throw new PackageManagerException("Package " + packageName + " is unknown");
21925            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21926                throw new PackageManagerException(
21927                        "Package " + packageName + " found on unknown volume " + volumeUuid
21928                                + "; expected volume " + ps.volumeUuid);
21929            }
21930        }
21931    }
21932
21933    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21934            throws PackageManagerException {
21935        synchronized (mPackages) {
21936            // Normalize package name to handle renamed packages
21937            packageName = normalizePackageNameLPr(packageName);
21938
21939            final PackageSetting ps = mSettings.mPackages.get(packageName);
21940            if (ps == null) {
21941                throw new PackageManagerException("Package " + packageName + " is unknown");
21942            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21943                throw new PackageManagerException(
21944                        "Package " + packageName + " found on unknown volume " + volumeUuid
21945                                + "; expected volume " + ps.volumeUuid);
21946            } else if (!ps.getInstalled(userId)) {
21947                throw new PackageManagerException(
21948                        "Package " + packageName + " not installed for user " + userId);
21949            }
21950        }
21951    }
21952
21953    private List<String> collectAbsoluteCodePaths() {
21954        synchronized (mPackages) {
21955            List<String> codePaths = new ArrayList<>();
21956            final int packageCount = mSettings.mPackages.size();
21957            for (int i = 0; i < packageCount; i++) {
21958                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21959                codePaths.add(ps.codePath.getAbsolutePath());
21960            }
21961            return codePaths;
21962        }
21963    }
21964
21965    /**
21966     * Examine all apps present on given mounted volume, and destroy apps that
21967     * aren't expected, either due to uninstallation or reinstallation on
21968     * another volume.
21969     */
21970    private void reconcileApps(String volumeUuid) {
21971        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21972        List<File> filesToDelete = null;
21973
21974        final File[] files = FileUtils.listFilesOrEmpty(
21975                Environment.getDataAppDirectory(volumeUuid));
21976        for (File file : files) {
21977            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21978                    && !PackageInstallerService.isStageName(file.getName());
21979            if (!isPackage) {
21980                // Ignore entries which are not packages
21981                continue;
21982            }
21983
21984            String absolutePath = file.getAbsolutePath();
21985
21986            boolean pathValid = false;
21987            final int absoluteCodePathCount = absoluteCodePaths.size();
21988            for (int i = 0; i < absoluteCodePathCount; i++) {
21989                String absoluteCodePath = absoluteCodePaths.get(i);
21990                if (absolutePath.startsWith(absoluteCodePath)) {
21991                    pathValid = true;
21992                    break;
21993                }
21994            }
21995
21996            if (!pathValid) {
21997                if (filesToDelete == null) {
21998                    filesToDelete = new ArrayList<>();
21999                }
22000                filesToDelete.add(file);
22001            }
22002        }
22003
22004        if (filesToDelete != null) {
22005            final int fileToDeleteCount = filesToDelete.size();
22006            for (int i = 0; i < fileToDeleteCount; i++) {
22007                File fileToDelete = filesToDelete.get(i);
22008                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22009                synchronized (mInstallLock) {
22010                    removeCodePathLI(fileToDelete);
22011                }
22012            }
22013        }
22014    }
22015
22016    /**
22017     * Reconcile all app data for the given user.
22018     * <p>
22019     * Verifies that directories exist and that ownership and labeling is
22020     * correct for all installed apps on all mounted volumes.
22021     */
22022    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22023        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22024        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22025            final String volumeUuid = vol.getFsUuid();
22026            synchronized (mInstallLock) {
22027                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22028            }
22029        }
22030    }
22031
22032    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22033            boolean migrateAppData) {
22034        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22035    }
22036
22037    /**
22038     * Reconcile all app data on given mounted volume.
22039     * <p>
22040     * Destroys app data that isn't expected, either due to uninstallation or
22041     * reinstallation on another volume.
22042     * <p>
22043     * Verifies that directories exist and that ownership and labeling is
22044     * correct for all installed apps.
22045     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22046     */
22047    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22048            boolean migrateAppData, boolean onlyCoreApps) {
22049        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22050                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22051        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22052
22053        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22054        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22055
22056        // First look for stale data that doesn't belong, and check if things
22057        // have changed since we did our last restorecon
22058        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22059            if (StorageManager.isFileEncryptedNativeOrEmulated()
22060                    && !StorageManager.isUserKeyUnlocked(userId)) {
22061                throw new RuntimeException(
22062                        "Yikes, someone asked us to reconcile CE storage while " + userId
22063                                + " was still locked; this would have caused massive data loss!");
22064            }
22065
22066            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22067            for (File file : files) {
22068                final String packageName = file.getName();
22069                try {
22070                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22071                } catch (PackageManagerException e) {
22072                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22073                    try {
22074                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22075                                StorageManager.FLAG_STORAGE_CE, 0);
22076                    } catch (InstallerException e2) {
22077                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22078                    }
22079                }
22080            }
22081        }
22082        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22083            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22084            for (File file : files) {
22085                final String packageName = file.getName();
22086                try {
22087                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22088                } catch (PackageManagerException e) {
22089                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22090                    try {
22091                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22092                                StorageManager.FLAG_STORAGE_DE, 0);
22093                    } catch (InstallerException e2) {
22094                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22095                    }
22096                }
22097            }
22098        }
22099
22100        // Ensure that data directories are ready to roll for all packages
22101        // installed for this volume and user
22102        final List<PackageSetting> packages;
22103        synchronized (mPackages) {
22104            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22105        }
22106        int preparedCount = 0;
22107        for (PackageSetting ps : packages) {
22108            final String packageName = ps.name;
22109            if (ps.pkg == null) {
22110                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22111                // TODO: might be due to legacy ASEC apps; we should circle back
22112                // and reconcile again once they're scanned
22113                continue;
22114            }
22115            // Skip non-core apps if requested
22116            if (onlyCoreApps && !ps.pkg.coreApp) {
22117                result.add(packageName);
22118                continue;
22119            }
22120
22121            if (ps.getInstalled(userId)) {
22122                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22123                preparedCount++;
22124            }
22125        }
22126
22127        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22128        return result;
22129    }
22130
22131    /**
22132     * Prepare app data for the given app just after it was installed or
22133     * upgraded. This method carefully only touches users that it's installed
22134     * for, and it forces a restorecon to handle any seinfo changes.
22135     * <p>
22136     * Verifies that directories exist and that ownership and labeling is
22137     * correct for all installed apps. If there is an ownership mismatch, it
22138     * will try recovering system apps by wiping data; third-party app data is
22139     * left intact.
22140     * <p>
22141     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22142     */
22143    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22144        final PackageSetting ps;
22145        synchronized (mPackages) {
22146            ps = mSettings.mPackages.get(pkg.packageName);
22147            mSettings.writeKernelMappingLPr(ps);
22148        }
22149
22150        final UserManager um = mContext.getSystemService(UserManager.class);
22151        UserManagerInternal umInternal = getUserManagerInternal();
22152        for (UserInfo user : um.getUsers()) {
22153            final int flags;
22154            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22155                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22156            } else if (umInternal.isUserRunning(user.id)) {
22157                flags = StorageManager.FLAG_STORAGE_DE;
22158            } else {
22159                continue;
22160            }
22161
22162            if (ps.getInstalled(user.id)) {
22163                // TODO: when user data is locked, mark that we're still dirty
22164                prepareAppDataLIF(pkg, user.id, flags);
22165            }
22166        }
22167    }
22168
22169    /**
22170     * Prepare app data for the given app.
22171     * <p>
22172     * Verifies that directories exist and that ownership and labeling is
22173     * correct for all installed apps. If there is an ownership mismatch, this
22174     * will try recovering system apps by wiping data; third-party app data is
22175     * left intact.
22176     */
22177    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22178        if (pkg == null) {
22179            Slog.wtf(TAG, "Package was null!", new Throwable());
22180            return;
22181        }
22182        prepareAppDataLeafLIF(pkg, userId, flags);
22183        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22184        for (int i = 0; i < childCount; i++) {
22185            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22186        }
22187    }
22188
22189    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22190            boolean maybeMigrateAppData) {
22191        prepareAppDataLIF(pkg, userId, flags);
22192
22193        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22194            // We may have just shuffled around app data directories, so
22195            // prepare them one more time
22196            prepareAppDataLIF(pkg, userId, flags);
22197        }
22198    }
22199
22200    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22201        if (DEBUG_APP_DATA) {
22202            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22203                    + Integer.toHexString(flags));
22204        }
22205
22206        final String volumeUuid = pkg.volumeUuid;
22207        final String packageName = pkg.packageName;
22208        final ApplicationInfo app = pkg.applicationInfo;
22209        final int appId = UserHandle.getAppId(app.uid);
22210
22211        Preconditions.checkNotNull(app.seInfo);
22212
22213        long ceDataInode = -1;
22214        try {
22215            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22216                    appId, app.seInfo, app.targetSdkVersion);
22217        } catch (InstallerException e) {
22218            if (app.isSystemApp()) {
22219                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22220                        + ", but trying to recover: " + e);
22221                destroyAppDataLeafLIF(pkg, userId, flags);
22222                try {
22223                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22224                            appId, app.seInfo, app.targetSdkVersion);
22225                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22226                } catch (InstallerException e2) {
22227                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22228                }
22229            } else {
22230                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22231            }
22232        }
22233        // Prepare the application profiles.
22234        mArtManagerService.prepareAppProfiles(pkg, userId);
22235
22236        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22237            // TODO: mark this structure as dirty so we persist it!
22238            synchronized (mPackages) {
22239                final PackageSetting ps = mSettings.mPackages.get(packageName);
22240                if (ps != null) {
22241                    ps.setCeDataInode(ceDataInode, userId);
22242                }
22243            }
22244        }
22245
22246        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22247    }
22248
22249    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22250        if (pkg == null) {
22251            Slog.wtf(TAG, "Package was null!", new Throwable());
22252            return;
22253        }
22254        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22255        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22256        for (int i = 0; i < childCount; i++) {
22257            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22258        }
22259    }
22260
22261    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22262        final String volumeUuid = pkg.volumeUuid;
22263        final String packageName = pkg.packageName;
22264        final ApplicationInfo app = pkg.applicationInfo;
22265
22266        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22267            // Create a native library symlink only if we have native libraries
22268            // and if the native libraries are 32 bit libraries. We do not provide
22269            // this symlink for 64 bit libraries.
22270            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22271                final String nativeLibPath = app.nativeLibraryDir;
22272                try {
22273                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22274                            nativeLibPath, userId);
22275                } catch (InstallerException e) {
22276                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22277                }
22278            }
22279        }
22280    }
22281
22282    /**
22283     * For system apps on non-FBE devices, this method migrates any existing
22284     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22285     * requested by the app.
22286     */
22287    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22288        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22289                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22290            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22291                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22292            try {
22293                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22294                        storageTarget);
22295            } catch (InstallerException e) {
22296                logCriticalInfo(Log.WARN,
22297                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22298            }
22299            return true;
22300        } else {
22301            return false;
22302        }
22303    }
22304
22305    public PackageFreezer freezePackage(String packageName, String killReason) {
22306        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22307    }
22308
22309    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22310        return new PackageFreezer(packageName, userId, killReason);
22311    }
22312
22313    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22314            String killReason) {
22315        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22316    }
22317
22318    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22319            String killReason) {
22320        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22321            return new PackageFreezer();
22322        } else {
22323            return freezePackage(packageName, userId, killReason);
22324        }
22325    }
22326
22327    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22328            String killReason) {
22329        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22330    }
22331
22332    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22333            String killReason) {
22334        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22335            return new PackageFreezer();
22336        } else {
22337            return freezePackage(packageName, userId, killReason);
22338        }
22339    }
22340
22341    /**
22342     * Class that freezes and kills the given package upon creation, and
22343     * unfreezes it upon closing. This is typically used when doing surgery on
22344     * app code/data to prevent the app from running while you're working.
22345     */
22346    private class PackageFreezer implements AutoCloseable {
22347        private final String mPackageName;
22348        private final PackageFreezer[] mChildren;
22349
22350        private final boolean mWeFroze;
22351
22352        private final AtomicBoolean mClosed = new AtomicBoolean();
22353        private final CloseGuard mCloseGuard = CloseGuard.get();
22354
22355        /**
22356         * Create and return a stub freezer that doesn't actually do anything,
22357         * typically used when someone requested
22358         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22359         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22360         */
22361        public PackageFreezer() {
22362            mPackageName = null;
22363            mChildren = null;
22364            mWeFroze = false;
22365            mCloseGuard.open("close");
22366        }
22367
22368        public PackageFreezer(String packageName, int userId, String killReason) {
22369            synchronized (mPackages) {
22370                mPackageName = packageName;
22371                mWeFroze = mFrozenPackages.add(mPackageName);
22372
22373                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22374                if (ps != null) {
22375                    killApplication(ps.name, ps.appId, userId, killReason);
22376                }
22377
22378                final PackageParser.Package p = mPackages.get(packageName);
22379                if (p != null && p.childPackages != null) {
22380                    final int N = p.childPackages.size();
22381                    mChildren = new PackageFreezer[N];
22382                    for (int i = 0; i < N; i++) {
22383                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22384                                userId, killReason);
22385                    }
22386                } else {
22387                    mChildren = null;
22388                }
22389            }
22390            mCloseGuard.open("close");
22391        }
22392
22393        @Override
22394        protected void finalize() throws Throwable {
22395            try {
22396                if (mCloseGuard != null) {
22397                    mCloseGuard.warnIfOpen();
22398                }
22399
22400                close();
22401            } finally {
22402                super.finalize();
22403            }
22404        }
22405
22406        @Override
22407        public void close() {
22408            mCloseGuard.close();
22409            if (mClosed.compareAndSet(false, true)) {
22410                synchronized (mPackages) {
22411                    if (mWeFroze) {
22412                        mFrozenPackages.remove(mPackageName);
22413                    }
22414
22415                    if (mChildren != null) {
22416                        for (PackageFreezer freezer : mChildren) {
22417                            freezer.close();
22418                        }
22419                    }
22420                }
22421            }
22422        }
22423    }
22424
22425    /**
22426     * Verify that given package is currently frozen.
22427     */
22428    private void checkPackageFrozen(String packageName) {
22429        synchronized (mPackages) {
22430            if (!mFrozenPackages.contains(packageName)) {
22431                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22432            }
22433        }
22434    }
22435
22436    @Override
22437    public int movePackage(final String packageName, final String volumeUuid) {
22438        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22439
22440        final int callingUid = Binder.getCallingUid();
22441        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22442        final int moveId = mNextMoveId.getAndIncrement();
22443        mHandler.post(new Runnable() {
22444            @Override
22445            public void run() {
22446                try {
22447                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22448                } catch (PackageManagerException e) {
22449                    Slog.w(TAG, "Failed to move " + packageName, e);
22450                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22451                }
22452            }
22453        });
22454        return moveId;
22455    }
22456
22457    private void movePackageInternal(final String packageName, final String volumeUuid,
22458            final int moveId, final int callingUid, UserHandle user)
22459                    throws PackageManagerException {
22460        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22461        final PackageManager pm = mContext.getPackageManager();
22462
22463        final boolean currentAsec;
22464        final String currentVolumeUuid;
22465        final File codeFile;
22466        final String installerPackageName;
22467        final String packageAbiOverride;
22468        final int appId;
22469        final String seinfo;
22470        final String label;
22471        final int targetSdkVersion;
22472        final PackageFreezer freezer;
22473        final int[] installedUserIds;
22474
22475        // reader
22476        synchronized (mPackages) {
22477            final PackageParser.Package pkg = mPackages.get(packageName);
22478            final PackageSetting ps = mSettings.mPackages.get(packageName);
22479            if (pkg == null
22480                    || ps == null
22481                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22482                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22483            }
22484            if (pkg.applicationInfo.isSystemApp()) {
22485                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22486                        "Cannot move system application");
22487            }
22488
22489            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22490            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22491                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22492            if (isInternalStorage && !allow3rdPartyOnInternal) {
22493                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22494                        "3rd party apps are not allowed on internal storage");
22495            }
22496
22497            if (pkg.applicationInfo.isExternalAsec()) {
22498                currentAsec = true;
22499                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22500            } else if (pkg.applicationInfo.isForwardLocked()) {
22501                currentAsec = true;
22502                currentVolumeUuid = "forward_locked";
22503            } else {
22504                currentAsec = false;
22505                currentVolumeUuid = ps.volumeUuid;
22506
22507                final File probe = new File(pkg.codePath);
22508                final File probeOat = new File(probe, "oat");
22509                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22510                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22511                            "Move only supported for modern cluster style installs");
22512                }
22513            }
22514
22515            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22516                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22517                        "Package already moved to " + volumeUuid);
22518            }
22519            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22520                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22521                        "Device admin cannot be moved");
22522            }
22523
22524            if (mFrozenPackages.contains(packageName)) {
22525                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22526                        "Failed to move already frozen package");
22527            }
22528
22529            codeFile = new File(pkg.codePath);
22530            installerPackageName = ps.installerPackageName;
22531            packageAbiOverride = ps.cpuAbiOverrideString;
22532            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22533            seinfo = pkg.applicationInfo.seInfo;
22534            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22535            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22536            freezer = freezePackage(packageName, "movePackageInternal");
22537            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22538        }
22539
22540        final Bundle extras = new Bundle();
22541        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22542        extras.putString(Intent.EXTRA_TITLE, label);
22543        mMoveCallbacks.notifyCreated(moveId, extras);
22544
22545        int installFlags;
22546        final boolean moveCompleteApp;
22547        final File measurePath;
22548
22549        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22550            installFlags = INSTALL_INTERNAL;
22551            moveCompleteApp = !currentAsec;
22552            measurePath = Environment.getDataAppDirectory(volumeUuid);
22553        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22554            installFlags = INSTALL_EXTERNAL;
22555            moveCompleteApp = false;
22556            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22557        } else {
22558            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22559            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22560                    || !volume.isMountedWritable()) {
22561                freezer.close();
22562                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22563                        "Move location not mounted private volume");
22564            }
22565
22566            Preconditions.checkState(!currentAsec);
22567
22568            installFlags = INSTALL_INTERNAL;
22569            moveCompleteApp = true;
22570            measurePath = Environment.getDataAppDirectory(volumeUuid);
22571        }
22572
22573        // If we're moving app data around, we need all the users unlocked
22574        if (moveCompleteApp) {
22575            for (int userId : installedUserIds) {
22576                if (StorageManager.isFileEncryptedNativeOrEmulated()
22577                        && !StorageManager.isUserKeyUnlocked(userId)) {
22578                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22579                            "User " + userId + " must be unlocked");
22580                }
22581            }
22582        }
22583
22584        final PackageStats stats = new PackageStats(null, -1);
22585        synchronized (mInstaller) {
22586            for (int userId : installedUserIds) {
22587                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22588                    freezer.close();
22589                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22590                            "Failed to measure package size");
22591                }
22592            }
22593        }
22594
22595        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22596                + stats.dataSize);
22597
22598        final long startFreeBytes = measurePath.getUsableSpace();
22599        final long sizeBytes;
22600        if (moveCompleteApp) {
22601            sizeBytes = stats.codeSize + stats.dataSize;
22602        } else {
22603            sizeBytes = stats.codeSize;
22604        }
22605
22606        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22607            freezer.close();
22608            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22609                    "Not enough free space to move");
22610        }
22611
22612        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22613
22614        final CountDownLatch installedLatch = new CountDownLatch(1);
22615        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22616            @Override
22617            public void onUserActionRequired(Intent intent) throws RemoteException {
22618                throw new IllegalStateException();
22619            }
22620
22621            @Override
22622            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22623                    Bundle extras) throws RemoteException {
22624                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22625                        + PackageManager.installStatusToString(returnCode, msg));
22626
22627                installedLatch.countDown();
22628                freezer.close();
22629
22630                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22631                switch (status) {
22632                    case PackageInstaller.STATUS_SUCCESS:
22633                        mMoveCallbacks.notifyStatusChanged(moveId,
22634                                PackageManager.MOVE_SUCCEEDED);
22635                        break;
22636                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22637                        mMoveCallbacks.notifyStatusChanged(moveId,
22638                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22639                        break;
22640                    default:
22641                        mMoveCallbacks.notifyStatusChanged(moveId,
22642                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22643                        break;
22644                }
22645            }
22646        };
22647
22648        final MoveInfo move;
22649        if (moveCompleteApp) {
22650            // Kick off a thread to report progress estimates
22651            new Thread() {
22652                @Override
22653                public void run() {
22654                    while (true) {
22655                        try {
22656                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22657                                break;
22658                            }
22659                        } catch (InterruptedException ignored) {
22660                        }
22661
22662                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22663                        final int progress = 10 + (int) MathUtils.constrain(
22664                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22665                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22666                    }
22667                }
22668            }.start();
22669
22670            final String dataAppName = codeFile.getName();
22671            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22672                    dataAppName, appId, seinfo, targetSdkVersion);
22673        } else {
22674            move = null;
22675        }
22676
22677        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22678
22679        final Message msg = mHandler.obtainMessage(INIT_COPY);
22680        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22681        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22682                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22683                packageAbiOverride, null /*grantedPermissions*/,
22684                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22685        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22686        msg.obj = params;
22687
22688        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22689                System.identityHashCode(msg.obj));
22690        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22691                System.identityHashCode(msg.obj));
22692
22693        mHandler.sendMessage(msg);
22694    }
22695
22696    @Override
22697    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22698        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22699
22700        final int realMoveId = mNextMoveId.getAndIncrement();
22701        final Bundle extras = new Bundle();
22702        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22703        mMoveCallbacks.notifyCreated(realMoveId, extras);
22704
22705        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22706            @Override
22707            public void onCreated(int moveId, Bundle extras) {
22708                // Ignored
22709            }
22710
22711            @Override
22712            public void onStatusChanged(int moveId, int status, long estMillis) {
22713                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22714            }
22715        };
22716
22717        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22718        storage.setPrimaryStorageUuid(volumeUuid, callback);
22719        return realMoveId;
22720    }
22721
22722    @Override
22723    public int getMoveStatus(int moveId) {
22724        mContext.enforceCallingOrSelfPermission(
22725                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22726        return mMoveCallbacks.mLastStatus.get(moveId);
22727    }
22728
22729    @Override
22730    public void registerMoveCallback(IPackageMoveObserver callback) {
22731        mContext.enforceCallingOrSelfPermission(
22732                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22733        mMoveCallbacks.register(callback);
22734    }
22735
22736    @Override
22737    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22738        mContext.enforceCallingOrSelfPermission(
22739                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22740        mMoveCallbacks.unregister(callback);
22741    }
22742
22743    @Override
22744    public boolean setInstallLocation(int loc) {
22745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22746                null);
22747        if (getInstallLocation() == loc) {
22748            return true;
22749        }
22750        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22751                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22752            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22753                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22754            return true;
22755        }
22756        return false;
22757   }
22758
22759    @Override
22760    public int getInstallLocation() {
22761        // allow instant app access
22762        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22763                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22764                PackageHelper.APP_INSTALL_AUTO);
22765    }
22766
22767    /** Called by UserManagerService */
22768    void cleanUpUser(UserManagerService userManager, int userHandle) {
22769        synchronized (mPackages) {
22770            mDirtyUsers.remove(userHandle);
22771            mUserNeedsBadging.delete(userHandle);
22772            mSettings.removeUserLPw(userHandle);
22773            mPendingBroadcasts.remove(userHandle);
22774            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22775            removeUnusedPackagesLPw(userManager, userHandle);
22776        }
22777    }
22778
22779    /**
22780     * We're removing userHandle and would like to remove any downloaded packages
22781     * that are no longer in use by any other user.
22782     * @param userHandle the user being removed
22783     */
22784    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22785        final boolean DEBUG_CLEAN_APKS = false;
22786        int [] users = userManager.getUserIds();
22787        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22788        while (psit.hasNext()) {
22789            PackageSetting ps = psit.next();
22790            if (ps.pkg == null) {
22791                continue;
22792            }
22793            final String packageName = ps.pkg.packageName;
22794            // Skip over if system app
22795            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22796                continue;
22797            }
22798            if (DEBUG_CLEAN_APKS) {
22799                Slog.i(TAG, "Checking package " + packageName);
22800            }
22801            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22802            if (keep) {
22803                if (DEBUG_CLEAN_APKS) {
22804                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22805                }
22806            } else {
22807                for (int i = 0; i < users.length; i++) {
22808                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22809                        keep = true;
22810                        if (DEBUG_CLEAN_APKS) {
22811                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22812                                    + users[i]);
22813                        }
22814                        break;
22815                    }
22816                }
22817            }
22818            if (!keep) {
22819                if (DEBUG_CLEAN_APKS) {
22820                    Slog.i(TAG, "  Removing package " + packageName);
22821                }
22822                mHandler.post(new Runnable() {
22823                    public void run() {
22824                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22825                                userHandle, 0);
22826                    } //end run
22827                });
22828            }
22829        }
22830    }
22831
22832    /** Called by UserManagerService */
22833    void createNewUser(int userId, String[] disallowedPackages) {
22834        synchronized (mInstallLock) {
22835            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22836        }
22837        synchronized (mPackages) {
22838            scheduleWritePackageRestrictionsLocked(userId);
22839            scheduleWritePackageListLocked(userId);
22840            applyFactoryDefaultBrowserLPw(userId);
22841            primeDomainVerificationsLPw(userId);
22842        }
22843    }
22844
22845    void onNewUserCreated(final int userId) {
22846        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22847        synchronized(mPackages) {
22848            // If permission review for legacy apps is required, we represent
22849            // dagerous permissions for such apps as always granted runtime
22850            // permissions to keep per user flag state whether review is needed.
22851            // Hence, if a new user is added we have to propagate dangerous
22852            // permission grants for these legacy apps.
22853            if (mSettings.mPermissions.mPermissionReviewRequired) {
22854// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22855                mPermissionManager.updateAllPermissions(
22856                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22857                        mPermissionCallback);
22858            }
22859        }
22860    }
22861
22862    @Override
22863    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22864        mContext.enforceCallingOrSelfPermission(
22865                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22866                "Only package verification agents can read the verifier device identity");
22867
22868        synchronized (mPackages) {
22869            return mSettings.getVerifierDeviceIdentityLPw();
22870        }
22871    }
22872
22873    @Override
22874    public void setPermissionEnforced(String permission, boolean enforced) {
22875        // TODO: Now that we no longer change GID for storage, this should to away.
22876        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22877                "setPermissionEnforced");
22878        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22879            synchronized (mPackages) {
22880                if (mSettings.mReadExternalStorageEnforced == null
22881                        || mSettings.mReadExternalStorageEnforced != enforced) {
22882                    mSettings.mReadExternalStorageEnforced =
22883                            enforced ? Boolean.TRUE : Boolean.FALSE;
22884                    mSettings.writeLPr();
22885                }
22886            }
22887            // kill any non-foreground processes so we restart them and
22888            // grant/revoke the GID.
22889            final IActivityManager am = ActivityManager.getService();
22890            if (am != null) {
22891                final long token = Binder.clearCallingIdentity();
22892                try {
22893                    am.killProcessesBelowForeground("setPermissionEnforcement");
22894                } catch (RemoteException e) {
22895                } finally {
22896                    Binder.restoreCallingIdentity(token);
22897                }
22898            }
22899        } else {
22900            throw new IllegalArgumentException("No selective enforcement for " + permission);
22901        }
22902    }
22903
22904    @Override
22905    @Deprecated
22906    public boolean isPermissionEnforced(String permission) {
22907        // allow instant applications
22908        return true;
22909    }
22910
22911    @Override
22912    public boolean isStorageLow() {
22913        // allow instant applications
22914        final long token = Binder.clearCallingIdentity();
22915        try {
22916            final DeviceStorageMonitorInternal
22917                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22918            if (dsm != null) {
22919                return dsm.isMemoryLow();
22920            } else {
22921                return false;
22922            }
22923        } finally {
22924            Binder.restoreCallingIdentity(token);
22925        }
22926    }
22927
22928    @Override
22929    public IPackageInstaller getPackageInstaller() {
22930        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22931            return null;
22932        }
22933        return mInstallerService;
22934    }
22935
22936    @Override
22937    public IArtManager getArtManager() {
22938        return mArtManagerService;
22939    }
22940
22941    private boolean userNeedsBadging(int userId) {
22942        int index = mUserNeedsBadging.indexOfKey(userId);
22943        if (index < 0) {
22944            final UserInfo userInfo;
22945            final long token = Binder.clearCallingIdentity();
22946            try {
22947                userInfo = sUserManager.getUserInfo(userId);
22948            } finally {
22949                Binder.restoreCallingIdentity(token);
22950            }
22951            final boolean b;
22952            if (userInfo != null && userInfo.isManagedProfile()) {
22953                b = true;
22954            } else {
22955                b = false;
22956            }
22957            mUserNeedsBadging.put(userId, b);
22958            return b;
22959        }
22960        return mUserNeedsBadging.valueAt(index);
22961    }
22962
22963    @Override
22964    public KeySet getKeySetByAlias(String packageName, String alias) {
22965        if (packageName == null || alias == null) {
22966            return null;
22967        }
22968        synchronized(mPackages) {
22969            final PackageParser.Package pkg = mPackages.get(packageName);
22970            if (pkg == null) {
22971                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22972                throw new IllegalArgumentException("Unknown package: " + packageName);
22973            }
22974            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22975            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22976                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22977                throw new IllegalArgumentException("Unknown package: " + packageName);
22978            }
22979            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22980            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22981        }
22982    }
22983
22984    @Override
22985    public KeySet getSigningKeySet(String packageName) {
22986        if (packageName == null) {
22987            return null;
22988        }
22989        synchronized(mPackages) {
22990            final int callingUid = Binder.getCallingUid();
22991            final int callingUserId = UserHandle.getUserId(callingUid);
22992            final PackageParser.Package pkg = mPackages.get(packageName);
22993            if (pkg == null) {
22994                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22995                throw new IllegalArgumentException("Unknown package: " + packageName);
22996            }
22997            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22998            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22999                // filter and pretend the package doesn't exist
23000                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23001                        + ", uid:" + callingUid);
23002                throw new IllegalArgumentException("Unknown package: " + packageName);
23003            }
23004            if (pkg.applicationInfo.uid != callingUid
23005                    && Process.SYSTEM_UID != callingUid) {
23006                throw new SecurityException("May not access signing KeySet of other apps.");
23007            }
23008            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23009            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23010        }
23011    }
23012
23013    @Override
23014    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23015        final int callingUid = Binder.getCallingUid();
23016        if (getInstantAppPackageName(callingUid) != null) {
23017            return false;
23018        }
23019        if (packageName == null || ks == null) {
23020            return false;
23021        }
23022        synchronized(mPackages) {
23023            final PackageParser.Package pkg = mPackages.get(packageName);
23024            if (pkg == null
23025                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23026                            UserHandle.getUserId(callingUid))) {
23027                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23028                throw new IllegalArgumentException("Unknown package: " + packageName);
23029            }
23030            IBinder ksh = ks.getToken();
23031            if (ksh instanceof KeySetHandle) {
23032                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23033                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23034            }
23035            return false;
23036        }
23037    }
23038
23039    @Override
23040    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23041        final int callingUid = Binder.getCallingUid();
23042        if (getInstantAppPackageName(callingUid) != null) {
23043            return false;
23044        }
23045        if (packageName == null || ks == null) {
23046            return false;
23047        }
23048        synchronized(mPackages) {
23049            final PackageParser.Package pkg = mPackages.get(packageName);
23050            if (pkg == null
23051                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23052                            UserHandle.getUserId(callingUid))) {
23053                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23054                throw new IllegalArgumentException("Unknown package: " + packageName);
23055            }
23056            IBinder ksh = ks.getToken();
23057            if (ksh instanceof KeySetHandle) {
23058                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23059                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23060            }
23061            return false;
23062        }
23063    }
23064
23065    private void deletePackageIfUnusedLPr(final String packageName) {
23066        PackageSetting ps = mSettings.mPackages.get(packageName);
23067        if (ps == null) {
23068            return;
23069        }
23070        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23071            // TODO Implement atomic delete if package is unused
23072            // It is currently possible that the package will be deleted even if it is installed
23073            // after this method returns.
23074            mHandler.post(new Runnable() {
23075                public void run() {
23076                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23077                            0, PackageManager.DELETE_ALL_USERS);
23078                }
23079            });
23080        }
23081    }
23082
23083    /**
23084     * Check and throw if the given before/after packages would be considered a
23085     * downgrade.
23086     */
23087    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23088            throws PackageManagerException {
23089        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23090            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23091                    "Update version code " + after.versionCode + " is older than current "
23092                    + before.getLongVersionCode());
23093        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23094            if (after.baseRevisionCode < before.baseRevisionCode) {
23095                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23096                        "Update base revision code " + after.baseRevisionCode
23097                        + " is older than current " + before.baseRevisionCode);
23098            }
23099
23100            if (!ArrayUtils.isEmpty(after.splitNames)) {
23101                for (int i = 0; i < after.splitNames.length; i++) {
23102                    final String splitName = after.splitNames[i];
23103                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23104                    if (j != -1) {
23105                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23106                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23107                                    "Update split " + splitName + " revision code "
23108                                    + after.splitRevisionCodes[i] + " is older than current "
23109                                    + before.splitRevisionCodes[j]);
23110                        }
23111                    }
23112                }
23113            }
23114        }
23115    }
23116
23117    private static class MoveCallbacks extends Handler {
23118        private static final int MSG_CREATED = 1;
23119        private static final int MSG_STATUS_CHANGED = 2;
23120
23121        private final RemoteCallbackList<IPackageMoveObserver>
23122                mCallbacks = new RemoteCallbackList<>();
23123
23124        private final SparseIntArray mLastStatus = new SparseIntArray();
23125
23126        public MoveCallbacks(Looper looper) {
23127            super(looper);
23128        }
23129
23130        public void register(IPackageMoveObserver callback) {
23131            mCallbacks.register(callback);
23132        }
23133
23134        public void unregister(IPackageMoveObserver callback) {
23135            mCallbacks.unregister(callback);
23136        }
23137
23138        @Override
23139        public void handleMessage(Message msg) {
23140            final SomeArgs args = (SomeArgs) msg.obj;
23141            final int n = mCallbacks.beginBroadcast();
23142            for (int i = 0; i < n; i++) {
23143                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23144                try {
23145                    invokeCallback(callback, msg.what, args);
23146                } catch (RemoteException ignored) {
23147                }
23148            }
23149            mCallbacks.finishBroadcast();
23150            args.recycle();
23151        }
23152
23153        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23154                throws RemoteException {
23155            switch (what) {
23156                case MSG_CREATED: {
23157                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23158                    break;
23159                }
23160                case MSG_STATUS_CHANGED: {
23161                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23162                    break;
23163                }
23164            }
23165        }
23166
23167        private void notifyCreated(int moveId, Bundle extras) {
23168            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23169
23170            final SomeArgs args = SomeArgs.obtain();
23171            args.argi1 = moveId;
23172            args.arg2 = extras;
23173            obtainMessage(MSG_CREATED, args).sendToTarget();
23174        }
23175
23176        private void notifyStatusChanged(int moveId, int status) {
23177            notifyStatusChanged(moveId, status, -1);
23178        }
23179
23180        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23181            Slog.v(TAG, "Move " + moveId + " status " + status);
23182
23183            final SomeArgs args = SomeArgs.obtain();
23184            args.argi1 = moveId;
23185            args.argi2 = status;
23186            args.arg3 = estMillis;
23187            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23188
23189            synchronized (mLastStatus) {
23190                mLastStatus.put(moveId, status);
23191            }
23192        }
23193    }
23194
23195    private final static class OnPermissionChangeListeners extends Handler {
23196        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23197
23198        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23199                new RemoteCallbackList<>();
23200
23201        public OnPermissionChangeListeners(Looper looper) {
23202            super(looper);
23203        }
23204
23205        @Override
23206        public void handleMessage(Message msg) {
23207            switch (msg.what) {
23208                case MSG_ON_PERMISSIONS_CHANGED: {
23209                    final int uid = msg.arg1;
23210                    handleOnPermissionsChanged(uid);
23211                } break;
23212            }
23213        }
23214
23215        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23216            mPermissionListeners.register(listener);
23217
23218        }
23219
23220        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23221            mPermissionListeners.unregister(listener);
23222        }
23223
23224        public void onPermissionsChanged(int uid) {
23225            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23226                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23227            }
23228        }
23229
23230        private void handleOnPermissionsChanged(int uid) {
23231            final int count = mPermissionListeners.beginBroadcast();
23232            try {
23233                for (int i = 0; i < count; i++) {
23234                    IOnPermissionsChangeListener callback = mPermissionListeners
23235                            .getBroadcastItem(i);
23236                    try {
23237                        callback.onPermissionsChanged(uid);
23238                    } catch (RemoteException e) {
23239                        Log.e(TAG, "Permission listener is dead", e);
23240                    }
23241                }
23242            } finally {
23243                mPermissionListeners.finishBroadcast();
23244            }
23245        }
23246    }
23247
23248    private class PackageManagerNative extends IPackageManagerNative.Stub {
23249        @Override
23250        public String[] getNamesForUids(int[] uids) throws RemoteException {
23251            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23252            // massage results so they can be parsed by the native binder
23253            for (int i = results.length - 1; i >= 0; --i) {
23254                if (results[i] == null) {
23255                    results[i] = "";
23256                }
23257            }
23258            return results;
23259        }
23260
23261        // NB: this differentiates between preloads and sideloads
23262        @Override
23263        public String getInstallerForPackage(String packageName) throws RemoteException {
23264            final String installerName = getInstallerPackageName(packageName);
23265            if (!TextUtils.isEmpty(installerName)) {
23266                return installerName;
23267            }
23268            // differentiate between preload and sideload
23269            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23270            ApplicationInfo appInfo = getApplicationInfo(packageName,
23271                                    /*flags*/ 0,
23272                                    /*userId*/ callingUser);
23273            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23274                return "preload";
23275            }
23276            return "";
23277        }
23278
23279        @Override
23280        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23281            try {
23282                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23283                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23284                if (pInfo != null) {
23285                    return pInfo.getLongVersionCode();
23286                }
23287            } catch (Exception e) {
23288            }
23289            return 0;
23290        }
23291    }
23292
23293    private class PackageManagerInternalImpl extends PackageManagerInternal {
23294        @Override
23295        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23296                int flagValues, int userId) {
23297            PackageManagerService.this.updatePermissionFlags(
23298                    permName, packageName, flagMask, flagValues, userId);
23299        }
23300
23301        @Override
23302        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23303            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23304        }
23305
23306        @Override
23307        public boolean isInstantApp(String packageName, int userId) {
23308            return PackageManagerService.this.isInstantApp(packageName, userId);
23309        }
23310
23311        @Override
23312        public String getInstantAppPackageName(int uid) {
23313            return PackageManagerService.this.getInstantAppPackageName(uid);
23314        }
23315
23316        @Override
23317        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23318            synchronized (mPackages) {
23319                return PackageManagerService.this.filterAppAccessLPr(
23320                        (PackageSetting) pkg.mExtras, callingUid, userId);
23321            }
23322        }
23323
23324        @Override
23325        public PackageParser.Package getPackage(String packageName) {
23326            synchronized (mPackages) {
23327                packageName = resolveInternalPackageNameLPr(
23328                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23329                return mPackages.get(packageName);
23330            }
23331        }
23332
23333        @Override
23334        public PackageList getPackageList(PackageListObserver observer) {
23335            synchronized (mPackages) {
23336                final int N = mPackages.size();
23337                final ArrayList<String> list = new ArrayList<>(N);
23338                for (int i = 0; i < N; i++) {
23339                    list.add(mPackages.keyAt(i));
23340                }
23341                final PackageList packageList = new PackageList(list, observer);
23342                if (observer != null) {
23343                    mPackageListObservers.add(packageList);
23344                }
23345                return packageList;
23346            }
23347        }
23348
23349        @Override
23350        public void removePackageListObserver(PackageListObserver observer) {
23351            synchronized (mPackages) {
23352                mPackageListObservers.remove(observer);
23353            }
23354        }
23355
23356        @Override
23357        public PackageParser.Package getDisabledPackage(String packageName) {
23358            synchronized (mPackages) {
23359                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23360                return (ps != null) ? ps.pkg : null;
23361            }
23362        }
23363
23364        @Override
23365        public String getKnownPackageName(int knownPackage, int userId) {
23366            switch(knownPackage) {
23367                case PackageManagerInternal.PACKAGE_BROWSER:
23368                    return getDefaultBrowserPackageName(userId);
23369                case PackageManagerInternal.PACKAGE_INSTALLER:
23370                    return mRequiredInstallerPackage;
23371                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23372                    return mSetupWizardPackage;
23373                case PackageManagerInternal.PACKAGE_SYSTEM:
23374                    return "android";
23375                case PackageManagerInternal.PACKAGE_VERIFIER:
23376                    return mRequiredVerifierPackage;
23377            }
23378            return null;
23379        }
23380
23381        @Override
23382        public boolean isResolveActivityComponent(ComponentInfo component) {
23383            return mResolveActivity.packageName.equals(component.packageName)
23384                    && mResolveActivity.name.equals(component.name);
23385        }
23386
23387        @Override
23388        public void setLocationPackagesProvider(PackagesProvider provider) {
23389            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23390        }
23391
23392        @Override
23393        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23394            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23395        }
23396
23397        @Override
23398        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23399            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23400        }
23401
23402        @Override
23403        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23404            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23405        }
23406
23407        @Override
23408        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23409            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23410        }
23411
23412        @Override
23413        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23414            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23415        }
23416
23417        @Override
23418        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23419            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23420        }
23421
23422        @Override
23423        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23424            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23425        }
23426
23427        @Override
23428        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23429            synchronized (mPackages) {
23430                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23431            }
23432            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23433        }
23434
23435        @Override
23436        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23437            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23438                    packageName, userId);
23439        }
23440
23441        @Override
23442        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23443            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23444                    packageName, userId);
23445        }
23446
23447        @Override
23448        public void setKeepUninstalledPackages(final List<String> packageList) {
23449            Preconditions.checkNotNull(packageList);
23450            List<String> removedFromList = null;
23451            synchronized (mPackages) {
23452                if (mKeepUninstalledPackages != null) {
23453                    final int packagesCount = mKeepUninstalledPackages.size();
23454                    for (int i = 0; i < packagesCount; i++) {
23455                        String oldPackage = mKeepUninstalledPackages.get(i);
23456                        if (packageList != null && packageList.contains(oldPackage)) {
23457                            continue;
23458                        }
23459                        if (removedFromList == null) {
23460                            removedFromList = new ArrayList<>();
23461                        }
23462                        removedFromList.add(oldPackage);
23463                    }
23464                }
23465                mKeepUninstalledPackages = new ArrayList<>(packageList);
23466                if (removedFromList != null) {
23467                    final int removedCount = removedFromList.size();
23468                    for (int i = 0; i < removedCount; i++) {
23469                        deletePackageIfUnusedLPr(removedFromList.get(i));
23470                    }
23471                }
23472            }
23473        }
23474
23475        @Override
23476        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23477            synchronized (mPackages) {
23478                return mPermissionManager.isPermissionsReviewRequired(
23479                        mPackages.get(packageName), userId);
23480            }
23481        }
23482
23483        @Override
23484        public PackageInfo getPackageInfo(
23485                String packageName, int flags, int filterCallingUid, int userId) {
23486            return PackageManagerService.this
23487                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23488                            flags, filterCallingUid, userId);
23489        }
23490
23491        @Override
23492        public int getPackageUid(String packageName, int flags, int userId) {
23493            return PackageManagerService.this
23494                    .getPackageUid(packageName, flags, userId);
23495        }
23496
23497        @Override
23498        public ApplicationInfo getApplicationInfo(
23499                String packageName, int flags, int filterCallingUid, int userId) {
23500            return PackageManagerService.this
23501                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23502        }
23503
23504        @Override
23505        public ActivityInfo getActivityInfo(
23506                ComponentName component, int flags, int filterCallingUid, int userId) {
23507            return PackageManagerService.this
23508                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23509        }
23510
23511        @Override
23512        public List<ResolveInfo> queryIntentActivities(
23513                Intent intent, int flags, int filterCallingUid, int userId) {
23514            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23515            return PackageManagerService.this
23516                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23517                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23518        }
23519
23520        @Override
23521        public List<ResolveInfo> queryIntentServices(
23522                Intent intent, int flags, int callingUid, int userId) {
23523            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23524            return PackageManagerService.this
23525                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23526                            false);
23527        }
23528
23529        @Override
23530        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23531                int userId) {
23532            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23533        }
23534
23535        @Override
23536        public void setDeviceAndProfileOwnerPackages(
23537                int deviceOwnerUserId, String deviceOwnerPackage,
23538                SparseArray<String> profileOwnerPackages) {
23539            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23540                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23541        }
23542
23543        @Override
23544        public boolean isPackageDataProtected(int userId, String packageName) {
23545            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23546        }
23547
23548        @Override
23549        public boolean isPackageEphemeral(int userId, String packageName) {
23550            synchronized (mPackages) {
23551                final PackageSetting ps = mSettings.mPackages.get(packageName);
23552                return ps != null ? ps.getInstantApp(userId) : false;
23553            }
23554        }
23555
23556        @Override
23557        public boolean wasPackageEverLaunched(String packageName, int userId) {
23558            synchronized (mPackages) {
23559                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23560            }
23561        }
23562
23563        @Override
23564        public void grantRuntimePermission(String packageName, String permName, int userId,
23565                boolean overridePolicy) {
23566            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23567                    permName, packageName, overridePolicy, getCallingUid(), userId,
23568                    mPermissionCallback);
23569        }
23570
23571        @Override
23572        public void revokeRuntimePermission(String packageName, String permName, int userId,
23573                boolean overridePolicy) {
23574            mPermissionManager.revokeRuntimePermission(
23575                    permName, packageName, overridePolicy, getCallingUid(), userId,
23576                    mPermissionCallback);
23577        }
23578
23579        @Override
23580        public String getNameForUid(int uid) {
23581            return PackageManagerService.this.getNameForUid(uid);
23582        }
23583
23584        @Override
23585        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23586                Intent origIntent, String resolvedType, String callingPackage,
23587                Bundle verificationBundle, int userId) {
23588            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23589                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23590                    userId);
23591        }
23592
23593        @Override
23594        public void grantEphemeralAccess(int userId, Intent intent,
23595                int targetAppId, int ephemeralAppId) {
23596            synchronized (mPackages) {
23597                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23598                        targetAppId, ephemeralAppId);
23599            }
23600        }
23601
23602        @Override
23603        public boolean isInstantAppInstallerComponent(ComponentName component) {
23604            synchronized (mPackages) {
23605                return mInstantAppInstallerActivity != null
23606                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23607            }
23608        }
23609
23610        @Override
23611        public void pruneInstantApps() {
23612            mInstantAppRegistry.pruneInstantApps();
23613        }
23614
23615        @Override
23616        public String getSetupWizardPackageName() {
23617            return mSetupWizardPackage;
23618        }
23619
23620        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23621            if (policy != null) {
23622                mExternalSourcesPolicy = policy;
23623            }
23624        }
23625
23626        @Override
23627        public boolean isPackagePersistent(String packageName) {
23628            synchronized (mPackages) {
23629                PackageParser.Package pkg = mPackages.get(packageName);
23630                return pkg != null
23631                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23632                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23633                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23634                        : false;
23635            }
23636        }
23637
23638        @Override
23639        public boolean isLegacySystemApp(Package pkg) {
23640            synchronized (mPackages) {
23641                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23642                return mPromoteSystemApps
23643                        && ps.isSystem()
23644                        && mExistingSystemPackages.contains(ps.name);
23645            }
23646        }
23647
23648        @Override
23649        public List<PackageInfo> getOverlayPackages(int userId) {
23650            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23651            synchronized (mPackages) {
23652                for (PackageParser.Package p : mPackages.values()) {
23653                    if (p.mOverlayTarget != null) {
23654                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23655                        if (pkg != null) {
23656                            overlayPackages.add(pkg);
23657                        }
23658                    }
23659                }
23660            }
23661            return overlayPackages;
23662        }
23663
23664        @Override
23665        public List<String> getTargetPackageNames(int userId) {
23666            List<String> targetPackages = new ArrayList<>();
23667            synchronized (mPackages) {
23668                for (PackageParser.Package p : mPackages.values()) {
23669                    if (p.mOverlayTarget == null) {
23670                        targetPackages.add(p.packageName);
23671                    }
23672                }
23673            }
23674            return targetPackages;
23675        }
23676
23677        @Override
23678        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23679                @Nullable List<String> overlayPackageNames) {
23680            synchronized (mPackages) {
23681                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23682                    Slog.e(TAG, "failed to find package " + targetPackageName);
23683                    return false;
23684                }
23685                ArrayList<String> overlayPaths = null;
23686                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23687                    final int N = overlayPackageNames.size();
23688                    overlayPaths = new ArrayList<>(N);
23689                    for (int i = 0; i < N; i++) {
23690                        final String packageName = overlayPackageNames.get(i);
23691                        final PackageParser.Package pkg = mPackages.get(packageName);
23692                        if (pkg == null) {
23693                            Slog.e(TAG, "failed to find package " + packageName);
23694                            return false;
23695                        }
23696                        overlayPaths.add(pkg.baseCodePath);
23697                    }
23698                }
23699
23700                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23701                ps.setOverlayPaths(overlayPaths, userId);
23702                return true;
23703            }
23704        }
23705
23706        @Override
23707        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23708                int flags, int userId, boolean resolveForStart) {
23709            return resolveIntentInternal(
23710                    intent, resolvedType, flags, userId, resolveForStart);
23711        }
23712
23713        @Override
23714        public ResolveInfo resolveService(Intent intent, String resolvedType,
23715                int flags, int userId, int callingUid) {
23716            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23717        }
23718
23719        @Override
23720        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23721            return PackageManagerService.this.resolveContentProviderInternal(
23722                    name, flags, userId);
23723        }
23724
23725        @Override
23726        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23727            synchronized (mPackages) {
23728                mIsolatedOwners.put(isolatedUid, ownerUid);
23729            }
23730        }
23731
23732        @Override
23733        public void removeIsolatedUid(int isolatedUid) {
23734            synchronized (mPackages) {
23735                mIsolatedOwners.delete(isolatedUid);
23736            }
23737        }
23738
23739        @Override
23740        public int getUidTargetSdkVersion(int uid) {
23741            synchronized (mPackages) {
23742                return getUidTargetSdkVersionLockedLPr(uid);
23743            }
23744        }
23745
23746        @Override
23747        public int getPackageTargetSdkVersion(String packageName) {
23748            synchronized (mPackages) {
23749                return getPackageTargetSdkVersionLockedLPr(packageName);
23750            }
23751        }
23752
23753        @Override
23754        public boolean canAccessInstantApps(int callingUid, int userId) {
23755            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23756        }
23757
23758        @Override
23759        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23760            synchronized (mPackages) {
23761                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23762            }
23763        }
23764
23765        @Override
23766        public void notifyPackageUse(String packageName, int reason) {
23767            synchronized (mPackages) {
23768                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23769            }
23770        }
23771    }
23772
23773    @Override
23774    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23775        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23776        synchronized (mPackages) {
23777            final long identity = Binder.clearCallingIdentity();
23778            try {
23779                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23780                        packageNames, userId);
23781            } finally {
23782                Binder.restoreCallingIdentity(identity);
23783            }
23784        }
23785    }
23786
23787    @Override
23788    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23789        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23790        synchronized (mPackages) {
23791            final long identity = Binder.clearCallingIdentity();
23792            try {
23793                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23794                        packageNames, userId);
23795            } finally {
23796                Binder.restoreCallingIdentity(identity);
23797            }
23798        }
23799    }
23800
23801    private static void enforceSystemOrPhoneCaller(String tag) {
23802        int callingUid = Binder.getCallingUid();
23803        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23804            throw new SecurityException(
23805                    "Cannot call " + tag + " from UID " + callingUid);
23806        }
23807    }
23808
23809    boolean isHistoricalPackageUsageAvailable() {
23810        return mPackageUsage.isHistoricalPackageUsageAvailable();
23811    }
23812
23813    /**
23814     * Return a <b>copy</b> of the collection of packages known to the package manager.
23815     * @return A copy of the values of mPackages.
23816     */
23817    Collection<PackageParser.Package> getPackages() {
23818        synchronized (mPackages) {
23819            return new ArrayList<>(mPackages.values());
23820        }
23821    }
23822
23823    /**
23824     * Logs process start information (including base APK hash) to the security log.
23825     * @hide
23826     */
23827    @Override
23828    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23829            String apkFile, int pid) {
23830        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23831            return;
23832        }
23833        if (!SecurityLog.isLoggingEnabled()) {
23834            return;
23835        }
23836        Bundle data = new Bundle();
23837        data.putLong("startTimestamp", System.currentTimeMillis());
23838        data.putString("processName", processName);
23839        data.putInt("uid", uid);
23840        data.putString("seinfo", seinfo);
23841        data.putString("apkFile", apkFile);
23842        data.putInt("pid", pid);
23843        Message msg = mProcessLoggingHandler.obtainMessage(
23844                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23845        msg.setData(data);
23846        mProcessLoggingHandler.sendMessage(msg);
23847    }
23848
23849    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23850        return mCompilerStats.getPackageStats(pkgName);
23851    }
23852
23853    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23854        return getOrCreateCompilerPackageStats(pkg.packageName);
23855    }
23856
23857    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23858        return mCompilerStats.getOrCreatePackageStats(pkgName);
23859    }
23860
23861    public void deleteCompilerPackageStats(String pkgName) {
23862        mCompilerStats.deletePackageStats(pkgName);
23863    }
23864
23865    @Override
23866    public int getInstallReason(String packageName, int userId) {
23867        final int callingUid = Binder.getCallingUid();
23868        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23869                true /* requireFullPermission */, false /* checkShell */,
23870                "get install reason");
23871        synchronized (mPackages) {
23872            final PackageSetting ps = mSettings.mPackages.get(packageName);
23873            if (filterAppAccessLPr(ps, callingUid, userId)) {
23874                return PackageManager.INSTALL_REASON_UNKNOWN;
23875            }
23876            if (ps != null) {
23877                return ps.getInstallReason(userId);
23878            }
23879        }
23880        return PackageManager.INSTALL_REASON_UNKNOWN;
23881    }
23882
23883    @Override
23884    public boolean canRequestPackageInstalls(String packageName, int userId) {
23885        return canRequestPackageInstallsInternal(packageName, 0, userId,
23886                true /* throwIfPermNotDeclared*/);
23887    }
23888
23889    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23890            boolean throwIfPermNotDeclared) {
23891        int callingUid = Binder.getCallingUid();
23892        int uid = getPackageUid(packageName, 0, userId);
23893        if (callingUid != uid && callingUid != Process.ROOT_UID
23894                && callingUid != Process.SYSTEM_UID) {
23895            throw new SecurityException(
23896                    "Caller uid " + callingUid + " does not own package " + packageName);
23897        }
23898        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23899        if (info == null) {
23900            return false;
23901        }
23902        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23903            return false;
23904        }
23905        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23906        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23907        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23908            if (throwIfPermNotDeclared) {
23909                throw new SecurityException("Need to declare " + appOpPermission
23910                        + " to call this api");
23911            } else {
23912                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23913                return false;
23914            }
23915        }
23916        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23917            return false;
23918        }
23919        if (mExternalSourcesPolicy != null) {
23920            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23921            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23922                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23923            }
23924        }
23925        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23926    }
23927
23928    @Override
23929    public ComponentName getInstantAppResolverSettingsComponent() {
23930        return mInstantAppResolverSettingsComponent;
23931    }
23932
23933    @Override
23934    public ComponentName getInstantAppInstallerComponent() {
23935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23936            return null;
23937        }
23938        return mInstantAppInstallerActivity == null
23939                ? null : mInstantAppInstallerActivity.getComponentName();
23940    }
23941
23942    @Override
23943    public String getInstantAppAndroidId(String packageName, int userId) {
23944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23945                "getInstantAppAndroidId");
23946        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23947                true /* requireFullPermission */, false /* checkShell */,
23948                "getInstantAppAndroidId");
23949        // Make sure the target is an Instant App.
23950        if (!isInstantApp(packageName, userId)) {
23951            return null;
23952        }
23953        synchronized (mPackages) {
23954            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23955        }
23956    }
23957
23958    boolean canHaveOatDir(String packageName) {
23959        synchronized (mPackages) {
23960            PackageParser.Package p = mPackages.get(packageName);
23961            if (p == null) {
23962                return false;
23963            }
23964            return p.canHaveOatDir();
23965        }
23966    }
23967
23968    private String getOatDir(PackageParser.Package pkg) {
23969        if (!pkg.canHaveOatDir()) {
23970            return null;
23971        }
23972        File codePath = new File(pkg.codePath);
23973        if (codePath.isDirectory()) {
23974            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23975        }
23976        return null;
23977    }
23978
23979    void deleteOatArtifactsOfPackage(String packageName) {
23980        final String[] instructionSets;
23981        final List<String> codePaths;
23982        final String oatDir;
23983        final PackageParser.Package pkg;
23984        synchronized (mPackages) {
23985            pkg = mPackages.get(packageName);
23986        }
23987        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23988        codePaths = pkg.getAllCodePaths();
23989        oatDir = getOatDir(pkg);
23990
23991        for (String codePath : codePaths) {
23992            for (String isa : instructionSets) {
23993                try {
23994                    mInstaller.deleteOdex(codePath, isa, oatDir);
23995                } catch (InstallerException e) {
23996                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23997                }
23998            }
23999        }
24000    }
24001
24002    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24003        Set<String> unusedPackages = new HashSet<>();
24004        long currentTimeInMillis = System.currentTimeMillis();
24005        synchronized (mPackages) {
24006            for (PackageParser.Package pkg : mPackages.values()) {
24007                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24008                if (ps == null) {
24009                    continue;
24010                }
24011                PackageDexUsage.PackageUseInfo packageUseInfo =
24012                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24013                if (PackageManagerServiceUtils
24014                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24015                                downgradeTimeThresholdMillis, packageUseInfo,
24016                                pkg.getLatestPackageUseTimeInMills(),
24017                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24018                    unusedPackages.add(pkg.packageName);
24019                }
24020            }
24021        }
24022        return unusedPackages;
24023    }
24024
24025    @Override
24026    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24027            int userId) {
24028        final int callingUid = Binder.getCallingUid();
24029        final int callingAppId = UserHandle.getAppId(callingUid);
24030
24031        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24032                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24033
24034        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24035                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24036            throw new SecurityException("Caller must have the "
24037                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24038        }
24039
24040        synchronized(mPackages) {
24041            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24042            scheduleWritePackageRestrictionsLocked(userId);
24043        }
24044    }
24045
24046    @Nullable
24047    @Override
24048    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24049        final int callingUid = Binder.getCallingUid();
24050        final int callingAppId = UserHandle.getAppId(callingUid);
24051
24052        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24053                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24054
24055        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24056                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24057            throw new SecurityException("Caller must have the "
24058                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24059        }
24060
24061        synchronized(mPackages) {
24062            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24063        }
24064    }
24065}
24066
24067interface PackageSender {
24068    /**
24069     * @param userIds User IDs where the action occurred on a full application
24070     * @param instantUserIds User IDs where the action occurred on an instant application
24071     */
24072    void sendPackageBroadcast(final String action, final String pkg,
24073        final Bundle extras, final int flags, final String targetPkg,
24074        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24075    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24076        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24077    void notifyPackageAdded(String packageName);
24078    void notifyPackageRemoved(String packageName);
24079}
24080