PackageManagerService.java revision 3621be71d0fe8a349ca468aca99a53a17f6575b3
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.COMPONENT_ENABLED_STATE_DEFAULT;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
32import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
40import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
41import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
42import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
50import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_NEWER_SDK;
52import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
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_USER_RESTRICTED;
59import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
60import static android.content.pm.PackageManager.INSTALL_INTERNAL;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
82import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
83import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
84import static android.content.pm.PackageManager.PERMISSION_DENIED;
85import static android.content.pm.PackageManager.PERMISSION_GRANTED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
94import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
95import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
104import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
105import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
106import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
107import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
108import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
109import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
110import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
111import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
112import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
116
117import android.Manifest;
118import android.annotation.IntDef;
119import android.annotation.NonNull;
120import android.annotation.Nullable;
121import android.app.ActivityManager;
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.DexMetadataHelper;
195import android.content.pm.dex.IArtManager;
196import android.content.res.Resources;
197import android.database.ContentObserver;
198import android.graphics.Bitmap;
199import android.hardware.display.DisplayManager;
200import android.net.Uri;
201import android.os.Binder;
202import android.os.Build;
203import android.os.Bundle;
204import android.os.Debug;
205import android.os.Environment;
206import android.os.Environment.UserEnvironment;
207import android.os.FileUtils;
208import android.os.Handler;
209import android.os.IBinder;
210import android.os.Looper;
211import android.os.Message;
212import android.os.Parcel;
213import android.os.ParcelFileDescriptor;
214import android.os.PatternMatcher;
215import android.os.Process;
216import android.os.RemoteCallbackList;
217import android.os.RemoteException;
218import android.os.ResultReceiver;
219import android.os.SELinux;
220import android.os.ServiceManager;
221import android.os.ShellCallback;
222import android.os.SystemClock;
223import android.os.SystemProperties;
224import android.os.Trace;
225import android.os.UserHandle;
226import android.os.UserManager;
227import android.os.UserManagerInternal;
228import android.os.storage.IStorageManager;
229import android.os.storage.StorageEventListener;
230import android.os.storage.StorageManager;
231import android.os.storage.StorageManagerInternal;
232import android.os.storage.VolumeInfo;
233import android.os.storage.VolumeRecord;
234import android.provider.Settings.Global;
235import android.provider.Settings.Secure;
236import android.security.KeyStore;
237import android.security.SystemKeyStore;
238import android.service.pm.PackageServiceDumpProto;
239import android.system.ErrnoException;
240import android.system.Os;
241import android.text.TextUtils;
242import android.text.format.DateUtils;
243import android.util.ArrayMap;
244import android.util.ArraySet;
245import android.util.Base64;
246import android.util.DisplayMetrics;
247import android.util.EventLog;
248import android.util.ExceptionUtils;
249import android.util.Log;
250import android.util.LogPrinter;
251import android.util.LongSparseArray;
252import android.util.LongSparseLongArray;
253import android.util.MathUtils;
254import android.util.PackageUtils;
255import android.util.Pair;
256import android.util.PrintStreamPrinter;
257import android.util.Slog;
258import android.util.SparseArray;
259import android.util.SparseBooleanArray;
260import android.util.SparseIntArray;
261import android.util.TimingsTraceLog;
262import android.util.Xml;
263import android.util.jar.StrictJarFile;
264import android.util.proto.ProtoOutputStream;
265import android.view.Display;
266
267import com.android.internal.R;
268import com.android.internal.annotations.GuardedBy;
269import com.android.internal.app.IMediaContainerService;
270import com.android.internal.app.ResolverActivity;
271import com.android.internal.content.NativeLibraryHelper;
272import com.android.internal.content.PackageHelper;
273import com.android.internal.logging.MetricsLogger;
274import com.android.internal.os.IParcelFileDescriptorFactory;
275import com.android.internal.os.SomeArgs;
276import com.android.internal.os.Zygote;
277import com.android.internal.telephony.CarrierAppUtils;
278import com.android.internal.util.ArrayUtils;
279import com.android.internal.util.ConcurrentUtils;
280import com.android.internal.util.DumpUtils;
281import com.android.internal.util.FastXmlSerializer;
282import com.android.internal.util.IndentingPrintWriter;
283import com.android.internal.util.Preconditions;
284import com.android.internal.util.XmlUtils;
285import com.android.server.AttributeCache;
286import com.android.server.DeviceIdleController;
287import com.android.server.EventLogTags;
288import com.android.server.FgThread;
289import com.android.server.IntentResolver;
290import com.android.server.LocalServices;
291import com.android.server.LockGuard;
292import com.android.server.ServiceThread;
293import com.android.server.SystemConfig;
294import com.android.server.SystemServerInitThreadPool;
295import com.android.server.Watchdog;
296import com.android.server.net.NetworkPolicyManagerInternal;
297import com.android.server.pm.Installer.InstallerException;
298import com.android.server.pm.Settings.DatabaseVersion;
299import com.android.server.pm.Settings.VersionInfo;
300import com.android.server.pm.dex.ArtManagerService;
301import com.android.server.pm.dex.DexLogger;
302import com.android.server.pm.dex.DexManager;
303import com.android.server.pm.dex.DexoptOptions;
304import com.android.server.pm.dex.PackageDexUsage;
305import com.android.server.pm.permission.BasePermission;
306import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
307import com.android.server.pm.permission.PermissionManagerService;
308import com.android.server.pm.permission.PermissionManagerInternal;
309import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
310import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
311import com.android.server.pm.permission.PermissionsState;
312import com.android.server.pm.permission.PermissionsState.PermissionState;
313import com.android.server.storage.DeviceStorageMonitorInternal;
314
315import dalvik.system.CloseGuard;
316import dalvik.system.VMRuntime;
317
318import libcore.io.IoUtils;
319
320import org.xmlpull.v1.XmlPullParser;
321import org.xmlpull.v1.XmlPullParserException;
322import org.xmlpull.v1.XmlSerializer;
323
324import java.io.BufferedOutputStream;
325import java.io.ByteArrayInputStream;
326import java.io.ByteArrayOutputStream;
327import java.io.File;
328import java.io.FileDescriptor;
329import java.io.FileInputStream;
330import java.io.FileOutputStream;
331import java.io.FilenameFilter;
332import java.io.IOException;
333import java.io.PrintWriter;
334import java.lang.annotation.Retention;
335import java.lang.annotation.RetentionPolicy;
336import java.nio.charset.StandardCharsets;
337import java.security.DigestInputStream;
338import java.security.MessageDigest;
339import java.security.NoSuchAlgorithmException;
340import java.security.PublicKey;
341import java.security.SecureRandom;
342import java.security.cert.CertificateException;
343import java.util.ArrayList;
344import java.util.Arrays;
345import java.util.Collection;
346import java.util.Collections;
347import java.util.Comparator;
348import java.util.HashMap;
349import java.util.HashSet;
350import java.util.Iterator;
351import java.util.LinkedHashSet;
352import java.util.List;
353import java.util.Map;
354import java.util.Objects;
355import java.util.Set;
356import java.util.concurrent.CountDownLatch;
357import java.util.concurrent.Future;
358import java.util.concurrent.TimeUnit;
359import java.util.concurrent.atomic.AtomicBoolean;
360import java.util.concurrent.atomic.AtomicInteger;
361
362/**
363 * Keep track of all those APKs everywhere.
364 * <p>
365 * Internally there are two important locks:
366 * <ul>
367 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
368 * and other related state. It is a fine-grained lock that should only be held
369 * momentarily, as it's one of the most contended locks in the system.
370 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
371 * operations typically involve heavy lifting of application data on disk. Since
372 * {@code installd} is single-threaded, and it's operations can often be slow,
373 * this lock should never be acquired while already holding {@link #mPackages}.
374 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
375 * holding {@link #mInstallLock}.
376 * </ul>
377 * Many internal methods rely on the caller to hold the appropriate locks, and
378 * this contract is expressed through method name suffixes:
379 * <ul>
380 * <li>fooLI(): the caller must hold {@link #mInstallLock}
381 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
382 * being modified must be frozen
383 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
384 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
385 * </ul>
386 * <p>
387 * Because this class is very central to the platform's security; please run all
388 * CTS and unit tests whenever making modifications:
389 *
390 * <pre>
391 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
392 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
393 * </pre>
394 */
395public class PackageManagerService extends IPackageManager.Stub
396        implements PackageSender {
397    static final String TAG = "PackageManager";
398    public static final boolean DEBUG_SETTINGS = false;
399    static final boolean DEBUG_PREFERRED = false;
400    static final boolean DEBUG_UPGRADE = false;
401    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
402    private static final boolean DEBUG_BACKUP = false;
403    public static final boolean DEBUG_INSTALL = false;
404    public static final boolean DEBUG_REMOVE = false;
405    private static final boolean DEBUG_BROADCASTS = false;
406    private static final boolean DEBUG_SHOW_INFO = false;
407    private static final boolean DEBUG_PACKAGE_INFO = false;
408    private static final boolean DEBUG_INTENT_MATCHING = false;
409    public static final boolean DEBUG_PACKAGE_SCANNING = false;
410    private static final boolean DEBUG_VERIFY = false;
411    private static final boolean DEBUG_FILTERS = false;
412    public static final boolean DEBUG_PERMISSIONS = false;
413    private static final boolean DEBUG_SHARED_LIBRARIES = false;
414    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
415
416    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
417    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
418    // user, but by default initialize to this.
419    public static final boolean DEBUG_DEXOPT = false;
420
421    private static final boolean DEBUG_ABI_SELECTION = false;
422    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
423    private static final boolean DEBUG_TRIAGED_MISSING = false;
424    private static final boolean DEBUG_APP_DATA = false;
425
426    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
427    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
428
429    private static final boolean HIDE_EPHEMERAL_APIS = false;
430
431    private static final boolean ENABLE_FREE_CACHE_V2 =
432            SystemProperties.getBoolean("fw.free_cache_v2", true);
433
434    private static final int RADIO_UID = Process.PHONE_UID;
435    private static final int LOG_UID = Process.LOG_UID;
436    private static final int NFC_UID = Process.NFC_UID;
437    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
438    private static final int SHELL_UID = Process.SHELL_UID;
439
440    // Suffix used during package installation when copying/moving
441    // package apks to install directory.
442    private static final String INSTALL_PACKAGE_SUFFIX = "-";
443
444    static final int SCAN_NO_DEX = 1<<0;
445    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
446    static final int SCAN_NEW_INSTALL = 1<<2;
447    static final int SCAN_UPDATE_TIME = 1<<3;
448    static final int SCAN_BOOTING = 1<<4;
449    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
450    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
451    static final int SCAN_REQUIRE_KNOWN = 1<<7;
452    static final int SCAN_MOVE = 1<<8;
453    static final int SCAN_INITIAL = 1<<9;
454    static final int SCAN_CHECK_ONLY = 1<<10;
455    static final int SCAN_DONT_KILL_APP = 1<<11;
456    static final int SCAN_IGNORE_FROZEN = 1<<12;
457    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
458    static final int SCAN_AS_INSTANT_APP = 1<<14;
459    static final int SCAN_AS_FULL_APP = 1<<15;
460    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
461    static final int SCAN_AS_SYSTEM = 1<<17;
462    static final int SCAN_AS_PRIVILEGED = 1<<18;
463    static final int SCAN_AS_OEM = 1<<19;
464    static final int SCAN_AS_VENDOR = 1<<20;
465
466    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
467            SCAN_NO_DEX,
468            SCAN_UPDATE_SIGNATURE,
469            SCAN_NEW_INSTALL,
470            SCAN_UPDATE_TIME,
471            SCAN_BOOTING,
472            SCAN_TRUSTED_OVERLAY,
473            SCAN_DELETE_DATA_ON_FAILURES,
474            SCAN_REQUIRE_KNOWN,
475            SCAN_MOVE,
476            SCAN_INITIAL,
477            SCAN_CHECK_ONLY,
478            SCAN_DONT_KILL_APP,
479            SCAN_IGNORE_FROZEN,
480            SCAN_FIRST_BOOT_OR_UPGRADE,
481            SCAN_AS_INSTANT_APP,
482            SCAN_AS_FULL_APP,
483            SCAN_AS_VIRTUAL_PRELOAD,
484    })
485    @Retention(RetentionPolicy.SOURCE)
486    public @interface ScanFlags {}
487
488    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
489    /** Extension of the compressed packages */
490    public final static String COMPRESSED_EXTENSION = ".gz";
491    /** Suffix of stub packages on the system partition */
492    public final static String STUB_SUFFIX = "-Stub";
493
494    private static final int[] EMPTY_INT_ARRAY = new int[0];
495
496    private static final int TYPE_UNKNOWN = 0;
497    private static final int TYPE_ACTIVITY = 1;
498    private static final int TYPE_RECEIVER = 2;
499    private static final int TYPE_SERVICE = 3;
500    private static final int TYPE_PROVIDER = 4;
501    @IntDef(prefix = { "TYPE_" }, value = {
502            TYPE_UNKNOWN,
503            TYPE_ACTIVITY,
504            TYPE_RECEIVER,
505            TYPE_SERVICE,
506            TYPE_PROVIDER,
507    })
508    @Retention(RetentionPolicy.SOURCE)
509    public @interface ComponentType {}
510
511    /**
512     * Timeout (in milliseconds) after which the watchdog should declare that
513     * our handler thread is wedged.  The usual default for such things is one
514     * minute but we sometimes do very lengthy I/O operations on this thread,
515     * such as installing multi-gigabyte applications, so ours needs to be longer.
516     */
517    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
518
519    /**
520     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
521     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
522     * settings entry if available, otherwise we use the hardcoded default.  If it's been
523     * more than this long since the last fstrim, we force one during the boot sequence.
524     *
525     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
526     * one gets run at the next available charging+idle time.  This final mandatory
527     * no-fstrim check kicks in only of the other scheduling criteria is never met.
528     */
529    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
530
531    /**
532     * Whether verification is enabled by default.
533     */
534    private static final boolean DEFAULT_VERIFY_ENABLE = true;
535
536    /**
537     * The default maximum time to wait for the verification agent to return in
538     * milliseconds.
539     */
540    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
541
542    /**
543     * The default response for package verification timeout.
544     *
545     * This can be either PackageManager.VERIFICATION_ALLOW or
546     * PackageManager.VERIFICATION_REJECT.
547     */
548    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
549
550    public static final String PLATFORM_PACKAGE_NAME = "android";
551
552    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
553
554    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
555            DEFAULT_CONTAINER_PACKAGE,
556            "com.android.defcontainer.DefaultContainerService");
557
558    private static final String KILL_APP_REASON_GIDS_CHANGED =
559            "permission grant or revoke changed gids";
560
561    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
562            "permissions revoked";
563
564    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
565
566    private static final String PACKAGE_SCHEME = "package";
567
568    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
569
570    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
571
572    /** Canonical intent used to identify what counts as a "web browser" app */
573    private static final Intent sBrowserIntent;
574    static {
575        sBrowserIntent = new Intent();
576        sBrowserIntent.setAction(Intent.ACTION_VIEW);
577        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
578        sBrowserIntent.setData(Uri.parse("http:"));
579    }
580
581    /**
582     * The set of all protected actions [i.e. those actions for which a high priority
583     * intent filter is disallowed].
584     */
585    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
586    static {
587        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
588        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
589        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
590        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
591    }
592
593    // Compilation reasons.
594    public static final int REASON_FIRST_BOOT = 0;
595    public static final int REASON_BOOT = 1;
596    public static final int REASON_INSTALL = 2;
597    public static final int REASON_BACKGROUND_DEXOPT = 3;
598    public static final int REASON_AB_OTA = 4;
599    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
600    public static final int REASON_SHARED = 6;
601
602    public static final int REASON_LAST = REASON_SHARED;
603
604    /**
605     * Version number for the package parser cache. Increment this whenever the format or
606     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
607     */
608    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
609
610    /**
611     * Whether the package parser cache is enabled.
612     */
613    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
614
615    /**
616     * Permissions required in order to receive instant application lifecycle broadcasts.
617     */
618    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
619            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
620
621    final ServiceThread mHandlerThread;
622
623    final PackageHandler mHandler;
624
625    private final ProcessLoggingHandler mProcessLoggingHandler;
626
627    /**
628     * Messages for {@link #mHandler} that need to wait for system ready before
629     * being dispatched.
630     */
631    private ArrayList<Message> mPostSystemReadyMessages;
632
633    final int mSdkVersion = Build.VERSION.SDK_INT;
634
635    final Context mContext;
636    final boolean mFactoryTest;
637    final boolean mOnlyCore;
638    final DisplayMetrics mMetrics;
639    final int mDefParseFlags;
640    final String[] mSeparateProcesses;
641    final boolean mIsUpgrade;
642    final boolean mIsPreNUpgrade;
643    final boolean mIsPreNMR1Upgrade;
644
645    // Have we told the Activity Manager to whitelist the default container service by uid yet?
646    @GuardedBy("mPackages")
647    boolean mDefaultContainerWhitelisted = false;
648
649    @GuardedBy("mPackages")
650    private boolean mDexOptDialogShown;
651
652    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
653    // LOCK HELD.  Can be called with mInstallLock held.
654    @GuardedBy("mInstallLock")
655    final Installer mInstaller;
656
657    /** Directory where installed applications are stored */
658    private static final File sAppInstallDir =
659            new File(Environment.getDataDirectory(), "app");
660    /** Directory where installed application's 32-bit native libraries are copied. */
661    private static final File sAppLib32InstallDir =
662            new File(Environment.getDataDirectory(), "app-lib");
663    /** Directory where code and non-resource assets of forward-locked applications are stored */
664    private static final File sDrmAppPrivateInstallDir =
665            new File(Environment.getDataDirectory(), "app-private");
666
667    // ----------------------------------------------------------------
668
669    // Lock for state used when installing and doing other long running
670    // operations.  Methods that must be called with this lock held have
671    // the suffix "LI".
672    final Object mInstallLock = new Object();
673
674    // ----------------------------------------------------------------
675
676    // Keys are String (package name), values are Package.  This also serves
677    // as the lock for the global state.  Methods that must be called with
678    // this lock held have the prefix "LP".
679    @GuardedBy("mPackages")
680    final ArrayMap<String, PackageParser.Package> mPackages =
681            new ArrayMap<String, PackageParser.Package>();
682
683    final ArrayMap<String, Set<String>> mKnownCodebase =
684            new ArrayMap<String, Set<String>>();
685
686    // Keys are isolated uids and values are the uid of the application
687    // that created the isolated proccess.
688    @GuardedBy("mPackages")
689    final SparseIntArray mIsolatedOwners = new SparseIntArray();
690
691    /**
692     * Tracks new system packages [received in an OTA] that we expect to
693     * find updated user-installed versions. Keys are package name, values
694     * are package location.
695     */
696    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
697    /**
698     * Tracks high priority intent filters for protected actions. During boot, certain
699     * filter actions are protected and should never be allowed to have a high priority
700     * intent filter for them. However, there is one, and only one exception -- the
701     * setup wizard. It must be able to define a high priority intent filter for these
702     * actions to ensure there are no escapes from the wizard. We need to delay processing
703     * of these during boot as we need to look at all of the system packages in order
704     * to know which component is the setup wizard.
705     */
706    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
707    /**
708     * Whether or not processing protected filters should be deferred.
709     */
710    private boolean mDeferProtectedFilters = true;
711
712    /**
713     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
714     */
715    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
716    /**
717     * Whether or not system app permissions should be promoted from install to runtime.
718     */
719    boolean mPromoteSystemApps;
720
721    @GuardedBy("mPackages")
722    final Settings mSettings;
723
724    /**
725     * Set of package names that are currently "frozen", which means active
726     * surgery is being done on the code/data for that package. The platform
727     * will refuse to launch frozen packages to avoid race conditions.
728     *
729     * @see PackageFreezer
730     */
731    @GuardedBy("mPackages")
732    final ArraySet<String> mFrozenPackages = new ArraySet<>();
733
734    final ProtectedPackages mProtectedPackages;
735
736    @GuardedBy("mLoadedVolumes")
737    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
738
739    boolean mFirstBoot;
740
741    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
742
743    @GuardedBy("mAvailableFeatures")
744    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
745
746    private final InstantAppRegistry mInstantAppRegistry;
747
748    @GuardedBy("mPackages")
749    int mChangedPackagesSequenceNumber;
750    /**
751     * List of changed [installed, removed or updated] packages.
752     * mapping from user id -> sequence number -> package name
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
756    /**
757     * The sequence number of the last change to a package.
758     * mapping from user id -> package name -> sequence number
759     */
760    @GuardedBy("mPackages")
761    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
762
763    @GuardedBy("mPackages")
764    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
765
766    class PackageParserCallback implements PackageParser.Callback {
767        @Override public final boolean hasFeature(String feature) {
768            return PackageManagerService.this.hasSystemFeature(feature, 0);
769        }
770
771        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
772                Collection<PackageParser.Package> allPackages, String targetPackageName) {
773            List<PackageParser.Package> overlayPackages = null;
774            for (PackageParser.Package p : allPackages) {
775                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
776                    if (overlayPackages == null) {
777                        overlayPackages = new ArrayList<PackageParser.Package>();
778                    }
779                    overlayPackages.add(p);
780                }
781            }
782            if (overlayPackages != null) {
783                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
784                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
785                        return p1.mOverlayPriority - p2.mOverlayPriority;
786                    }
787                };
788                Collections.sort(overlayPackages, cmp);
789            }
790            return overlayPackages;
791        }
792
793        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
794                String targetPackageName, String targetPath) {
795            if ("android".equals(targetPackageName)) {
796                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
797                // native AssetManager.
798                return null;
799            }
800            List<PackageParser.Package> overlayPackages =
801                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
802            if (overlayPackages == null || overlayPackages.isEmpty()) {
803                return null;
804            }
805            List<String> overlayPathList = null;
806            for (PackageParser.Package overlayPackage : overlayPackages) {
807                if (targetPath == null) {
808                    if (overlayPathList == null) {
809                        overlayPathList = new ArrayList<String>();
810                    }
811                    overlayPathList.add(overlayPackage.baseCodePath);
812                    continue;
813                }
814
815                try {
816                    // Creates idmaps for system to parse correctly the Android manifest of the
817                    // target package.
818                    //
819                    // OverlayManagerService will update each of them with a correct gid from its
820                    // target package app id.
821                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
822                            UserHandle.getSharedAppGid(
823                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                } catch (InstallerException e) {
829                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
830                            overlayPackage.baseCodePath);
831                }
832            }
833            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
834        }
835
836        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
837            synchronized (mPackages) {
838                return getStaticOverlayPathsLocked(
839                        mPackages.values(), targetPackageName, targetPath);
840            }
841        }
842
843        @Override public final String[] getOverlayApks(String targetPackageName) {
844            return getStaticOverlayPaths(targetPackageName, null);
845        }
846
847        @Override public final String[] getOverlayPaths(String targetPackageName,
848                String targetPath) {
849            return getStaticOverlayPaths(targetPackageName, targetPath);
850        }
851    }
852
853    class ParallelPackageParserCallback extends PackageParserCallback {
854        List<PackageParser.Package> mOverlayPackages = null;
855
856        void findStaticOverlayPackages() {
857            synchronized (mPackages) {
858                for (PackageParser.Package p : mPackages.values()) {
859                    if (p.mIsStaticOverlay) {
860                        if (mOverlayPackages == null) {
861                            mOverlayPackages = new ArrayList<PackageParser.Package>();
862                        }
863                        mOverlayPackages.add(p);
864                    }
865                }
866            }
867        }
868
869        @Override
870        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
871            // We can trust mOverlayPackages without holding mPackages because package uninstall
872            // can't happen while running parallel parsing.
873            // Moreover holding mPackages on each parsing thread causes dead-lock.
874            return mOverlayPackages == null ? null :
875                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
876        }
877    }
878
879    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
880    final ParallelPackageParserCallback mParallelPackageParserCallback =
881            new ParallelPackageParserCallback();
882
883    public static final class SharedLibraryEntry {
884        public final @Nullable String path;
885        public final @Nullable String apk;
886        public final @NonNull SharedLibraryInfo info;
887
888        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
889                String declaringPackageName, long declaringPackageVersionCode) {
890            path = _path;
891            apk = _apk;
892            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
893                    declaringPackageName, declaringPackageVersionCode), null);
894        }
895    }
896
897    // Currently known shared libraries.
898    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
899    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
900            new ArrayMap<>();
901
902    // All available activities, for your resolving pleasure.
903    final ActivityIntentResolver mActivities =
904            new ActivityIntentResolver();
905
906    // All available receivers, for your resolving pleasure.
907    final ActivityIntentResolver mReceivers =
908            new ActivityIntentResolver();
909
910    // All available services, for your resolving pleasure.
911    final ServiceIntentResolver mServices = new ServiceIntentResolver();
912
913    // All available providers, for your resolving pleasure.
914    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
915
916    // Mapping from provider base names (first directory in content URI codePath)
917    // to the provider information.
918    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
919            new ArrayMap<String, PackageParser.Provider>();
920
921    // Mapping from instrumentation class names to info about them.
922    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
923            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
924
925    // Packages whose data we have transfered into another package, thus
926    // should no longer exist.
927    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
928
929    // Broadcast actions that are only available to the system.
930    @GuardedBy("mProtectedBroadcasts")
931    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
932
933    /** List of packages waiting for verification. */
934    final SparseArray<PackageVerificationState> mPendingVerification
935            = new SparseArray<PackageVerificationState>();
936
937    final PackageInstallerService mInstallerService;
938
939    final ArtManagerService mArtManagerService;
940
941    private final PackageDexOptimizer mPackageDexOptimizer;
942    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
943    // is used by other apps).
944    private final DexManager mDexManager;
945
946    private AtomicInteger mNextMoveId = new AtomicInteger();
947    private final MoveCallbacks mMoveCallbacks;
948
949    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
950
951    // Cache of users who need badging.
952    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
953
954    /** Token for keys in mPendingVerification. */
955    private int mPendingVerificationToken = 0;
956
957    volatile boolean mSystemReady;
958    volatile boolean mSafeMode;
959    volatile boolean mHasSystemUidErrors;
960    private volatile boolean mEphemeralAppsDisabled;
961
962    ApplicationInfo mAndroidApplication;
963    final ActivityInfo mResolveActivity = new ActivityInfo();
964    final ResolveInfo mResolveInfo = new ResolveInfo();
965    ComponentName mResolveComponentName;
966    PackageParser.Package mPlatformPackage;
967    ComponentName mCustomResolverComponentName;
968
969    boolean mResolverReplaced = false;
970
971    private final @Nullable ComponentName mIntentFilterVerifierComponent;
972    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
973
974    private int mIntentFilterVerificationToken = 0;
975
976    /** The service connection to the ephemeral resolver */
977    final EphemeralResolverConnection mInstantAppResolverConnection;
978    /** Component used to show resolver settings for Instant Apps */
979    final ComponentName mInstantAppResolverSettingsComponent;
980
981    /** Activity used to install instant applications */
982    ActivityInfo mInstantAppInstallerActivity;
983    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
984
985    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
986            = new SparseArray<IntentFilterVerificationState>();
987
988    // TODO remove this and go through mPermissonManager directly
989    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
990    private final PermissionManagerInternal mPermissionManager;
991
992    // List of packages names to keep cached, even if they are uninstalled for all users
993    private List<String> mKeepUninstalledPackages;
994
995    private UserManagerInternal mUserManagerInternal;
996
997    private DeviceIdleController.LocalService mDeviceIdleController;
998
999    private File mCacheDir;
1000
1001    private Future<?> mPrepareAppDataFuture;
1002
1003    private static class IFVerificationParams {
1004        PackageParser.Package pkg;
1005        boolean replacing;
1006        int userId;
1007        int verifierUid;
1008
1009        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1010                int _userId, int _verifierUid) {
1011            pkg = _pkg;
1012            replacing = _replacing;
1013            userId = _userId;
1014            replacing = _replacing;
1015            verifierUid = _verifierUid;
1016        }
1017    }
1018
1019    private interface IntentFilterVerifier<T extends IntentFilter> {
1020        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1021                                               T filter, String packageName);
1022        void startVerifications(int userId);
1023        void receiveVerificationResponse(int verificationId);
1024    }
1025
1026    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1027        private Context mContext;
1028        private ComponentName mIntentFilterVerifierComponent;
1029        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1030
1031        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1032            mContext = context;
1033            mIntentFilterVerifierComponent = verifierComponent;
1034        }
1035
1036        private String getDefaultScheme() {
1037            return IntentFilter.SCHEME_HTTPS;
1038        }
1039
1040        @Override
1041        public void startVerifications(int userId) {
1042            // Launch verifications requests
1043            int count = mCurrentIntentFilterVerifications.size();
1044            for (int n=0; n<count; n++) {
1045                int verificationId = mCurrentIntentFilterVerifications.get(n);
1046                final IntentFilterVerificationState ivs =
1047                        mIntentFilterVerificationStates.get(verificationId);
1048
1049                String packageName = ivs.getPackageName();
1050
1051                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1052                final int filterCount = filters.size();
1053                ArraySet<String> domainsSet = new ArraySet<>();
1054                for (int m=0; m<filterCount; m++) {
1055                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1056                    domainsSet.addAll(filter.getHostsList());
1057                }
1058                synchronized (mPackages) {
1059                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1060                            packageName, domainsSet) != null) {
1061                        scheduleWriteSettingsLocked();
1062                    }
1063                }
1064                sendVerificationRequest(verificationId, ivs);
1065            }
1066            mCurrentIntentFilterVerifications.clear();
1067        }
1068
1069        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1070            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1073                    verificationId);
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1076                    getDefaultScheme());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1079                    ivs.getHostsString());
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1082                    ivs.getPackageName());
1083            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1084            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1085
1086            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1087            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1088                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1089                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1090
1091            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1092            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1093                    "Sending IntentFilter verification broadcast");
1094        }
1095
1096        public void receiveVerificationResponse(int verificationId) {
1097            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1098
1099            final boolean verified = ivs.isVerified();
1100
1101            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1102            final int count = filters.size();
1103            if (DEBUG_DOMAIN_VERIFICATION) {
1104                Slog.i(TAG, "Received verification response " + verificationId
1105                        + " for " + count + " filters, verified=" + verified);
1106            }
1107            for (int n=0; n<count; n++) {
1108                PackageParser.ActivityIntentInfo filter = filters.get(n);
1109                filter.setVerified(verified);
1110
1111                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1112                        + " verified with result:" + verified + " and hosts:"
1113                        + ivs.getHostsString());
1114            }
1115
1116            mIntentFilterVerificationStates.remove(verificationId);
1117
1118            final String packageName = ivs.getPackageName();
1119            IntentFilterVerificationInfo ivi = null;
1120
1121            synchronized (mPackages) {
1122                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1123            }
1124            if (ivi == null) {
1125                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1126                        + verificationId + " packageName:" + packageName);
1127                return;
1128            }
1129            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1130                    "Updating IntentFilterVerificationInfo for package " + packageName
1131                            +" verificationId:" + verificationId);
1132
1133            synchronized (mPackages) {
1134                if (verified) {
1135                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1136                } else {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1138                }
1139                scheduleWriteSettingsLocked();
1140
1141                final int userId = ivs.getUserId();
1142                if (userId != UserHandle.USER_ALL) {
1143                    final int userStatus =
1144                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1145
1146                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1147                    boolean needUpdate = false;
1148
1149                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1150                    // already been set by the User thru the Disambiguation dialog
1151                    switch (userStatus) {
1152                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1153                            if (verified) {
1154                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1155                            } else {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1157                            }
1158                            needUpdate = true;
1159                            break;
1160
1161                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1162                            if (verified) {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1164                                needUpdate = true;
1165                            }
1166                            break;
1167
1168                        default:
1169                            // Nothing to do
1170                    }
1171
1172                    if (needUpdate) {
1173                        mSettings.updateIntentFilterVerificationStatusLPw(
1174                                packageName, updatedStatus, userId);
1175                        scheduleWritePackageRestrictionsLocked(userId);
1176                    }
1177                }
1178            }
1179        }
1180
1181        @Override
1182        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1183                    ActivityIntentInfo filter, String packageName) {
1184            if (!hasValidDomains(filter)) {
1185                return false;
1186            }
1187            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1188            if (ivs == null) {
1189                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1190                        packageName);
1191            }
1192            if (DEBUG_DOMAIN_VERIFICATION) {
1193                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1194            }
1195            ivs.addFilter(filter);
1196            return true;
1197        }
1198
1199        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1200                int userId, int verificationId, String packageName) {
1201            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1202                    verifierUid, userId, packageName);
1203            ivs.setPendingState();
1204            synchronized (mPackages) {
1205                mIntentFilterVerificationStates.append(verificationId, ivs);
1206                mCurrentIntentFilterVerifications.add(verificationId);
1207            }
1208            return ivs;
1209        }
1210    }
1211
1212    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1213        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1214                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1215                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1216    }
1217
1218    // Set of pending broadcasts for aggregating enable/disable of components.
1219    static class PendingPackageBroadcasts {
1220        // for each user id, a map of <package name -> components within that package>
1221        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1222
1223        public PendingPackageBroadcasts() {
1224            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1225        }
1226
1227        public ArrayList<String> get(int userId, String packageName) {
1228            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1229            return packages.get(packageName);
1230        }
1231
1232        public void put(int userId, String packageName, ArrayList<String> components) {
1233            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1234            packages.put(packageName, components);
1235        }
1236
1237        public void remove(int userId, String packageName) {
1238            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1239            if (packages != null) {
1240                packages.remove(packageName);
1241            }
1242        }
1243
1244        public void remove(int userId) {
1245            mUidMap.remove(userId);
1246        }
1247
1248        public int userIdCount() {
1249            return mUidMap.size();
1250        }
1251
1252        public int userIdAt(int n) {
1253            return mUidMap.keyAt(n);
1254        }
1255
1256        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1257            return mUidMap.get(userId);
1258        }
1259
1260        public int size() {
1261            // total number of pending broadcast entries across all userIds
1262            int num = 0;
1263            for (int i = 0; i< mUidMap.size(); i++) {
1264                num += mUidMap.valueAt(i).size();
1265            }
1266            return num;
1267        }
1268
1269        public void clear() {
1270            mUidMap.clear();
1271        }
1272
1273        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1274            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1275            if (map == null) {
1276                map = new ArrayMap<String, ArrayList<String>>();
1277                mUidMap.put(userId, map);
1278            }
1279            return map;
1280        }
1281    }
1282    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1283
1284    // Service Connection to remote media container service to copy
1285    // package uri's from external media onto secure containers
1286    // or internal storage.
1287    private IMediaContainerService mContainerService = null;
1288
1289    static final int SEND_PENDING_BROADCAST = 1;
1290    static final int MCS_BOUND = 3;
1291    static final int END_COPY = 4;
1292    static final int INIT_COPY = 5;
1293    static final int MCS_UNBIND = 6;
1294    static final int START_CLEANING_PACKAGE = 7;
1295    static final int FIND_INSTALL_LOC = 8;
1296    static final int POST_INSTALL = 9;
1297    static final int MCS_RECONNECT = 10;
1298    static final int MCS_GIVE_UP = 11;
1299    static final int WRITE_SETTINGS = 13;
1300    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1301    static final int PACKAGE_VERIFIED = 15;
1302    static final int CHECK_PENDING_VERIFICATION = 16;
1303    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1304    static final int INTENT_FILTER_VERIFIED = 18;
1305    static final int WRITE_PACKAGE_LIST = 19;
1306    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1307
1308    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1309
1310    // Delay time in millisecs
1311    static final int BROADCAST_DELAY = 10 * 1000;
1312
1313    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1314            2 * 60 * 60 * 1000L; /* two hours */
1315
1316    static UserManagerService sUserManager;
1317
1318    // Stores a list of users whose package restrictions file needs to be updated
1319    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1320
1321    final private DefaultContainerConnection mDefContainerConn =
1322            new DefaultContainerConnection();
1323    class DefaultContainerConnection implements ServiceConnection {
1324        public void onServiceConnected(ComponentName name, IBinder service) {
1325            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1326            final IMediaContainerService imcs = IMediaContainerService.Stub
1327                    .asInterface(Binder.allowBlocking(service));
1328            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1329        }
1330
1331        public void onServiceDisconnected(ComponentName name) {
1332            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1333        }
1334    }
1335
1336    // Recordkeeping of restore-after-install operations that are currently in flight
1337    // between the Package Manager and the Backup Manager
1338    static class PostInstallData {
1339        public InstallArgs args;
1340        public PackageInstalledInfo res;
1341
1342        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1343            args = _a;
1344            res = _r;
1345        }
1346    }
1347
1348    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1349    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1350
1351    // XML tags for backup/restore of various bits of state
1352    private static final String TAG_PREFERRED_BACKUP = "pa";
1353    private static final String TAG_DEFAULT_APPS = "da";
1354    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1355
1356    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1357    private static final String TAG_ALL_GRANTS = "rt-grants";
1358    private static final String TAG_GRANT = "grant";
1359    private static final String ATTR_PACKAGE_NAME = "pkg";
1360
1361    private static final String TAG_PERMISSION = "perm";
1362    private static final String ATTR_PERMISSION_NAME = "name";
1363    private static final String ATTR_IS_GRANTED = "g";
1364    private static final String ATTR_USER_SET = "set";
1365    private static final String ATTR_USER_FIXED = "fixed";
1366    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1367
1368    // System/policy permission grants are not backed up
1369    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1370            FLAG_PERMISSION_POLICY_FIXED
1371            | FLAG_PERMISSION_SYSTEM_FIXED
1372            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1373
1374    // And we back up these user-adjusted states
1375    private static final int USER_RUNTIME_GRANT_MASK =
1376            FLAG_PERMISSION_USER_SET
1377            | FLAG_PERMISSION_USER_FIXED
1378            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1379
1380    final @Nullable String mRequiredVerifierPackage;
1381    final @NonNull String mRequiredInstallerPackage;
1382    final @NonNull String mRequiredUninstallerPackage;
1383    final @Nullable String mSetupWizardPackage;
1384    final @Nullable String mStorageManagerPackage;
1385    final @NonNull String mServicesSystemSharedLibraryPackageName;
1386    final @NonNull String mSharedSystemSharedLibraryPackageName;
1387
1388    private final PackageUsage mPackageUsage = new PackageUsage();
1389    private final CompilerStats mCompilerStats = new CompilerStats();
1390
1391    class PackageHandler extends Handler {
1392        private boolean mBound = false;
1393        final ArrayList<HandlerParams> mPendingInstalls =
1394            new ArrayList<HandlerParams>();
1395
1396        private boolean connectToService() {
1397            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1398                    " DefaultContainerService");
1399            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1402                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1403                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                mBound = true;
1405                return true;
1406            }
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408            return false;
1409        }
1410
1411        private void disconnectService() {
1412            mContainerService = null;
1413            mBound = false;
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415            mContext.unbindService(mDefContainerConn);
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417        }
1418
1419        PackageHandler(Looper looper) {
1420            super(looper);
1421        }
1422
1423        public void handleMessage(Message msg) {
1424            try {
1425                doHandleMessage(msg);
1426            } finally {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428            }
1429        }
1430
1431        void doHandleMessage(Message msg) {
1432            switch (msg.what) {
1433                case INIT_COPY: {
1434                    HandlerParams params = (HandlerParams) msg.obj;
1435                    int idx = mPendingInstalls.size();
1436                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1437                    // If a bind was already initiated we dont really
1438                    // need to do anything. The pending install
1439                    // will be processed later on.
1440                    if (!mBound) {
1441                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1442                                System.identityHashCode(mHandler));
1443                        // If this is the only one pending we might
1444                        // have to bind to the service again.
1445                        if (!connectToService()) {
1446                            Slog.e(TAG, "Failed to bind to media container service");
1447                            params.serviceError();
1448                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                    System.identityHashCode(mHandler));
1450                            if (params.traceMethod != null) {
1451                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1452                                        params.traceCookie);
1453                            }
1454                            return;
1455                        } else {
1456                            // Once we bind to the service, the first
1457                            // pending request will be processed.
1458                            mPendingInstalls.add(idx, params);
1459                        }
1460                    } else {
1461                        mPendingInstalls.add(idx, params);
1462                        // Already bound to the service. Just make
1463                        // sure we trigger off processing the first request.
1464                        if (idx == 0) {
1465                            mHandler.sendEmptyMessage(MCS_BOUND);
1466                        }
1467                    }
1468                    break;
1469                }
1470                case MCS_BOUND: {
1471                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1472                    if (msg.obj != null) {
1473                        mContainerService = (IMediaContainerService) msg.obj;
1474                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                System.identityHashCode(mHandler));
1476                    }
1477                    if (mContainerService == null) {
1478                        if (!mBound) {
1479                            // Something seriously wrong since we are not bound and we are not
1480                            // waiting for connection. Bail out.
1481                            Slog.e(TAG, "Cannot bind to media container service");
1482                            for (HandlerParams params : mPendingInstalls) {
1483                                // Indicate service bind error
1484                                params.serviceError();
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486                                        System.identityHashCode(params));
1487                                if (params.traceMethod != null) {
1488                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1489                                            params.traceMethod, params.traceCookie);
1490                                }
1491                                return;
1492                            }
1493                            mPendingInstalls.clear();
1494                        } else {
1495                            Slog.w(TAG, "Waiting to connect to media container service");
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        HandlerParams params = mPendingInstalls.get(0);
1499                        if (params != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                    System.identityHashCode(params));
1502                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1503                            if (params.startCopy()) {
1504                                // We are done...  look for more work or to
1505                                // go idle.
1506                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1507                                        "Checking for more work or unbind...");
1508                                // Delete pending install
1509                                if (mPendingInstalls.size() > 0) {
1510                                    mPendingInstalls.remove(0);
1511                                }
1512                                if (mPendingInstalls.size() == 0) {
1513                                    if (mBound) {
1514                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                                "Posting delayed MCS_UNBIND");
1516                                        removeMessages(MCS_UNBIND);
1517                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1518                                        // Unbind after a little delay, to avoid
1519                                        // continual thrashing.
1520                                        sendMessageDelayed(ubmsg, 10000);
1521                                    }
1522                                } else {
1523                                    // There are more pending requests in queue.
1524                                    // Just post MCS_BOUND message to trigger processing
1525                                    // of next pending install.
1526                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                            "Posting MCS_BOUND for next work");
1528                                    mHandler.sendEmptyMessage(MCS_BOUND);
1529                                }
1530                            }
1531                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1532                        }
1533                    } else {
1534                        // Should never happen ideally.
1535                        Slog.w(TAG, "Empty queue");
1536                    }
1537                    break;
1538                }
1539                case MCS_RECONNECT: {
1540                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1541                    if (mPendingInstalls.size() > 0) {
1542                        if (mBound) {
1543                            disconnectService();
1544                        }
1545                        if (!connectToService()) {
1546                            Slog.e(TAG, "Failed to bind to media container service");
1547                            for (HandlerParams params : mPendingInstalls) {
1548                                // Indicate service bind error
1549                                params.serviceError();
1550                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1551                                        System.identityHashCode(params));
1552                            }
1553                            mPendingInstalls.clear();
1554                        }
1555                    }
1556                    break;
1557                }
1558                case MCS_UNBIND: {
1559                    // If there is no actual work left, then time to unbind.
1560                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1561
1562                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1563                        if (mBound) {
1564                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1565
1566                            disconnectService();
1567                        }
1568                    } else if (mPendingInstalls.size() > 0) {
1569                        // There are more pending requests in queue.
1570                        // Just post MCS_BOUND message to trigger processing
1571                        // of next pending install.
1572                        mHandler.sendEmptyMessage(MCS_BOUND);
1573                    }
1574
1575                    break;
1576                }
1577                case MCS_GIVE_UP: {
1578                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1579                    HandlerParams params = mPendingInstalls.remove(0);
1580                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1581                            System.identityHashCode(params));
1582                    break;
1583                }
1584                case SEND_PENDING_BROADCAST: {
1585                    String packages[];
1586                    ArrayList<String> components[];
1587                    int size = 0;
1588                    int uids[];
1589                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1590                    synchronized (mPackages) {
1591                        if (mPendingBroadcasts == null) {
1592                            return;
1593                        }
1594                        size = mPendingBroadcasts.size();
1595                        if (size <= 0) {
1596                            // Nothing to be done. Just return
1597                            return;
1598                        }
1599                        packages = new String[size];
1600                        components = new ArrayList[size];
1601                        uids = new int[size];
1602                        int i = 0;  // filling out the above arrays
1603
1604                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1605                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1606                            Iterator<Map.Entry<String, ArrayList<String>>> it
1607                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1608                                            .entrySet().iterator();
1609                            while (it.hasNext() && i < size) {
1610                                Map.Entry<String, ArrayList<String>> ent = it.next();
1611                                packages[i] = ent.getKey();
1612                                components[i] = ent.getValue();
1613                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1614                                uids[i] = (ps != null)
1615                                        ? UserHandle.getUid(packageUserId, ps.appId)
1616                                        : -1;
1617                                i++;
1618                            }
1619                        }
1620                        size = i;
1621                        mPendingBroadcasts.clear();
1622                    }
1623                    // Send broadcasts
1624                    for (int i = 0; i < size; i++) {
1625                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1626                    }
1627                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1628                    break;
1629                }
1630                case START_CLEANING_PACKAGE: {
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632                    final String packageName = (String)msg.obj;
1633                    final int userId = msg.arg1;
1634                    final boolean andCode = msg.arg2 != 0;
1635                    synchronized (mPackages) {
1636                        if (userId == UserHandle.USER_ALL) {
1637                            int[] users = sUserManager.getUserIds();
1638                            for (int user : users) {
1639                                mSettings.addPackageToCleanLPw(
1640                                        new PackageCleanItem(user, packageName, andCode));
1641                            }
1642                        } else {
1643                            mSettings.addPackageToCleanLPw(
1644                                    new PackageCleanItem(userId, packageName, andCode));
1645                        }
1646                    }
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                    startCleaningPackages();
1649                } break;
1650                case POST_INSTALL: {
1651                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1652
1653                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1654                    final boolean didRestore = (msg.arg2 != 0);
1655                    mRunningInstalls.delete(msg.arg1);
1656
1657                    if (data != null) {
1658                        InstallArgs args = data.args;
1659                        PackageInstalledInfo parentRes = data.res;
1660
1661                        final boolean grantPermissions = (args.installFlags
1662                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1663                        final boolean killApp = (args.installFlags
1664                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1665                        final boolean virtualPreload = ((args.installFlags
1666                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1667                        final String[] grantedPermissions = args.installGrantPermissions;
1668
1669                        // Handle the parent package
1670                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1671                                virtualPreload, grantedPermissions, didRestore,
1672                                args.installerPackageName, args.observer);
1673
1674                        // Handle the child packages
1675                        final int childCount = (parentRes.addedChildPackages != null)
1676                                ? parentRes.addedChildPackages.size() : 0;
1677                        for (int i = 0; i < childCount; i++) {
1678                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1679                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1680                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1681                                    args.installerPackageName, args.observer);
1682                        }
1683
1684                        // Log tracing if needed
1685                        if (args.traceMethod != null) {
1686                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1687                                    args.traceCookie);
1688                        }
1689                    } else {
1690                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1691                    }
1692
1693                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1694                } break;
1695                case WRITE_SETTINGS: {
1696                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1697                    synchronized (mPackages) {
1698                        removeMessages(WRITE_SETTINGS);
1699                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1700                        mSettings.writeLPr();
1701                        mDirtyUsers.clear();
1702                    }
1703                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1704                } break;
1705                case WRITE_PACKAGE_RESTRICTIONS: {
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1707                    synchronized (mPackages) {
1708                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1709                        for (int userId : mDirtyUsers) {
1710                            mSettings.writePackageRestrictionsLPr(userId);
1711                        }
1712                        mDirtyUsers.clear();
1713                    }
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1715                } break;
1716                case WRITE_PACKAGE_LIST: {
1717                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1718                    synchronized (mPackages) {
1719                        removeMessages(WRITE_PACKAGE_LIST);
1720                        mSettings.writePackageListLPr(msg.arg1);
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case CHECK_PENDING_VERIFICATION: {
1725                    final int verificationId = msg.arg1;
1726                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1727
1728                    if ((state != null) && !state.timeoutExtended()) {
1729                        final InstallArgs args = state.getInstallArgs();
1730                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1731
1732                        Slog.i(TAG, "Verification timed out for " + originUri);
1733                        mPendingVerification.remove(verificationId);
1734
1735                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1736
1737                        final UserHandle user = args.getUser();
1738                        if (getDefaultVerificationResponse(user)
1739                                == PackageManager.VERIFICATION_ALLOW) {
1740                            Slog.i(TAG, "Continuing with installation of " + originUri);
1741                            state.setVerifierResponse(Binder.getCallingUid(),
1742                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1743                            broadcastPackageVerified(verificationId, originUri,
1744                                    PackageManager.VERIFICATION_ALLOW, user);
1745                            try {
1746                                ret = args.copyApk(mContainerService, true);
1747                            } catch (RemoteException e) {
1748                                Slog.e(TAG, "Could not contact the ContainerService");
1749                            }
1750                        } else {
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_REJECT, user);
1753                        }
1754
1755                        Trace.asyncTraceEnd(
1756                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1757
1758                        processPendingInstall(args, ret);
1759                        mHandler.sendEmptyMessage(MCS_UNBIND);
1760                    }
1761                    break;
1762                }
1763                case PACKAGE_VERIFIED: {
1764                    final int verificationId = msg.arg1;
1765
1766                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1767                    if (state == null) {
1768                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1769                        break;
1770                    }
1771
1772                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1773
1774                    state.setVerifierResponse(response.callerUid, response.code);
1775
1776                    if (state.isVerificationComplete()) {
1777                        mPendingVerification.remove(verificationId);
1778
1779                        final InstallArgs args = state.getInstallArgs();
1780                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1781
1782                        int ret;
1783                        if (state.isInstallAllowed()) {
1784                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1785                            broadcastPackageVerified(verificationId, originUri,
1786                                    response.code, state.getInstallArgs().getUser());
1787                            try {
1788                                ret = args.copyApk(mContainerService, true);
1789                            } catch (RemoteException e) {
1790                                Slog.e(TAG, "Could not contact the ContainerService");
1791                            }
1792                        } else {
1793                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1794                        }
1795
1796                        Trace.asyncTraceEnd(
1797                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1798
1799                        processPendingInstall(args, ret);
1800                        mHandler.sendEmptyMessage(MCS_UNBIND);
1801                    }
1802
1803                    break;
1804                }
1805                case START_INTENT_FILTER_VERIFICATIONS: {
1806                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1807                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1808                            params.replacing, params.pkg);
1809                    break;
1810                }
1811                case INTENT_FILTER_VERIFIED: {
1812                    final int verificationId = msg.arg1;
1813
1814                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1815                            verificationId);
1816                    if (state == null) {
1817                        Slog.w(TAG, "Invalid IntentFilter verification token "
1818                                + verificationId + " received");
1819                        break;
1820                    }
1821
1822                    final int userId = state.getUserId();
1823
1824                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1825                            "Processing IntentFilter verification with token:"
1826                            + verificationId + " and userId:" + userId);
1827
1828                    final IntentFilterVerificationResponse response =
1829                            (IntentFilterVerificationResponse) msg.obj;
1830
1831                    state.setVerifierResponse(response.callerUid, response.code);
1832
1833                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1834                            "IntentFilter verification with token:" + verificationId
1835                            + " and userId:" + userId
1836                            + " is settings verifier response with response code:"
1837                            + response.code);
1838
1839                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1840                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1841                                + response.getFailedDomainsString());
1842                    }
1843
1844                    if (state.isVerificationComplete()) {
1845                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1846                    } else {
1847                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1848                                "IntentFilter verification with token:" + verificationId
1849                                + " was not said to be complete");
1850                    }
1851
1852                    break;
1853                }
1854                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1855                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1856                            mInstantAppResolverConnection,
1857                            (InstantAppRequest) msg.obj,
1858                            mInstantAppInstallerActivity,
1859                            mHandler);
1860                }
1861            }
1862        }
1863    }
1864
1865    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1866        @Override
1867        public void onGidsChanged(int appId, int userId) {
1868            mHandler.post(new Runnable() {
1869                @Override
1870                public void run() {
1871                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1872                }
1873            });
1874        }
1875        @Override
1876        public void onPermissionGranted(int uid, int userId) {
1877            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1878
1879            // Not critical; if this is lost, the application has to request again.
1880            synchronized (mPackages) {
1881                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1882            }
1883        }
1884        @Override
1885        public void onInstallPermissionGranted() {
1886            synchronized (mPackages) {
1887                scheduleWriteSettingsLocked();
1888            }
1889        }
1890        @Override
1891        public void onPermissionRevoked(int uid, int userId) {
1892            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1893
1894            synchronized (mPackages) {
1895                // Critical; after this call the application should never have the permission
1896                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1897            }
1898
1899            final int appId = UserHandle.getAppId(uid);
1900            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1901        }
1902        @Override
1903        public void onInstallPermissionRevoked() {
1904            synchronized (mPackages) {
1905                scheduleWriteSettingsLocked();
1906            }
1907        }
1908        @Override
1909        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1910            synchronized (mPackages) {
1911                for (int userId : updatedUserIds) {
1912                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1913                }
1914            }
1915        }
1916        @Override
1917        public void onInstallPermissionUpdated() {
1918            synchronized (mPackages) {
1919                scheduleWriteSettingsLocked();
1920            }
1921        }
1922        @Override
1923        public void onPermissionRemoved() {
1924            synchronized (mPackages) {
1925                mSettings.writeLPr();
1926            }
1927        }
1928    };
1929
1930    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1931            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1932            boolean launchedForRestore, String installerPackage,
1933            IPackageInstallObserver2 installObserver) {
1934        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1935            // Send the removed broadcasts
1936            if (res.removedInfo != null) {
1937                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1938            }
1939
1940            // Now that we successfully installed the package, grant runtime
1941            // permissions if requested before broadcasting the install. Also
1942            // for legacy apps in permission review mode we clear the permission
1943            // review flag which is used to emulate runtime permissions for
1944            // legacy apps.
1945            if (grantPermissions) {
1946                final int callingUid = Binder.getCallingUid();
1947                mPermissionManager.grantRequestedRuntimePermissions(
1948                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1949                        mPermissionCallback);
1950            }
1951
1952            final boolean update = res.removedInfo != null
1953                    && res.removedInfo.removedPackage != null;
1954            final String installerPackageName =
1955                    res.installerPackageName != null
1956                            ? res.installerPackageName
1957                            : res.removedInfo != null
1958                                    ? res.removedInfo.installerPackageName
1959                                    : null;
1960
1961            // If this is the first time we have child packages for a disabled privileged
1962            // app that had no children, we grant requested runtime permissions to the new
1963            // children if the parent on the system image had them already granted.
1964            if (res.pkg.parentPackage != null) {
1965                final int callingUid = Binder.getCallingUid();
1966                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1967                        res.pkg, callingUid, mPermissionCallback);
1968            }
1969
1970            synchronized (mPackages) {
1971                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1972            }
1973
1974            final String packageName = res.pkg.applicationInfo.packageName;
1975
1976            // Determine the set of users who are adding this package for
1977            // the first time vs. those who are seeing an update.
1978            int[] firstUserIds = EMPTY_INT_ARRAY;
1979            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1980            int[] updateUserIds = EMPTY_INT_ARRAY;
1981            int[] instantUserIds = EMPTY_INT_ARRAY;
1982            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1983            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1984            for (int newUser : res.newUsers) {
1985                final boolean isInstantApp = ps.getInstantApp(newUser);
1986                if (allNewUsers) {
1987                    if (isInstantApp) {
1988                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1989                    } else {
1990                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1991                    }
1992                    continue;
1993                }
1994                boolean isNew = true;
1995                for (int origUser : res.origUsers) {
1996                    if (origUser == newUser) {
1997                        isNew = false;
1998                        break;
1999                    }
2000                }
2001                if (isNew) {
2002                    if (isInstantApp) {
2003                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2004                    } else {
2005                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2006                    }
2007                } else {
2008                    if (isInstantApp) {
2009                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2010                    } else {
2011                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2012                    }
2013                }
2014            }
2015
2016            // Send installed broadcasts if the package is not a static shared lib.
2017            if (res.pkg.staticSharedLibName == null) {
2018                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2019
2020                // Send added for users that see the package for the first time
2021                // sendPackageAddedForNewUsers also deals with system apps
2022                int appId = UserHandle.getAppId(res.uid);
2023                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2024                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2025                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2026
2027                // Send added for users that don't see the package for the first time
2028                Bundle extras = new Bundle(1);
2029                extras.putInt(Intent.EXTRA_UID, res.uid);
2030                if (update) {
2031                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2032                }
2033                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2034                        extras, 0 /*flags*/,
2035                        null /*targetPackage*/, null /*finishedReceiver*/,
2036                        updateUserIds, instantUserIds);
2037                if (installerPackageName != null) {
2038                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2039                            extras, 0 /*flags*/,
2040                            installerPackageName, null /*finishedReceiver*/,
2041                            updateUserIds, instantUserIds);
2042                }
2043
2044                // Send replaced for users that don't see the package for the first time
2045                if (update) {
2046                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2047                            packageName, extras, 0 /*flags*/,
2048                            null /*targetPackage*/, null /*finishedReceiver*/,
2049                            updateUserIds, instantUserIds);
2050                    if (installerPackageName != null) {
2051                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2052                                extras, 0 /*flags*/,
2053                                installerPackageName, null /*finishedReceiver*/,
2054                                updateUserIds, instantUserIds);
2055                    }
2056                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2057                            null /*package*/, null /*extras*/, 0 /*flags*/,
2058                            packageName /*targetPackage*/,
2059                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2060                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2061                    // First-install and we did a restore, so we're responsible for the
2062                    // first-launch broadcast.
2063                    if (DEBUG_BACKUP) {
2064                        Slog.i(TAG, "Post-restore of " + packageName
2065                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2066                    }
2067                    sendFirstLaunchBroadcast(packageName, installerPackage,
2068                            firstUserIds, firstInstantUserIds);
2069                }
2070
2071                // Send broadcast package appeared if forward locked/external for all users
2072                // treat asec-hosted packages like removable media on upgrade
2073                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2074                    if (DEBUG_INSTALL) {
2075                        Slog.i(TAG, "upgrading pkg " + res.pkg
2076                                + " is ASEC-hosted -> AVAILABLE");
2077                    }
2078                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2079                    ArrayList<String> pkgList = new ArrayList<>(1);
2080                    pkgList.add(packageName);
2081                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2082                }
2083            }
2084
2085            // Work that needs to happen on first install within each user
2086            if (firstUserIds != null && firstUserIds.length > 0) {
2087                synchronized (mPackages) {
2088                    for (int userId : firstUserIds) {
2089                        // If this app is a browser and it's newly-installed for some
2090                        // users, clear any default-browser state in those users. The
2091                        // app's nature doesn't depend on the user, so we can just check
2092                        // its browser nature in any user and generalize.
2093                        if (packageIsBrowser(packageName, userId)) {
2094                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2095                        }
2096
2097                        // We may also need to apply pending (restored) runtime
2098                        // permission grants within these users.
2099                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2100                    }
2101                }
2102            }
2103
2104            if (allNewUsers && !update) {
2105                notifyPackageAdded(packageName);
2106            }
2107
2108            // Log current value of "unknown sources" setting
2109            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2110                    getUnknownSourcesSettings());
2111
2112            // Remove the replaced package's older resources safely now
2113            // We delete after a gc for applications  on sdcard.
2114            if (res.removedInfo != null && res.removedInfo.args != null) {
2115                Runtime.getRuntime().gc();
2116                synchronized (mInstallLock) {
2117                    res.removedInfo.args.doPostDeleteLI(true);
2118                }
2119            } else {
2120                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2121                // and not block here.
2122                VMRuntime.getRuntime().requestConcurrentGC();
2123            }
2124
2125            // Notify DexManager that the package was installed for new users.
2126            // The updated users should already be indexed and the package code paths
2127            // should not change.
2128            // Don't notify the manager for ephemeral apps as they are not expected to
2129            // survive long enough to benefit of background optimizations.
2130            for (int userId : firstUserIds) {
2131                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2132                // There's a race currently where some install events may interleave with an uninstall.
2133                // This can lead to package info being null (b/36642664).
2134                if (info != null) {
2135                    mDexManager.notifyPackageInstalled(info, userId);
2136                }
2137            }
2138        }
2139
2140        // If someone is watching installs - notify them
2141        if (installObserver != null) {
2142            try {
2143                Bundle extras = extrasForInstallResult(res);
2144                installObserver.onPackageInstalled(res.name, res.returnCode,
2145                        res.returnMsg, extras);
2146            } catch (RemoteException e) {
2147                Slog.i(TAG, "Observer no longer exists.");
2148            }
2149        }
2150    }
2151
2152    private StorageEventListener mStorageListener = new StorageEventListener() {
2153        @Override
2154        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2155            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2156                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2157                    final String volumeUuid = vol.getFsUuid();
2158
2159                    // Clean up any users or apps that were removed or recreated
2160                    // while this volume was missing
2161                    sUserManager.reconcileUsers(volumeUuid);
2162                    reconcileApps(volumeUuid);
2163
2164                    // Clean up any install sessions that expired or were
2165                    // cancelled while this volume was missing
2166                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2167
2168                    loadPrivatePackages(vol);
2169
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    unloadPrivatePackages(vol);
2172                }
2173            }
2174        }
2175
2176        @Override
2177        public void onVolumeForgotten(String fsUuid) {
2178            if (TextUtils.isEmpty(fsUuid)) {
2179                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2180                return;
2181            }
2182
2183            // Remove any apps installed on the forgotten volume
2184            synchronized (mPackages) {
2185                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2186                for (PackageSetting ps : packages) {
2187                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2188                    deletePackageVersioned(new VersionedPackage(ps.name,
2189                            PackageManager.VERSION_CODE_HIGHEST),
2190                            new LegacyPackageDeleteObserver(null).getBinder(),
2191                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2192                    // Try very hard to release any references to this package
2193                    // so we don't risk the system server being killed due to
2194                    // open FDs
2195                    AttributeCache.instance().removePackage(ps.name);
2196                }
2197
2198                mSettings.onVolumeForgotten(fsUuid);
2199                mSettings.writeLPr();
2200            }
2201        }
2202    };
2203
2204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2205        Bundle extras = null;
2206        switch (res.returnCode) {
2207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2208                extras = new Bundle();
2209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2210                        res.origPermission);
2211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2212                        res.origPackage);
2213                break;
2214            }
2215            case PackageManager.INSTALL_SUCCEEDED: {
2216                extras = new Bundle();
2217                extras.putBoolean(Intent.EXTRA_REPLACING,
2218                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2219                break;
2220            }
2221        }
2222        return extras;
2223    }
2224
2225    void scheduleWriteSettingsLocked() {
2226        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2227            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2228        }
2229    }
2230
2231    void scheduleWritePackageListLocked(int userId) {
2232        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2233            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2234            msg.arg1 = userId;
2235            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2240        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2241        scheduleWritePackageRestrictionsLocked(userId);
2242    }
2243
2244    void scheduleWritePackageRestrictionsLocked(int userId) {
2245        final int[] userIds = (userId == UserHandle.USER_ALL)
2246                ? sUserManager.getUserIds() : new int[]{userId};
2247        for (int nextUserId : userIds) {
2248            if (!sUserManager.exists(nextUserId)) return;
2249            mDirtyUsers.add(nextUserId);
2250            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2251                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2252            }
2253        }
2254    }
2255
2256    public static PackageManagerService main(Context context, Installer installer,
2257            boolean factoryTest, boolean onlyCore) {
2258        // Self-check for initial settings.
2259        PackageManagerServiceCompilerMapping.checkProperties();
2260
2261        PackageManagerService m = new PackageManagerService(context, installer,
2262                factoryTest, onlyCore);
2263        m.enableSystemUserPackages();
2264        ServiceManager.addService("package", m);
2265        final PackageManagerNative pmn = m.new PackageManagerNative();
2266        ServiceManager.addService("package_native", pmn);
2267        return m;
2268    }
2269
2270    private void enableSystemUserPackages() {
2271        if (!UserManager.isSplitSystemUser()) {
2272            return;
2273        }
2274        // For system user, enable apps based on the following conditions:
2275        // - app is whitelisted or belong to one of these groups:
2276        //   -- system app which has no launcher icons
2277        //   -- system app which has INTERACT_ACROSS_USERS permission
2278        //   -- system IME app
2279        // - app is not in the blacklist
2280        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2281        Set<String> enableApps = new ArraySet<>();
2282        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2283                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2284                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2285        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2286        enableApps.addAll(wlApps);
2287        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2288                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2289        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2290        enableApps.removeAll(blApps);
2291        Log.i(TAG, "Applications installed for system user: " + enableApps);
2292        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2293                UserHandle.SYSTEM);
2294        final int allAppsSize = allAps.size();
2295        synchronized (mPackages) {
2296            for (int i = 0; i < allAppsSize; i++) {
2297                String pName = allAps.get(i);
2298                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2299                // Should not happen, but we shouldn't be failing if it does
2300                if (pkgSetting == null) {
2301                    continue;
2302                }
2303                boolean install = enableApps.contains(pName);
2304                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2305                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2306                            + " for system user");
2307                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2308                }
2309            }
2310            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2311        }
2312    }
2313
2314    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2315        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2316                Context.DISPLAY_SERVICE);
2317        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2318    }
2319
2320    /**
2321     * Requests that files preopted on a secondary system partition be copied to the data partition
2322     * if possible.  Note that the actual copying of the files is accomplished by init for security
2323     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2324     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2325     */
2326    private static void requestCopyPreoptedFiles() {
2327        final int WAIT_TIME_MS = 100;
2328        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2329        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2330            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2331            // We will wait for up to 100 seconds.
2332            final long timeStart = SystemClock.uptimeMillis();
2333            final long timeEnd = timeStart + 100 * 1000;
2334            long timeNow = timeStart;
2335            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2336                try {
2337                    Thread.sleep(WAIT_TIME_MS);
2338                } catch (InterruptedException e) {
2339                    // Do nothing
2340                }
2341                timeNow = SystemClock.uptimeMillis();
2342                if (timeNow > timeEnd) {
2343                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2344                    Slog.wtf(TAG, "cppreopt did not finish!");
2345                    break;
2346                }
2347            }
2348
2349            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2350        }
2351    }
2352
2353    public PackageManagerService(Context context, Installer installer,
2354            boolean factoryTest, boolean onlyCore) {
2355        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2356        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2357        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2358                SystemClock.uptimeMillis());
2359
2360        if (mSdkVersion <= 0) {
2361            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2362        }
2363
2364        mContext = context;
2365
2366        mFactoryTest = factoryTest;
2367        mOnlyCore = onlyCore;
2368        mMetrics = new DisplayMetrics();
2369        mInstaller = installer;
2370
2371        // Create sub-components that provide services / data. Order here is important.
2372        synchronized (mInstallLock) {
2373        synchronized (mPackages) {
2374            // Expose private service for system components to use.
2375            LocalServices.addService(
2376                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2377            sUserManager = new UserManagerService(context, this,
2378                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2379            mPermissionManager = PermissionManagerService.create(context,
2380                    new DefaultPermissionGrantedCallback() {
2381                        @Override
2382                        public void onDefaultRuntimePermissionsGranted(int userId) {
2383                            synchronized(mPackages) {
2384                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2385                            }
2386                        }
2387                    }, mPackages /*externalLock*/);
2388            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2389            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2390        }
2391        }
2392        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2393                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2394        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404
2405        String separateProcesses = SystemProperties.get("debug.separate_processes");
2406        if (separateProcesses != null && separateProcesses.length() > 0) {
2407            if ("*".equals(separateProcesses)) {
2408                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2409                mSeparateProcesses = null;
2410                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2411            } else {
2412                mDefParseFlags = 0;
2413                mSeparateProcesses = separateProcesses.split(",");
2414                Slog.w(TAG, "Running with debug.separate_processes: "
2415                        + separateProcesses);
2416            }
2417        } else {
2418            mDefParseFlags = 0;
2419            mSeparateProcesses = null;
2420        }
2421
2422        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2423                "*dexopt*");
2424        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2425                installer, mInstallLock);
2426        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2427                dexManagerListener);
2428        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2429        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2430
2431        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2432                FgThread.get().getLooper());
2433
2434        getDefaultDisplayMetrics(context, mMetrics);
2435
2436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2437        SystemConfig systemConfig = SystemConfig.getInstance();
2438        mAvailableFeatures = systemConfig.getAvailableFeatures();
2439        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2440
2441        mProtectedPackages = new ProtectedPackages(mContext);
2442
2443        synchronized (mInstallLock) {
2444        // writer
2445        synchronized (mPackages) {
2446            mHandlerThread = new ServiceThread(TAG,
2447                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2448            mHandlerThread.start();
2449            mHandler = new PackageHandler(mHandlerThread.getLooper());
2450            mProcessLoggingHandler = new ProcessLoggingHandler();
2451            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2452            mInstantAppRegistry = new InstantAppRegistry(this);
2453
2454            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2455            final int builtInLibCount = libConfig.size();
2456            for (int i = 0; i < builtInLibCount; i++) {
2457                String name = libConfig.keyAt(i);
2458                String path = libConfig.valueAt(i);
2459                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2460                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2461            }
2462
2463            SELinuxMMAC.readInstallPolicy();
2464
2465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2466            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2467            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2468
2469            // Clean up orphaned packages for which the code path doesn't exist
2470            // and they are an update to a system app - caused by bug/32321269
2471            final int packageSettingCount = mSettings.mPackages.size();
2472            for (int i = packageSettingCount - 1; i >= 0; i--) {
2473                PackageSetting ps = mSettings.mPackages.valueAt(i);
2474                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2475                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2476                    mSettings.mPackages.removeAt(i);
2477                    mSettings.enableSystemPackageLPw(ps.name);
2478                }
2479            }
2480
2481            if (mFirstBoot) {
2482                requestCopyPreoptedFiles();
2483            }
2484
2485            String customResolverActivity = Resources.getSystem().getString(
2486                    R.string.config_customResolverActivity);
2487            if (TextUtils.isEmpty(customResolverActivity)) {
2488                customResolverActivity = null;
2489            } else {
2490                mCustomResolverComponentName = ComponentName.unflattenFromString(
2491                        customResolverActivity);
2492            }
2493
2494            long startTime = SystemClock.uptimeMillis();
2495
2496            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2497                    startTime);
2498
2499            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2500            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2501
2502            if (bootClassPath == null) {
2503                Slog.w(TAG, "No BOOTCLASSPATH found!");
2504            }
2505
2506            if (systemServerClassPath == null) {
2507                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2508            }
2509
2510            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2511
2512            final VersionInfo ver = mSettings.getInternalVersion();
2513            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2514            if (mIsUpgrade) {
2515                logCriticalInfo(Log.INFO,
2516                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2517            }
2518
2519            // when upgrading from pre-M, promote system app permissions from install to runtime
2520            mPromoteSystemApps =
2521                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2522
2523            // When upgrading from pre-N, we need to handle package extraction like first boot,
2524            // as there is no profiling data available.
2525            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2526
2527            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2528
2529            // save off the names of pre-existing system packages prior to scanning; we don't
2530            // want to automatically grant runtime permissions for new system apps
2531            if (mPromoteSystemApps) {
2532                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2533                while (pkgSettingIter.hasNext()) {
2534                    PackageSetting ps = pkgSettingIter.next();
2535                    if (isSystemApp(ps)) {
2536                        mExistingSystemPackages.add(ps.name);
2537                    }
2538                }
2539            }
2540
2541            mCacheDir = preparePackageParserCache(mIsUpgrade);
2542
2543            // Set flag to monitor and not change apk file paths when
2544            // scanning install directories.
2545            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2546
2547            if (mIsUpgrade || mFirstBoot) {
2548                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2549            }
2550
2551            // Collect vendor overlay packages. (Do this before scanning any apps.)
2552            // For security and version matching reason, only consider
2553            // overlay packages if they reside in the right directory.
2554            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2555                    mDefParseFlags
2556                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2557                    scanFlags
2558                    | SCAN_AS_SYSTEM
2559                    | SCAN_TRUSTED_OVERLAY,
2560                    0);
2561
2562            mParallelPackageParserCallback.findStaticOverlayPackages();
2563
2564            // Find base frameworks (resource packages without code).
2565            scanDirTracedLI(frameworkDir,
2566                    mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2568                    scanFlags
2569                    | SCAN_NO_DEX
2570                    | SCAN_AS_SYSTEM
2571                    | SCAN_AS_PRIVILEGED,
2572                    0);
2573
2574            // Collected privileged system packages.
2575            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2576            scanDirTracedLI(privilegedAppDir,
2577                    mDefParseFlags
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2579                    scanFlags
2580                    | SCAN_AS_SYSTEM
2581                    | SCAN_AS_PRIVILEGED,
2582                    0);
2583
2584            // Collect ordinary system packages.
2585            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2586            scanDirTracedLI(systemAppDir,
2587                    mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2589                    scanFlags
2590                    | SCAN_AS_SYSTEM,
2591                    0);
2592
2593            // Collected privileged vendor packages.
2594                File privilegedVendorAppDir = new File(Environment.getVendorDirectory(),
2595                        "priv-app");
2596            try {
2597                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2598            } catch (IOException e) {
2599                // failed to look up canonical path, continue with original one
2600            }
2601            scanDirTracedLI(privilegedVendorAppDir,
2602                    mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2604                    scanFlags
2605                    | SCAN_AS_SYSTEM
2606                    | SCAN_AS_VENDOR
2607                    | SCAN_AS_PRIVILEGED,
2608                    0);
2609
2610            // Collect ordinary vendor packages.
2611            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2612            try {
2613                vendorAppDir = vendorAppDir.getCanonicalFile();
2614            } catch (IOException e) {
2615                // failed to look up canonical path, continue with original one
2616            }
2617            scanDirTracedLI(vendorAppDir,
2618                    mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2620                    scanFlags
2621                    | SCAN_AS_SYSTEM
2622                    | SCAN_AS_VENDOR,
2623                    0);
2624
2625            // Collect all OEM packages.
2626            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2627            scanDirTracedLI(oemAppDir,
2628                    mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2630                    scanFlags
2631                    | SCAN_AS_SYSTEM
2632                    | SCAN_AS_OEM,
2633                    0);
2634
2635            // Prune any system packages that no longer exist.
2636            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2637            // Stub packages must either be replaced with full versions in the /data
2638            // partition or be disabled.
2639            final List<String> stubSystemApps = new ArrayList<>();
2640            if (!mOnlyCore) {
2641                // do this first before mucking with mPackages for the "expecting better" case
2642                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2643                while (pkgIterator.hasNext()) {
2644                    final PackageParser.Package pkg = pkgIterator.next();
2645                    if (pkg.isStub) {
2646                        stubSystemApps.add(pkg.packageName);
2647                    }
2648                }
2649
2650                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2651                while (psit.hasNext()) {
2652                    PackageSetting ps = psit.next();
2653
2654                    /*
2655                     * If this is not a system app, it can't be a
2656                     * disable system app.
2657                     */
2658                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2659                        continue;
2660                    }
2661
2662                    /*
2663                     * If the package is scanned, it's not erased.
2664                     */
2665                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2666                    if (scannedPkg != null) {
2667                        /*
2668                         * If the system app is both scanned and in the
2669                         * disabled packages list, then it must have been
2670                         * added via OTA. Remove it from the currently
2671                         * scanned package so the previously user-installed
2672                         * application can be scanned.
2673                         */
2674                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2675                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2676                                    + ps.name + "; removing system app.  Last known codePath="
2677                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2678                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2679                                    + scannedPkg.getLongVersionCode());
2680                            removePackageLI(scannedPkg, true);
2681                            mExpectingBetter.put(ps.name, ps.codePath);
2682                        }
2683
2684                        continue;
2685                    }
2686
2687                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2688                        psit.remove();
2689                        logCriticalInfo(Log.WARN, "System package " + ps.name
2690                                + " no longer exists; it's data will be wiped");
2691                        // Actual deletion of code and data will be handled by later
2692                        // reconciliation step
2693                    } else {
2694                        // we still have a disabled system package, but, it still might have
2695                        // been removed. check the code path still exists and check there's
2696                        // still a package. the latter can happen if an OTA keeps the same
2697                        // code path, but, changes the package name.
2698                        final PackageSetting disabledPs =
2699                                mSettings.getDisabledSystemPkgLPr(ps.name);
2700                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2701                                || disabledPs.pkg == null) {
2702if (REFACTOR_DEBUG) {
2703Slog.e("TODD",
2704        "Possibly deleted app: " + ps.dumpState_temp()
2705        + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath)
2706        + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString()));
2707}
2708                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2709                        }
2710                    }
2711                }
2712            }
2713
2714            //look for any incomplete package installations
2715            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2716            for (int i = 0; i < deletePkgsList.size(); i++) {
2717                // Actual deletion of code and data will be handled by later
2718                // reconciliation step
2719                final String packageName = deletePkgsList.get(i).name;
2720                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2721                synchronized (mPackages) {
2722                    mSettings.removePackageLPw(packageName);
2723                }
2724            }
2725
2726            //delete tmp files
2727            deleteTempPackageFiles();
2728
2729            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2730
2731            // Remove any shared userIDs that have no associated packages
2732            mSettings.pruneSharedUsersLPw();
2733            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2734            final int systemPackagesCount = mPackages.size();
2735            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2736                    + " ms, packageCount: " + systemPackagesCount
2737                    + " , timePerPackage: "
2738                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2739                    + " , cached: " + cachedSystemApps);
2740            if (mIsUpgrade && systemPackagesCount > 0) {
2741                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2742                        ((int) systemScanTime) / systemPackagesCount);
2743            }
2744            if (!mOnlyCore) {
2745                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2746                        SystemClock.uptimeMillis());
2747                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2748
2749                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2750                        | PackageParser.PARSE_FORWARD_LOCK,
2751                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2752
2753                // Remove disable package settings for updated system apps that were
2754                // removed via an OTA. If the update is no longer present, remove the
2755                // app completely. Otherwise, revoke their system privileges.
2756                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2757                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2758                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2759if (REFACTOR_DEBUG) {
2760Slog.e("TODD",
2761        "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null));
2762}
2763                    final String msg;
2764                    if (deletedPkg == null) {
2765                        // should have found an update, but, we didn't; remove everything
2766                        msg = "Updated system package " + deletedAppName
2767                                + " no longer exists; removing its data";
2768                        // Actual deletion of code and data will be handled by later
2769                        // reconciliation step
2770                    } else {
2771                        // found an update; revoke system privileges
2772                        msg = "Updated system package + " + deletedAppName
2773                                + " no longer exists; revoking system privileges";
2774
2775                        // Don't do anything if a stub is removed from the system image. If
2776                        // we were to remove the uncompressed version from the /data partition,
2777                        // this is where it'd be done.
2778
2779                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2780                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2781                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2782                    }
2783                    logCriticalInfo(Log.WARN, msg);
2784                }
2785
2786                /*
2787                 * Make sure all system apps that we expected to appear on
2788                 * the userdata partition actually showed up. If they never
2789                 * appeared, crawl back and revive the system version.
2790                 */
2791                for (int i = 0; i < mExpectingBetter.size(); i++) {
2792                    final String packageName = mExpectingBetter.keyAt(i);
2793                    if (!mPackages.containsKey(packageName)) {
2794                        final File scanFile = mExpectingBetter.valueAt(i);
2795
2796                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2797                                + " but never showed up; reverting to system");
2798
2799                        final @ParseFlags int reparseFlags;
2800                        final @ScanFlags int rescanFlags;
2801                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2802                            reparseFlags =
2803                                    mDefParseFlags |
2804                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2805                            rescanFlags =
2806                                    scanFlags
2807                                    | SCAN_AS_SYSTEM
2808                                    | SCAN_AS_PRIVILEGED;
2809                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2810                            reparseFlags =
2811                                    mDefParseFlags |
2812                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2813                            rescanFlags =
2814                                    scanFlags
2815                                    | SCAN_AS_SYSTEM;
2816                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2817                            reparseFlags =
2818                                    mDefParseFlags |
2819                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2820                            rescanFlags =
2821                                    scanFlags
2822                                    | SCAN_AS_SYSTEM
2823                                    | SCAN_AS_VENDOR
2824                                    | SCAN_AS_PRIVILEGED;
2825                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2826                            reparseFlags =
2827                                    mDefParseFlags |
2828                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2829                            rescanFlags =
2830                                    scanFlags
2831                                    | SCAN_AS_SYSTEM
2832                                    | SCAN_AS_VENDOR;
2833                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2834                            reparseFlags =
2835                                    mDefParseFlags |
2836                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2837                            rescanFlags =
2838                                    scanFlags
2839                                    | SCAN_AS_SYSTEM
2840                                    | SCAN_AS_OEM;
2841                        } else {
2842                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2843                            continue;
2844                        }
2845
2846                        mSettings.enableSystemPackageLPw(packageName);
2847
2848                        try {
2849                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2850                        } catch (PackageManagerException e) {
2851                            Slog.e(TAG, "Failed to parse original system package: "
2852                                    + e.getMessage());
2853                        }
2854                    }
2855                }
2856
2857                // Uncompress and install any stubbed system applications.
2858                // This must be done last to ensure all stubs are replaced or disabled.
2859                decompressSystemApplications(stubSystemApps, scanFlags);
2860
2861                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2862                                - cachedSystemApps;
2863
2864                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2865                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2866                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2867                        + " ms, packageCount: " + dataPackagesCount
2868                        + " , timePerPackage: "
2869                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2870                        + " , cached: " + cachedNonSystemApps);
2871                if (mIsUpgrade && dataPackagesCount > 0) {
2872                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2873                            ((int) dataScanTime) / dataPackagesCount);
2874                }
2875            }
2876            mExpectingBetter.clear();
2877
2878            // Resolve the storage manager.
2879            mStorageManagerPackage = getStorageManagerPackageName();
2880
2881            // Resolve protected action filters. Only the setup wizard is allowed to
2882            // have a high priority filter for these actions.
2883            mSetupWizardPackage = getSetupWizardPackageName();
2884            if (mProtectedFilters.size() > 0) {
2885                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2886                    Slog.i(TAG, "No setup wizard;"
2887                        + " All protected intents capped to priority 0");
2888                }
2889                for (ActivityIntentInfo filter : mProtectedFilters) {
2890                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2891                        if (DEBUG_FILTERS) {
2892                            Slog.i(TAG, "Found setup wizard;"
2893                                + " allow priority " + filter.getPriority() + ";"
2894                                + " package: " + filter.activity.info.packageName
2895                                + " activity: " + filter.activity.className
2896                                + " priority: " + filter.getPriority());
2897                        }
2898                        // skip setup wizard; allow it to keep the high priority filter
2899                        continue;
2900                    }
2901                    if (DEBUG_FILTERS) {
2902                        Slog.i(TAG, "Protected action; cap priority to 0;"
2903                                + " package: " + filter.activity.info.packageName
2904                                + " activity: " + filter.activity.className
2905                                + " origPrio: " + filter.getPriority());
2906                    }
2907                    filter.setPriority(0);
2908                }
2909            }
2910            mDeferProtectedFilters = false;
2911            mProtectedFilters.clear();
2912
2913            // Now that we know all of the shared libraries, update all clients to have
2914            // the correct library paths.
2915            updateAllSharedLibrariesLPw(null);
2916
2917            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2918                // NOTE: We ignore potential failures here during a system scan (like
2919                // the rest of the commands above) because there's precious little we
2920                // can do about it. A settings error is reported, though.
2921                final List<String> changedAbiCodePath =
2922                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2923                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2924                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2925                        final String codePathString = changedAbiCodePath.get(i);
2926                        try {
2927                            mInstaller.rmdex(codePathString,
2928                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2929                        } catch (InstallerException ignored) {
2930                        }
2931                    }
2932                }
2933            }
2934
2935            // Now that we know all the packages we are keeping,
2936            // read and update their last usage times.
2937            mPackageUsage.read(mPackages);
2938            mCompilerStats.read();
2939
2940            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2941                    SystemClock.uptimeMillis());
2942            Slog.i(TAG, "Time to scan packages: "
2943                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2944                    + " seconds");
2945
2946            // If the platform SDK has changed since the last time we booted,
2947            // we need to re-grant app permission to catch any new ones that
2948            // appear.  This is really a hack, and means that apps can in some
2949            // cases get permissions that the user didn't initially explicitly
2950            // allow...  it would be nice to have some better way to handle
2951            // this situation.
2952            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2953            if (sdkUpdated) {
2954                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2955                        + mSdkVersion + "; regranting permissions for internal storage");
2956            }
2957            mPermissionManager.updateAllPermissions(
2958                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2959                    mPermissionCallback);
2960            ver.sdkVersion = mSdkVersion;
2961
2962            // If this is the first boot or an update from pre-M, and it is a normal
2963            // boot, then we need to initialize the default preferred apps across
2964            // all defined users.
2965            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2966                for (UserInfo user : sUserManager.getUsers(true)) {
2967                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2968                    applyFactoryDefaultBrowserLPw(user.id);
2969                    primeDomainVerificationsLPw(user.id);
2970                }
2971            }
2972
2973            // Prepare storage for system user really early during boot,
2974            // since core system apps like SettingsProvider and SystemUI
2975            // can't wait for user to start
2976            final int storageFlags;
2977            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2978                storageFlags = StorageManager.FLAG_STORAGE_DE;
2979            } else {
2980                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2981            }
2982            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2983                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2984                    true /* onlyCoreApps */);
2985            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2986                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2987                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2988                traceLog.traceBegin("AppDataFixup");
2989                try {
2990                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2991                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2992                } catch (InstallerException e) {
2993                    Slog.w(TAG, "Trouble fixing GIDs", e);
2994                }
2995                traceLog.traceEnd();
2996
2997                traceLog.traceBegin("AppDataPrepare");
2998                if (deferPackages == null || deferPackages.isEmpty()) {
2999                    return;
3000                }
3001                int count = 0;
3002                for (String pkgName : deferPackages) {
3003                    PackageParser.Package pkg = null;
3004                    synchronized (mPackages) {
3005                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3006                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3007                            pkg = ps.pkg;
3008                        }
3009                    }
3010                    if (pkg != null) {
3011                        synchronized (mInstallLock) {
3012                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3013                                    true /* maybeMigrateAppData */);
3014                        }
3015                        count++;
3016                    }
3017                }
3018                traceLog.traceEnd();
3019                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3020            }, "prepareAppData");
3021
3022            // If this is first boot after an OTA, and a normal boot, then
3023            // we need to clear code cache directories.
3024            // Note that we do *not* clear the application profiles. These remain valid
3025            // across OTAs and are used to drive profile verification (post OTA) and
3026            // profile compilation (without waiting to collect a fresh set of profiles).
3027            if (mIsUpgrade && !onlyCore) {
3028                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3029                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3030                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3031                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3032                        // No apps are running this early, so no need to freeze
3033                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3034                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3035                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3036                    }
3037                }
3038                ver.fingerprint = Build.FINGERPRINT;
3039            }
3040
3041            checkDefaultBrowser();
3042
3043            // clear only after permissions and other defaults have been updated
3044            mExistingSystemPackages.clear();
3045            mPromoteSystemApps = false;
3046
3047            // All the changes are done during package scanning.
3048            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3049
3050            // can downgrade to reader
3051            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3052            mSettings.writeLPr();
3053            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3054            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3055                    SystemClock.uptimeMillis());
3056
3057            if (!mOnlyCore) {
3058                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3059                mRequiredInstallerPackage = getRequiredInstallerLPr();
3060                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3061                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3062                if (mIntentFilterVerifierComponent != null) {
3063                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3064                            mIntentFilterVerifierComponent);
3065                } else {
3066                    mIntentFilterVerifier = null;
3067                }
3068                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3069                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3070                        SharedLibraryInfo.VERSION_UNDEFINED);
3071                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3072                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3073                        SharedLibraryInfo.VERSION_UNDEFINED);
3074            } else {
3075                mRequiredVerifierPackage = null;
3076                mRequiredInstallerPackage = null;
3077                mRequiredUninstallerPackage = null;
3078                mIntentFilterVerifierComponent = null;
3079                mIntentFilterVerifier = null;
3080                mServicesSystemSharedLibraryPackageName = null;
3081                mSharedSystemSharedLibraryPackageName = null;
3082            }
3083
3084            mInstallerService = new PackageInstallerService(context, this);
3085            final Pair<ComponentName, String> instantAppResolverComponent =
3086                    getInstantAppResolverLPr();
3087            if (instantAppResolverComponent != null) {
3088                if (DEBUG_EPHEMERAL) {
3089                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3090                }
3091                mInstantAppResolverConnection = new EphemeralResolverConnection(
3092                        mContext, instantAppResolverComponent.first,
3093                        instantAppResolverComponent.second);
3094                mInstantAppResolverSettingsComponent =
3095                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3096            } else {
3097                mInstantAppResolverConnection = null;
3098                mInstantAppResolverSettingsComponent = null;
3099            }
3100            updateInstantAppInstallerLocked(null);
3101
3102            // Read and update the usage of dex files.
3103            // Do this at the end of PM init so that all the packages have their
3104            // data directory reconciled.
3105            // At this point we know the code paths of the packages, so we can validate
3106            // the disk file and build the internal cache.
3107            // The usage file is expected to be small so loading and verifying it
3108            // should take a fairly small time compare to the other activities (e.g. package
3109            // scanning).
3110            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3111            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3112            for (int userId : currentUserIds) {
3113                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3114            }
3115            mDexManager.load(userPackages);
3116            if (mIsUpgrade) {
3117                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3118                        (int) (SystemClock.uptimeMillis() - startTime));
3119            }
3120        } // synchronized (mPackages)
3121        } // synchronized (mInstallLock)
3122
3123        // Now after opening every single application zip, make sure they
3124        // are all flushed.  Not really needed, but keeps things nice and
3125        // tidy.
3126        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3127        Runtime.getRuntime().gc();
3128        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3129
3130        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3131        FallbackCategoryProvider.loadFallbacks();
3132        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3133
3134        // The initial scanning above does many calls into installd while
3135        // holding the mPackages lock, but we're mostly interested in yelling
3136        // once we have a booted system.
3137        mInstaller.setWarnIfHeld(mPackages);
3138
3139        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3140    }
3141
3142    /**
3143     * Uncompress and install stub applications.
3144     * <p>In order to save space on the system partition, some applications are shipped in a
3145     * compressed form. In addition the compressed bits for the full application, the
3146     * system image contains a tiny stub comprised of only the Android manifest.
3147     * <p>During the first boot, attempt to uncompress and install the full application. If
3148     * the application can't be installed for any reason, disable the stub and prevent
3149     * uncompressing the full application during future boots.
3150     * <p>In order to forcefully attempt an installation of a full application, go to app
3151     * settings and enable the application.
3152     */
3153    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3154        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3155            final String pkgName = stubSystemApps.get(i);
3156            // skip if the system package is already disabled
3157            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3158                stubSystemApps.remove(i);
3159                continue;
3160            }
3161            // skip if the package isn't installed (?!); this should never happen
3162            final PackageParser.Package pkg = mPackages.get(pkgName);
3163            if (pkg == null) {
3164                stubSystemApps.remove(i);
3165                continue;
3166            }
3167            // skip if the package has been disabled by the user
3168            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3169            if (ps != null) {
3170                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3171                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3172                    stubSystemApps.remove(i);
3173                    continue;
3174                }
3175            }
3176
3177            if (DEBUG_COMPRESSION) {
3178                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3179            }
3180
3181            // uncompress the binary to its eventual destination on /data
3182            final File scanFile = decompressPackage(pkg);
3183            if (scanFile == null) {
3184                continue;
3185            }
3186
3187            // install the package to replace the stub on /system
3188            try {
3189                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3190                removePackageLI(pkg, true /*chatty*/);
3191                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3192                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3193                        UserHandle.USER_SYSTEM, "android");
3194                stubSystemApps.remove(i);
3195                continue;
3196            } catch (PackageManagerException e) {
3197                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3198            }
3199
3200            // any failed attempt to install the package will be cleaned up later
3201        }
3202
3203        // disable any stub still left; these failed to install the full application
3204        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3205            final String pkgName = stubSystemApps.get(i);
3206            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3207            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3208                    UserHandle.USER_SYSTEM, "android");
3209            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3210        }
3211    }
3212
3213    /**
3214     * Decompresses the given package on the system image onto
3215     * the /data partition.
3216     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3217     */
3218    private File decompressPackage(PackageParser.Package pkg) {
3219        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3220        if (compressedFiles == null || compressedFiles.length == 0) {
3221            if (DEBUG_COMPRESSION) {
3222                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3223            }
3224            return null;
3225        }
3226        final File dstCodePath =
3227                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3228        int ret = PackageManager.INSTALL_SUCCEEDED;
3229        try {
3230            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3231            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3232            for (File srcFile : compressedFiles) {
3233                final String srcFileName = srcFile.getName();
3234                final String dstFileName = srcFileName.substring(
3235                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3236                final File dstFile = new File(dstCodePath, dstFileName);
3237                ret = decompressFile(srcFile, dstFile);
3238                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3239                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3240                            + "; pkg: " + pkg.packageName
3241                            + ", file: " + dstFileName);
3242                    break;
3243                }
3244            }
3245        } catch (ErrnoException e) {
3246            logCriticalInfo(Log.ERROR, "Failed to decompress"
3247                    + "; pkg: " + pkg.packageName
3248                    + ", err: " + e.errno);
3249        }
3250        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3251            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3252            NativeLibraryHelper.Handle handle = null;
3253            try {
3254                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3255                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3256                        null /*abiOverride*/);
3257            } catch (IOException e) {
3258                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3259                        + "; pkg: " + pkg.packageName);
3260                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3261            } finally {
3262                IoUtils.closeQuietly(handle);
3263            }
3264        }
3265        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3266            if (dstCodePath == null || !dstCodePath.exists()) {
3267                return null;
3268            }
3269            removeCodePathLI(dstCodePath);
3270            return null;
3271        }
3272
3273        return dstCodePath;
3274    }
3275
3276    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3277        // we're only interested in updating the installer appliction when 1) it's not
3278        // already set or 2) the modified package is the installer
3279        if (mInstantAppInstallerActivity != null
3280                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3281                        .equals(modifiedPackage)) {
3282            return;
3283        }
3284        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3285    }
3286
3287    private static File preparePackageParserCache(boolean isUpgrade) {
3288        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3289            return null;
3290        }
3291
3292        // Disable package parsing on eng builds to allow for faster incremental development.
3293        if (Build.IS_ENG) {
3294            return null;
3295        }
3296
3297        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3298            Slog.i(TAG, "Disabling package parser cache due to system property.");
3299            return null;
3300        }
3301
3302        // The base directory for the package parser cache lives under /data/system/.
3303        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3304                "package_cache");
3305        if (cacheBaseDir == null) {
3306            return null;
3307        }
3308
3309        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3310        // This also serves to "GC" unused entries when the package cache version changes (which
3311        // can only happen during upgrades).
3312        if (isUpgrade) {
3313            FileUtils.deleteContents(cacheBaseDir);
3314        }
3315
3316
3317        // Return the versioned package cache directory. This is something like
3318        // "/data/system/package_cache/1"
3319        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3320
3321        // The following is a workaround to aid development on non-numbered userdebug
3322        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3323        // the system partition is newer.
3324        //
3325        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3326        // that starts with "eng." to signify that this is an engineering build and not
3327        // destined for release.
3328        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3329            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3330
3331            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3332            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3333            // in general and should not be used for production changes. In this specific case,
3334            // we know that they will work.
3335            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3336            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3337                FileUtils.deleteContents(cacheBaseDir);
3338                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3339            }
3340        }
3341
3342        return cacheDir;
3343    }
3344
3345    @Override
3346    public boolean isFirstBoot() {
3347        // allow instant applications
3348        return mFirstBoot;
3349    }
3350
3351    @Override
3352    public boolean isOnlyCoreApps() {
3353        // allow instant applications
3354        return mOnlyCore;
3355    }
3356
3357    @Override
3358    public boolean isUpgrade() {
3359        // allow instant applications
3360        // The system property allows testing ota flow when upgraded to the same image.
3361        return mIsUpgrade || SystemProperties.getBoolean(
3362                "persist.pm.mock-upgrade", false /* default */);
3363    }
3364
3365    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3366        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3367
3368        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3369                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3370                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3371        if (matches.size() == 1) {
3372            return matches.get(0).getComponentInfo().packageName;
3373        } else if (matches.size() == 0) {
3374            Log.e(TAG, "There should probably be a verifier, but, none were found");
3375            return null;
3376        }
3377        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3378    }
3379
3380    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3381        synchronized (mPackages) {
3382            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3383            if (libraryEntry == null) {
3384                throw new IllegalStateException("Missing required shared library:" + name);
3385            }
3386            return libraryEntry.apk;
3387        }
3388    }
3389
3390    private @NonNull String getRequiredInstallerLPr() {
3391        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3392        intent.addCategory(Intent.CATEGORY_DEFAULT);
3393        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3394
3395        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3396                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3397                UserHandle.USER_SYSTEM);
3398        if (matches.size() == 1) {
3399            ResolveInfo resolveInfo = matches.get(0);
3400            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3401                throw new RuntimeException("The installer must be a privileged app");
3402            }
3403            return matches.get(0).getComponentInfo().packageName;
3404        } else {
3405            throw new RuntimeException("There must be exactly one installer; found " + matches);
3406        }
3407    }
3408
3409    private @NonNull String getRequiredUninstallerLPr() {
3410        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3411        intent.addCategory(Intent.CATEGORY_DEFAULT);
3412        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3413
3414        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3415                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3416                UserHandle.USER_SYSTEM);
3417        if (resolveInfo == null ||
3418                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3419            throw new RuntimeException("There must be exactly one uninstaller; found "
3420                    + resolveInfo);
3421        }
3422        return resolveInfo.getComponentInfo().packageName;
3423    }
3424
3425    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3426        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3427
3428        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3429                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3430                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3431        ResolveInfo best = null;
3432        final int N = matches.size();
3433        for (int i = 0; i < N; i++) {
3434            final ResolveInfo cur = matches.get(i);
3435            final String packageName = cur.getComponentInfo().packageName;
3436            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3437                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3438                continue;
3439            }
3440
3441            if (best == null || cur.priority > best.priority) {
3442                best = cur;
3443            }
3444        }
3445
3446        if (best != null) {
3447            return best.getComponentInfo().getComponentName();
3448        }
3449        Slog.w(TAG, "Intent filter verifier not found");
3450        return null;
3451    }
3452
3453    @Override
3454    public @Nullable ComponentName getInstantAppResolverComponent() {
3455        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3456            return null;
3457        }
3458        synchronized (mPackages) {
3459            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3460            if (instantAppResolver == null) {
3461                return null;
3462            }
3463            return instantAppResolver.first;
3464        }
3465    }
3466
3467    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3468        final String[] packageArray =
3469                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3470        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3471            if (DEBUG_EPHEMERAL) {
3472                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3473            }
3474            return null;
3475        }
3476
3477        final int callingUid = Binder.getCallingUid();
3478        final int resolveFlags =
3479                MATCH_DIRECT_BOOT_AWARE
3480                | MATCH_DIRECT_BOOT_UNAWARE
3481                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3482        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3483        final Intent resolverIntent = new Intent(actionName);
3484        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3485                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3486        // temporarily look for the old action
3487        if (resolvers.size() == 0) {
3488            if (DEBUG_EPHEMERAL) {
3489                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3490            }
3491            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3492            resolverIntent.setAction(actionName);
3493            resolvers = queryIntentServicesInternal(resolverIntent, null,
3494                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3495        }
3496        final int N = resolvers.size();
3497        if (N == 0) {
3498            if (DEBUG_EPHEMERAL) {
3499                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3500            }
3501            return null;
3502        }
3503
3504        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3505        for (int i = 0; i < N; i++) {
3506            final ResolveInfo info = resolvers.get(i);
3507
3508            if (info.serviceInfo == null) {
3509                continue;
3510            }
3511
3512            final String packageName = info.serviceInfo.packageName;
3513            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3514                if (DEBUG_EPHEMERAL) {
3515                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3516                            + " pkg: " + packageName + ", info:" + info);
3517                }
3518                continue;
3519            }
3520
3521            if (DEBUG_EPHEMERAL) {
3522                Slog.v(TAG, "Ephemeral resolver found;"
3523                        + " pkg: " + packageName + ", info:" + info);
3524            }
3525            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3526        }
3527        if (DEBUG_EPHEMERAL) {
3528            Slog.v(TAG, "Ephemeral resolver NOT found");
3529        }
3530        return null;
3531    }
3532
3533    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3534        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3535        intent.addCategory(Intent.CATEGORY_DEFAULT);
3536        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3537
3538        final int resolveFlags =
3539                MATCH_DIRECT_BOOT_AWARE
3540                | MATCH_DIRECT_BOOT_UNAWARE
3541                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3542        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3543                resolveFlags, UserHandle.USER_SYSTEM);
3544        // temporarily look for the old action
3545        if (matches.isEmpty()) {
3546            if (DEBUG_EPHEMERAL) {
3547                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3548            }
3549            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3550            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3551                    resolveFlags, UserHandle.USER_SYSTEM);
3552        }
3553        Iterator<ResolveInfo> iter = matches.iterator();
3554        while (iter.hasNext()) {
3555            final ResolveInfo rInfo = iter.next();
3556            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3557            if (ps != null) {
3558                final PermissionsState permissionsState = ps.getPermissionsState();
3559                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3560                    continue;
3561                }
3562            }
3563            iter.remove();
3564        }
3565        if (matches.size() == 0) {
3566            return null;
3567        } else if (matches.size() == 1) {
3568            return (ActivityInfo) matches.get(0).getComponentInfo();
3569        } else {
3570            throw new RuntimeException(
3571                    "There must be at most one ephemeral installer; found " + matches);
3572        }
3573    }
3574
3575    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3576            @NonNull ComponentName resolver) {
3577        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3578                .addCategory(Intent.CATEGORY_DEFAULT)
3579                .setPackage(resolver.getPackageName());
3580        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3581        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3582                UserHandle.USER_SYSTEM);
3583        // temporarily look for the old action
3584        if (matches.isEmpty()) {
3585            if (DEBUG_EPHEMERAL) {
3586                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3587            }
3588            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3589            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3590                    UserHandle.USER_SYSTEM);
3591        }
3592        if (matches.isEmpty()) {
3593            return null;
3594        }
3595        return matches.get(0).getComponentInfo().getComponentName();
3596    }
3597
3598    private void primeDomainVerificationsLPw(int userId) {
3599        if (DEBUG_DOMAIN_VERIFICATION) {
3600            Slog.d(TAG, "Priming domain verifications in user " + userId);
3601        }
3602
3603        SystemConfig systemConfig = SystemConfig.getInstance();
3604        ArraySet<String> packages = systemConfig.getLinkedApps();
3605
3606        for (String packageName : packages) {
3607            PackageParser.Package pkg = mPackages.get(packageName);
3608            if (pkg != null) {
3609                if (!pkg.isSystem()) {
3610                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3611                    continue;
3612                }
3613
3614                ArraySet<String> domains = null;
3615                for (PackageParser.Activity a : pkg.activities) {
3616                    for (ActivityIntentInfo filter : a.intents) {
3617                        if (hasValidDomains(filter)) {
3618                            if (domains == null) {
3619                                domains = new ArraySet<String>();
3620                            }
3621                            domains.addAll(filter.getHostsList());
3622                        }
3623                    }
3624                }
3625
3626                if (domains != null && domains.size() > 0) {
3627                    if (DEBUG_DOMAIN_VERIFICATION) {
3628                        Slog.v(TAG, "      + " + packageName);
3629                    }
3630                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3631                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3632                    // and then 'always' in the per-user state actually used for intent resolution.
3633                    final IntentFilterVerificationInfo ivi;
3634                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3635                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3636                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3637                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3638                } else {
3639                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3640                            + "' does not handle web links");
3641                }
3642            } else {
3643                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3644            }
3645        }
3646
3647        scheduleWritePackageRestrictionsLocked(userId);
3648        scheduleWriteSettingsLocked();
3649    }
3650
3651    private void applyFactoryDefaultBrowserLPw(int userId) {
3652        // The default browser app's package name is stored in a string resource,
3653        // with a product-specific overlay used for vendor customization.
3654        String browserPkg = mContext.getResources().getString(
3655                com.android.internal.R.string.default_browser);
3656        if (!TextUtils.isEmpty(browserPkg)) {
3657            // non-empty string => required to be a known package
3658            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3659            if (ps == null) {
3660                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3661                browserPkg = null;
3662            } else {
3663                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3664            }
3665        }
3666
3667        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3668        // default.  If there's more than one, just leave everything alone.
3669        if (browserPkg == null) {
3670            calculateDefaultBrowserLPw(userId);
3671        }
3672    }
3673
3674    private void calculateDefaultBrowserLPw(int userId) {
3675        List<String> allBrowsers = resolveAllBrowserApps(userId);
3676        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3677        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3678    }
3679
3680    private List<String> resolveAllBrowserApps(int userId) {
3681        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3682        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3683                PackageManager.MATCH_ALL, userId);
3684
3685        final int count = list.size();
3686        List<String> result = new ArrayList<String>(count);
3687        for (int i=0; i<count; i++) {
3688            ResolveInfo info = list.get(i);
3689            if (info.activityInfo == null
3690                    || !info.handleAllWebDataURI
3691                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3692                    || result.contains(info.activityInfo.packageName)) {
3693                continue;
3694            }
3695            result.add(info.activityInfo.packageName);
3696        }
3697
3698        return result;
3699    }
3700
3701    private boolean packageIsBrowser(String packageName, int userId) {
3702        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3703                PackageManager.MATCH_ALL, userId);
3704        final int N = list.size();
3705        for (int i = 0; i < N; i++) {
3706            ResolveInfo info = list.get(i);
3707            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3708                return true;
3709            }
3710        }
3711        return false;
3712    }
3713
3714    private void checkDefaultBrowser() {
3715        final int myUserId = UserHandle.myUserId();
3716        final String packageName = getDefaultBrowserPackageName(myUserId);
3717        if (packageName != null) {
3718            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3719            if (info == null) {
3720                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3721                synchronized (mPackages) {
3722                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3723                }
3724            }
3725        }
3726    }
3727
3728    @Override
3729    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3730            throws RemoteException {
3731        try {
3732            return super.onTransact(code, data, reply, flags);
3733        } catch (RuntimeException e) {
3734            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3735                Slog.wtf(TAG, "Package Manager Crash", e);
3736            }
3737            throw e;
3738        }
3739    }
3740
3741    static int[] appendInts(int[] cur, int[] add) {
3742        if (add == null) return cur;
3743        if (cur == null) return add;
3744        final int N = add.length;
3745        for (int i=0; i<N; i++) {
3746            cur = appendInt(cur, add[i]);
3747        }
3748        return cur;
3749    }
3750
3751    /**
3752     * Returns whether or not a full application can see an instant application.
3753     * <p>
3754     * Currently, there are three cases in which this can occur:
3755     * <ol>
3756     * <li>The calling application is a "special" process. Special processes
3757     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3758     * <li>The calling application has the permission
3759     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3760     * <li>The calling application is the default launcher on the
3761     *     system partition.</li>
3762     * </ol>
3763     */
3764    private boolean canViewInstantApps(int callingUid, int userId) {
3765        if (callingUid < Process.FIRST_APPLICATION_UID) {
3766            return true;
3767        }
3768        if (mContext.checkCallingOrSelfPermission(
3769                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3770            return true;
3771        }
3772        if (mContext.checkCallingOrSelfPermission(
3773                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3774            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3775            if (homeComponent != null
3776                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3777                return true;
3778            }
3779        }
3780        return false;
3781    }
3782
3783    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3784        if (!sUserManager.exists(userId)) return null;
3785        if (ps == null) {
3786            return null;
3787        }
3788        PackageParser.Package p = ps.pkg;
3789        if (p == null) {
3790            return null;
3791        }
3792        final int callingUid = Binder.getCallingUid();
3793        // Filter out ephemeral app metadata:
3794        //   * The system/shell/root can see metadata for any app
3795        //   * An installed app can see metadata for 1) other installed apps
3796        //     and 2) ephemeral apps that have explicitly interacted with it
3797        //   * Ephemeral apps can only see their own data and exposed installed apps
3798        //   * Holding a signature permission allows seeing instant apps
3799        if (filterAppAccessLPr(ps, callingUid, userId)) {
3800            return null;
3801        }
3802
3803        final PermissionsState permissionsState = ps.getPermissionsState();
3804
3805        // Compute GIDs only if requested
3806        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3807                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3808        // Compute granted permissions only if package has requested permissions
3809        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3810                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3811        final PackageUserState state = ps.readUserState(userId);
3812
3813        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3814                && ps.isSystem()) {
3815            flags |= MATCH_ANY_USER;
3816        }
3817
3818        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3819                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3820
3821        if (packageInfo == null) {
3822            return null;
3823        }
3824
3825        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3826                resolveExternalPackageNameLPr(p);
3827
3828        return packageInfo;
3829    }
3830
3831    @Override
3832    public void checkPackageStartable(String packageName, int userId) {
3833        final int callingUid = Binder.getCallingUid();
3834        if (getInstantAppPackageName(callingUid) != null) {
3835            throw new SecurityException("Instant applications don't have access to this method");
3836        }
3837        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3838        synchronized (mPackages) {
3839            final PackageSetting ps = mSettings.mPackages.get(packageName);
3840            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3841                throw new SecurityException("Package " + packageName + " was not found!");
3842            }
3843
3844            if (!ps.getInstalled(userId)) {
3845                throw new SecurityException(
3846                        "Package " + packageName + " was not installed for user " + userId + "!");
3847            }
3848
3849            if (mSafeMode && !ps.isSystem()) {
3850                throw new SecurityException("Package " + packageName + " not a system app!");
3851            }
3852
3853            if (mFrozenPackages.contains(packageName)) {
3854                throw new SecurityException("Package " + packageName + " is currently frozen!");
3855            }
3856
3857            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3858                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3859            }
3860        }
3861    }
3862
3863    @Override
3864    public boolean isPackageAvailable(String packageName, int userId) {
3865        if (!sUserManager.exists(userId)) return false;
3866        final int callingUid = Binder.getCallingUid();
3867        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3868                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3869        synchronized (mPackages) {
3870            PackageParser.Package p = mPackages.get(packageName);
3871            if (p != null) {
3872                final PackageSetting ps = (PackageSetting) p.mExtras;
3873                if (filterAppAccessLPr(ps, callingUid, userId)) {
3874                    return false;
3875                }
3876                if (ps != null) {
3877                    final PackageUserState state = ps.readUserState(userId);
3878                    if (state != null) {
3879                        return PackageParser.isAvailable(state);
3880                    }
3881                }
3882            }
3883        }
3884        return false;
3885    }
3886
3887    @Override
3888    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3889        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3890                flags, Binder.getCallingUid(), userId);
3891    }
3892
3893    @Override
3894    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3895            int flags, int userId) {
3896        return getPackageInfoInternal(versionedPackage.getPackageName(),
3897                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3898    }
3899
3900    /**
3901     * Important: The provided filterCallingUid is used exclusively to filter out packages
3902     * that can be seen based on user state. It's typically the original caller uid prior
3903     * to clearing. Because it can only be provided by trusted code, it's value can be
3904     * trusted and will be used as-is; unlike userId which will be validated by this method.
3905     */
3906    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3907            int flags, int filterCallingUid, int userId) {
3908        if (!sUserManager.exists(userId)) return null;
3909        flags = updateFlagsForPackage(flags, userId, packageName);
3910        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3911                false /* requireFullPermission */, false /* checkShell */, "get package info");
3912
3913        // reader
3914        synchronized (mPackages) {
3915            // Normalize package name to handle renamed packages and static libs
3916            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3917
3918            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3919            if (matchFactoryOnly) {
3920                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3921                if (ps != null) {
3922                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3923                        return null;
3924                    }
3925                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3926                        return null;
3927                    }
3928                    return generatePackageInfo(ps, flags, userId);
3929                }
3930            }
3931
3932            PackageParser.Package p = mPackages.get(packageName);
3933            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3934                return null;
3935            }
3936            if (DEBUG_PACKAGE_INFO)
3937                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3938            if (p != null) {
3939                final PackageSetting ps = (PackageSetting) p.mExtras;
3940                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3941                    return null;
3942                }
3943                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3944                    return null;
3945                }
3946                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3947            }
3948            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3949                final PackageSetting ps = mSettings.mPackages.get(packageName);
3950                if (ps == null) return null;
3951                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3952                    return null;
3953                }
3954                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3955                    return null;
3956                }
3957                return generatePackageInfo(ps, flags, userId);
3958            }
3959        }
3960        return null;
3961    }
3962
3963    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3964        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3965            return true;
3966        }
3967        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3968            return true;
3969        }
3970        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3971            return true;
3972        }
3973        return false;
3974    }
3975
3976    private boolean isComponentVisibleToInstantApp(
3977            @Nullable ComponentName component, @ComponentType int type) {
3978        if (type == TYPE_ACTIVITY) {
3979            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3980            return activity != null
3981                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3982                    : false;
3983        } else if (type == TYPE_RECEIVER) {
3984            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3985            return activity != null
3986                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3987                    : false;
3988        } else if (type == TYPE_SERVICE) {
3989            final PackageParser.Service service = mServices.mServices.get(component);
3990            return service != null
3991                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3992                    : false;
3993        } else if (type == TYPE_PROVIDER) {
3994            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3995            return provider != null
3996                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3997                    : false;
3998        } else if (type == TYPE_UNKNOWN) {
3999            return isComponentVisibleToInstantApp(component);
4000        }
4001        return false;
4002    }
4003
4004    /**
4005     * Returns whether or not access to the application should be filtered.
4006     * <p>
4007     * Access may be limited based upon whether the calling or target applications
4008     * are instant applications.
4009     *
4010     * @see #canAccessInstantApps(int)
4011     */
4012    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4013            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4014        // if we're in an isolated process, get the real calling UID
4015        if (Process.isIsolated(callingUid)) {
4016            callingUid = mIsolatedOwners.get(callingUid);
4017        }
4018        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4019        final boolean callerIsInstantApp = instantAppPkgName != null;
4020        if (ps == null) {
4021            if (callerIsInstantApp) {
4022                // pretend the application exists, but, needs to be filtered
4023                return true;
4024            }
4025            return false;
4026        }
4027        // if the target and caller are the same application, don't filter
4028        if (isCallerSameApp(ps.name, callingUid)) {
4029            return false;
4030        }
4031        if (callerIsInstantApp) {
4032            // request for a specific component; if it hasn't been explicitly exposed, filter
4033            if (component != null) {
4034                return !isComponentVisibleToInstantApp(component, componentType);
4035            }
4036            // request for application; if no components have been explicitly exposed, filter
4037            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4038        }
4039        if (ps.getInstantApp(userId)) {
4040            // caller can see all components of all instant applications, don't filter
4041            if (canViewInstantApps(callingUid, userId)) {
4042                return false;
4043            }
4044            // request for a specific instant application component, filter
4045            if (component != null) {
4046                return true;
4047            }
4048            // request for an instant application; if the caller hasn't been granted access, filter
4049            return !mInstantAppRegistry.isInstantAccessGranted(
4050                    userId, UserHandle.getAppId(callingUid), ps.appId);
4051        }
4052        return false;
4053    }
4054
4055    /**
4056     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4057     */
4058    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4059        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4060    }
4061
4062    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4063            int flags) {
4064        // Callers can access only the libs they depend on, otherwise they need to explicitly
4065        // ask for the shared libraries given the caller is allowed to access all static libs.
4066        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4067            // System/shell/root get to see all static libs
4068            final int appId = UserHandle.getAppId(uid);
4069            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4070                    || appId == Process.ROOT_UID) {
4071                return false;
4072            }
4073        }
4074
4075        // No package means no static lib as it is always on internal storage
4076        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4077            return false;
4078        }
4079
4080        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4081                ps.pkg.staticSharedLibVersion);
4082        if (libEntry == null) {
4083            return false;
4084        }
4085
4086        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4087        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4088        if (uidPackageNames == null) {
4089            return true;
4090        }
4091
4092        for (String uidPackageName : uidPackageNames) {
4093            if (ps.name.equals(uidPackageName)) {
4094                return false;
4095            }
4096            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4097            if (uidPs != null) {
4098                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4099                        libEntry.info.getName());
4100                if (index < 0) {
4101                    continue;
4102                }
4103                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4104                    return false;
4105                }
4106            }
4107        }
4108        return true;
4109    }
4110
4111    @Override
4112    public String[] currentToCanonicalPackageNames(String[] names) {
4113        final int callingUid = Binder.getCallingUid();
4114        if (getInstantAppPackageName(callingUid) != null) {
4115            return names;
4116        }
4117        final String[] out = new String[names.length];
4118        // reader
4119        synchronized (mPackages) {
4120            final int callingUserId = UserHandle.getUserId(callingUid);
4121            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4122            for (int i=names.length-1; i>=0; i--) {
4123                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4124                boolean translateName = false;
4125                if (ps != null && ps.realName != null) {
4126                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4127                    translateName = !targetIsInstantApp
4128                            || canViewInstantApps
4129                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4130                                    UserHandle.getAppId(callingUid), ps.appId);
4131                }
4132                out[i] = translateName ? ps.realName : names[i];
4133            }
4134        }
4135        return out;
4136    }
4137
4138    @Override
4139    public String[] canonicalToCurrentPackageNames(String[] names) {
4140        final int callingUid = Binder.getCallingUid();
4141        if (getInstantAppPackageName(callingUid) != null) {
4142            return names;
4143        }
4144        final String[] out = new String[names.length];
4145        // reader
4146        synchronized (mPackages) {
4147            final int callingUserId = UserHandle.getUserId(callingUid);
4148            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4149            for (int i=names.length-1; i>=0; i--) {
4150                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4151                boolean translateName = false;
4152                if (cur != null) {
4153                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4154                    final boolean targetIsInstantApp =
4155                            ps != null && ps.getInstantApp(callingUserId);
4156                    translateName = !targetIsInstantApp
4157                            || canViewInstantApps
4158                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4159                                    UserHandle.getAppId(callingUid), ps.appId);
4160                }
4161                out[i] = translateName ? cur : names[i];
4162            }
4163        }
4164        return out;
4165    }
4166
4167    @Override
4168    public int getPackageUid(String packageName, int flags, int userId) {
4169        if (!sUserManager.exists(userId)) return -1;
4170        final int callingUid = Binder.getCallingUid();
4171        flags = updateFlagsForPackage(flags, userId, packageName);
4172        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4173                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4174
4175        // reader
4176        synchronized (mPackages) {
4177            final PackageParser.Package p = mPackages.get(packageName);
4178            if (p != null && p.isMatch(flags)) {
4179                PackageSetting ps = (PackageSetting) p.mExtras;
4180                if (filterAppAccessLPr(ps, callingUid, userId)) {
4181                    return -1;
4182                }
4183                return UserHandle.getUid(userId, p.applicationInfo.uid);
4184            }
4185            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4186                final PackageSetting ps = mSettings.mPackages.get(packageName);
4187                if (ps != null && ps.isMatch(flags)
4188                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4189                    return UserHandle.getUid(userId, ps.appId);
4190                }
4191            }
4192        }
4193
4194        return -1;
4195    }
4196
4197    @Override
4198    public int[] getPackageGids(String packageName, int flags, int userId) {
4199        if (!sUserManager.exists(userId)) return null;
4200        final int callingUid = Binder.getCallingUid();
4201        flags = updateFlagsForPackage(flags, userId, packageName);
4202        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4203                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4204
4205        // reader
4206        synchronized (mPackages) {
4207            final PackageParser.Package p = mPackages.get(packageName);
4208            if (p != null && p.isMatch(flags)) {
4209                PackageSetting ps = (PackageSetting) p.mExtras;
4210                if (filterAppAccessLPr(ps, callingUid, userId)) {
4211                    return null;
4212                }
4213                // TODO: Shouldn't this be checking for package installed state for userId and
4214                // return null?
4215                return ps.getPermissionsState().computeGids(userId);
4216            }
4217            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4218                final PackageSetting ps = mSettings.mPackages.get(packageName);
4219                if (ps != null && ps.isMatch(flags)
4220                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4221                    return ps.getPermissionsState().computeGids(userId);
4222                }
4223            }
4224        }
4225
4226        return null;
4227    }
4228
4229    @Override
4230    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4231        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4232    }
4233
4234    @Override
4235    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4236            int flags) {
4237        final List<PermissionInfo> permissionList =
4238                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4239        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4240    }
4241
4242    @Override
4243    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4244        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4245    }
4246
4247    @Override
4248    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4249        final List<PermissionGroupInfo> permissionList =
4250                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4251        return (permissionList == null)
4252                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4253    }
4254
4255    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4256            int filterCallingUid, int userId) {
4257        if (!sUserManager.exists(userId)) return null;
4258        PackageSetting ps = mSettings.mPackages.get(packageName);
4259        if (ps != null) {
4260            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4261                return null;
4262            }
4263            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4264                return null;
4265            }
4266            if (ps.pkg == null) {
4267                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4268                if (pInfo != null) {
4269                    return pInfo.applicationInfo;
4270                }
4271                return null;
4272            }
4273            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4274                    ps.readUserState(userId), userId);
4275            if (ai != null) {
4276                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4277            }
4278            return ai;
4279        }
4280        return null;
4281    }
4282
4283    @Override
4284    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4285        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4286    }
4287
4288    /**
4289     * Important: The provided filterCallingUid is used exclusively to filter out applications
4290     * that can be seen based on user state. It's typically the original caller uid prior
4291     * to clearing. Because it can only be provided by trusted code, it's value can be
4292     * trusted and will be used as-is; unlike userId which will be validated by this method.
4293     */
4294    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4295            int filterCallingUid, int userId) {
4296        if (!sUserManager.exists(userId)) return null;
4297        flags = updateFlagsForApplication(flags, userId, packageName);
4298        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4299                false /* requireFullPermission */, false /* checkShell */, "get application info");
4300
4301        // writer
4302        synchronized (mPackages) {
4303            // Normalize package name to handle renamed packages and static libs
4304            packageName = resolveInternalPackageNameLPr(packageName,
4305                    PackageManager.VERSION_CODE_HIGHEST);
4306
4307            PackageParser.Package p = mPackages.get(packageName);
4308            if (DEBUG_PACKAGE_INFO) Log.v(
4309                    TAG, "getApplicationInfo " + packageName
4310                    + ": " + p);
4311            if (p != null) {
4312                PackageSetting ps = mSettings.mPackages.get(packageName);
4313                if (ps == null) return null;
4314                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4315                    return null;
4316                }
4317                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4318                    return null;
4319                }
4320                // Note: isEnabledLP() does not apply here - always return info
4321                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4322                        p, flags, ps.readUserState(userId), userId);
4323                if (ai != null) {
4324                    ai.packageName = resolveExternalPackageNameLPr(p);
4325                }
4326                return ai;
4327            }
4328            if ("android".equals(packageName)||"system".equals(packageName)) {
4329                return mAndroidApplication;
4330            }
4331            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4332                // Already generates the external package name
4333                return generateApplicationInfoFromSettingsLPw(packageName,
4334                        flags, filterCallingUid, userId);
4335            }
4336        }
4337        return null;
4338    }
4339
4340    private String normalizePackageNameLPr(String packageName) {
4341        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4342        return normalizedPackageName != null ? normalizedPackageName : packageName;
4343    }
4344
4345    @Override
4346    public void deletePreloadsFileCache() {
4347        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4348            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4349        }
4350        File dir = Environment.getDataPreloadsFileCacheDirectory();
4351        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4352        FileUtils.deleteContents(dir);
4353    }
4354
4355    @Override
4356    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4357            final int storageFlags, final IPackageDataObserver observer) {
4358        mContext.enforceCallingOrSelfPermission(
4359                android.Manifest.permission.CLEAR_APP_CACHE, null);
4360        mHandler.post(() -> {
4361            boolean success = false;
4362            try {
4363                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4364                success = true;
4365            } catch (IOException e) {
4366                Slog.w(TAG, e);
4367            }
4368            if (observer != null) {
4369                try {
4370                    observer.onRemoveCompleted(null, success);
4371                } catch (RemoteException e) {
4372                    Slog.w(TAG, e);
4373                }
4374            }
4375        });
4376    }
4377
4378    @Override
4379    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4380            final int storageFlags, final IntentSender pi) {
4381        mContext.enforceCallingOrSelfPermission(
4382                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4383        mHandler.post(() -> {
4384            boolean success = false;
4385            try {
4386                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4387                success = true;
4388            } catch (IOException e) {
4389                Slog.w(TAG, e);
4390            }
4391            if (pi != null) {
4392                try {
4393                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4394                } catch (SendIntentException e) {
4395                    Slog.w(TAG, e);
4396                }
4397            }
4398        });
4399    }
4400
4401    /**
4402     * Blocking call to clear various types of cached data across the system
4403     * until the requested bytes are available.
4404     */
4405    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4406        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4407        final File file = storage.findPathForUuid(volumeUuid);
4408        if (file.getUsableSpace() >= bytes) return;
4409
4410        if (ENABLE_FREE_CACHE_V2) {
4411            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4412                    volumeUuid);
4413            final boolean aggressive = (storageFlags
4414                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4415            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4416
4417            // 1. Pre-flight to determine if we have any chance to succeed
4418            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4419            if (internalVolume && (aggressive || SystemProperties
4420                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4421                deletePreloadsFileCache();
4422                if (file.getUsableSpace() >= bytes) return;
4423            }
4424
4425            // 3. Consider parsed APK data (aggressive only)
4426            if (internalVolume && aggressive) {
4427                FileUtils.deleteContents(mCacheDir);
4428                if (file.getUsableSpace() >= bytes) return;
4429            }
4430
4431            // 4. Consider cached app data (above quotas)
4432            try {
4433                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4434                        Installer.FLAG_FREE_CACHE_V2);
4435            } catch (InstallerException ignored) {
4436            }
4437            if (file.getUsableSpace() >= bytes) return;
4438
4439            // 5. Consider shared libraries with refcount=0 and age>min cache period
4440            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4441                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4442                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4443                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4444                return;
4445            }
4446
4447            // 6. Consider dexopt output (aggressive only)
4448            // TODO: Implement
4449
4450            // 7. Consider installed instant apps unused longer than min cache period
4451            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4452                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4453                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4454                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4455                return;
4456            }
4457
4458            // 8. Consider cached app data (below quotas)
4459            try {
4460                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4461                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4462            } catch (InstallerException ignored) {
4463            }
4464            if (file.getUsableSpace() >= bytes) return;
4465
4466            // 9. Consider DropBox entries
4467            // TODO: Implement
4468
4469            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4470            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4471                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4472                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4473                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4474                return;
4475            }
4476        } else {
4477            try {
4478                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4479            } catch (InstallerException ignored) {
4480            }
4481            if (file.getUsableSpace() >= bytes) return;
4482        }
4483
4484        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4485    }
4486
4487    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4488            throws IOException {
4489        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4490        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4491
4492        List<VersionedPackage> packagesToDelete = null;
4493        final long now = System.currentTimeMillis();
4494
4495        synchronized (mPackages) {
4496            final int[] allUsers = sUserManager.getUserIds();
4497            final int libCount = mSharedLibraries.size();
4498            for (int i = 0; i < libCount; i++) {
4499                final LongSparseArray<SharedLibraryEntry> versionedLib
4500                        = mSharedLibraries.valueAt(i);
4501                if (versionedLib == null) {
4502                    continue;
4503                }
4504                final int versionCount = versionedLib.size();
4505                for (int j = 0; j < versionCount; j++) {
4506                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4507                    // Skip packages that are not static shared libs.
4508                    if (!libInfo.isStatic()) {
4509                        break;
4510                    }
4511                    // Important: We skip static shared libs used for some user since
4512                    // in such a case we need to keep the APK on the device. The check for
4513                    // a lib being used for any user is performed by the uninstall call.
4514                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4515                    // Resolve the package name - we use synthetic package names internally
4516                    final String internalPackageName = resolveInternalPackageNameLPr(
4517                            declaringPackage.getPackageName(),
4518                            declaringPackage.getLongVersionCode());
4519                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4520                    // Skip unused static shared libs cached less than the min period
4521                    // to prevent pruning a lib needed by a subsequently installed package.
4522                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4523                        continue;
4524                    }
4525                    if (packagesToDelete == null) {
4526                        packagesToDelete = new ArrayList<>();
4527                    }
4528                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4529                            declaringPackage.getLongVersionCode()));
4530                }
4531            }
4532        }
4533
4534        if (packagesToDelete != null) {
4535            final int packageCount = packagesToDelete.size();
4536            for (int i = 0; i < packageCount; i++) {
4537                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4538                // Delete the package synchronously (will fail of the lib used for any user).
4539                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4540                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4541                                == PackageManager.DELETE_SUCCEEDED) {
4542                    if (volume.getUsableSpace() >= neededSpace) {
4543                        return true;
4544                    }
4545                }
4546            }
4547        }
4548
4549        return false;
4550    }
4551
4552    /**
4553     * Update given flags based on encryption status of current user.
4554     */
4555    private int updateFlags(int flags, int userId) {
4556        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4557                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4558            // Caller expressed an explicit opinion about what encryption
4559            // aware/unaware components they want to see, so fall through and
4560            // give them what they want
4561        } else {
4562            // Caller expressed no opinion, so match based on user state
4563            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4564                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4565            } else {
4566                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4567            }
4568        }
4569        return flags;
4570    }
4571
4572    private UserManagerInternal getUserManagerInternal() {
4573        if (mUserManagerInternal == null) {
4574            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4575        }
4576        return mUserManagerInternal;
4577    }
4578
4579    private DeviceIdleController.LocalService getDeviceIdleController() {
4580        if (mDeviceIdleController == null) {
4581            mDeviceIdleController =
4582                    LocalServices.getService(DeviceIdleController.LocalService.class);
4583        }
4584        return mDeviceIdleController;
4585    }
4586
4587    /**
4588     * Update given flags when being used to request {@link PackageInfo}.
4589     */
4590    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4591        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4592        boolean triaged = true;
4593        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4594                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4595            // Caller is asking for component details, so they'd better be
4596            // asking for specific encryption matching behavior, or be triaged
4597            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4598                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4599                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4600                triaged = false;
4601            }
4602        }
4603        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4604                | PackageManager.MATCH_SYSTEM_ONLY
4605                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4606            triaged = false;
4607        }
4608        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4609            mPermissionManager.enforceCrossUserPermission(
4610                    Binder.getCallingUid(), userId, false, false,
4611                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4612                    + Debug.getCallers(5));
4613        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4614                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4615            // If the caller wants all packages and has a restricted profile associated with it,
4616            // then match all users. This is to make sure that launchers that need to access work
4617            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4618            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4619            flags |= PackageManager.MATCH_ANY_USER;
4620        }
4621        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4622            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4623                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4624        }
4625        return updateFlags(flags, userId);
4626    }
4627
4628    /**
4629     * Update given flags when being used to request {@link ApplicationInfo}.
4630     */
4631    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4632        return updateFlagsForPackage(flags, userId, cookie);
4633    }
4634
4635    /**
4636     * Update given flags when being used to request {@link ComponentInfo}.
4637     */
4638    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4639        if (cookie instanceof Intent) {
4640            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4641                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4642            }
4643        }
4644
4645        boolean triaged = true;
4646        // Caller is asking for component details, so they'd better be
4647        // asking for specific encryption matching behavior, or be triaged
4648        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4649                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4650                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4651            triaged = false;
4652        }
4653        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4654            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4655                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4656        }
4657
4658        return updateFlags(flags, userId);
4659    }
4660
4661    /**
4662     * Update given intent when being used to request {@link ResolveInfo}.
4663     */
4664    private Intent updateIntentForResolve(Intent intent) {
4665        if (intent.getSelector() != null) {
4666            intent = intent.getSelector();
4667        }
4668        if (DEBUG_PREFERRED) {
4669            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4670        }
4671        return intent;
4672    }
4673
4674    /**
4675     * Update given flags when being used to request {@link ResolveInfo}.
4676     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4677     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4678     * flag set. However, this flag is only honoured in three circumstances:
4679     * <ul>
4680     * <li>when called from a system process</li>
4681     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4682     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4683     * action and a {@code android.intent.category.BROWSABLE} category</li>
4684     * </ul>
4685     */
4686    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4687        return updateFlagsForResolve(flags, userId, intent, callingUid,
4688                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4689    }
4690    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4691            boolean wantInstantApps) {
4692        return updateFlagsForResolve(flags, userId, intent, callingUid,
4693                wantInstantApps, false /*onlyExposedExplicitly*/);
4694    }
4695    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4696            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4697        // Safe mode means we shouldn't match any third-party components
4698        if (mSafeMode) {
4699            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4700        }
4701        if (getInstantAppPackageName(callingUid) != null) {
4702            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4703            if (onlyExposedExplicitly) {
4704                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4705            }
4706            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4707            flags |= PackageManager.MATCH_INSTANT;
4708        } else {
4709            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4710            final boolean allowMatchInstant =
4711                    (wantInstantApps
4712                            && Intent.ACTION_VIEW.equals(intent.getAction())
4713                            && hasWebURI(intent))
4714                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4715            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4716                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4717            if (!allowMatchInstant) {
4718                flags &= ~PackageManager.MATCH_INSTANT;
4719            }
4720        }
4721        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4722    }
4723
4724    @Override
4725    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4726        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4727    }
4728
4729    /**
4730     * Important: The provided filterCallingUid is used exclusively to filter out activities
4731     * that can be seen based on user state. It's typically the original caller uid prior
4732     * to clearing. Because it can only be provided by trusted code, it's value can be
4733     * trusted and will be used as-is; unlike userId which will be validated by this method.
4734     */
4735    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4736            int filterCallingUid, int userId) {
4737        if (!sUserManager.exists(userId)) return null;
4738        flags = updateFlagsForComponent(flags, userId, component);
4739        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4740                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4741        synchronized (mPackages) {
4742            PackageParser.Activity a = mActivities.mActivities.get(component);
4743
4744            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4745            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4746                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4747                if (ps == null) return null;
4748                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4749                    return null;
4750                }
4751                return PackageParser.generateActivityInfo(
4752                        a, flags, ps.readUserState(userId), userId);
4753            }
4754            if (mResolveComponentName.equals(component)) {
4755                return PackageParser.generateActivityInfo(
4756                        mResolveActivity, flags, new PackageUserState(), userId);
4757            }
4758        }
4759        return null;
4760    }
4761
4762    @Override
4763    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4764            String resolvedType) {
4765        synchronized (mPackages) {
4766            if (component.equals(mResolveComponentName)) {
4767                // The resolver supports EVERYTHING!
4768                return true;
4769            }
4770            final int callingUid = Binder.getCallingUid();
4771            final int callingUserId = UserHandle.getUserId(callingUid);
4772            PackageParser.Activity a = mActivities.mActivities.get(component);
4773            if (a == null) {
4774                return false;
4775            }
4776            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4777            if (ps == null) {
4778                return false;
4779            }
4780            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4781                return false;
4782            }
4783            for (int i=0; i<a.intents.size(); i++) {
4784                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4785                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4786                    return true;
4787                }
4788            }
4789            return false;
4790        }
4791    }
4792
4793    @Override
4794    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4795        if (!sUserManager.exists(userId)) return null;
4796        final int callingUid = Binder.getCallingUid();
4797        flags = updateFlagsForComponent(flags, userId, component);
4798        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4799                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4800        synchronized (mPackages) {
4801            PackageParser.Activity a = mReceivers.mActivities.get(component);
4802            if (DEBUG_PACKAGE_INFO) Log.v(
4803                TAG, "getReceiverInfo " + component + ": " + a);
4804            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4805                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4806                if (ps == null) return null;
4807                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4808                    return null;
4809                }
4810                return PackageParser.generateActivityInfo(
4811                        a, flags, ps.readUserState(userId), userId);
4812            }
4813        }
4814        return null;
4815    }
4816
4817    @Override
4818    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4819            int flags, int userId) {
4820        if (!sUserManager.exists(userId)) return null;
4821        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4822        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4823            return null;
4824        }
4825
4826        flags = updateFlagsForPackage(flags, userId, null);
4827
4828        final boolean canSeeStaticLibraries =
4829                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4830                        == PERMISSION_GRANTED
4831                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4832                        == PERMISSION_GRANTED
4833                || canRequestPackageInstallsInternal(packageName,
4834                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4835                        false  /* throwIfPermNotDeclared*/)
4836                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4837                        == PERMISSION_GRANTED;
4838
4839        synchronized (mPackages) {
4840            List<SharedLibraryInfo> result = null;
4841
4842            final int libCount = mSharedLibraries.size();
4843            for (int i = 0; i < libCount; i++) {
4844                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4845                if (versionedLib == null) {
4846                    continue;
4847                }
4848
4849                final int versionCount = versionedLib.size();
4850                for (int j = 0; j < versionCount; j++) {
4851                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4852                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4853                        break;
4854                    }
4855                    final long identity = Binder.clearCallingIdentity();
4856                    try {
4857                        PackageInfo packageInfo = getPackageInfoVersioned(
4858                                libInfo.getDeclaringPackage(), flags
4859                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4860                        if (packageInfo == null) {
4861                            continue;
4862                        }
4863                    } finally {
4864                        Binder.restoreCallingIdentity(identity);
4865                    }
4866
4867                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4868                            libInfo.getLongVersion(), libInfo.getType(),
4869                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4870                            flags, userId));
4871
4872                    if (result == null) {
4873                        result = new ArrayList<>();
4874                    }
4875                    result.add(resLibInfo);
4876                }
4877            }
4878
4879            return result != null ? new ParceledListSlice<>(result) : null;
4880        }
4881    }
4882
4883    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4884            SharedLibraryInfo libInfo, int flags, int userId) {
4885        List<VersionedPackage> versionedPackages = null;
4886        final int packageCount = mSettings.mPackages.size();
4887        for (int i = 0; i < packageCount; i++) {
4888            PackageSetting ps = mSettings.mPackages.valueAt(i);
4889
4890            if (ps == null) {
4891                continue;
4892            }
4893
4894            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4895                continue;
4896            }
4897
4898            final String libName = libInfo.getName();
4899            if (libInfo.isStatic()) {
4900                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4901                if (libIdx < 0) {
4902                    continue;
4903                }
4904                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4905                    continue;
4906                }
4907                if (versionedPackages == null) {
4908                    versionedPackages = new ArrayList<>();
4909                }
4910                // If the dependent is a static shared lib, use the public package name
4911                String dependentPackageName = ps.name;
4912                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4913                    dependentPackageName = ps.pkg.manifestPackageName;
4914                }
4915                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4916            } else if (ps.pkg != null) {
4917                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4918                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4919                    if (versionedPackages == null) {
4920                        versionedPackages = new ArrayList<>();
4921                    }
4922                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4923                }
4924            }
4925        }
4926
4927        return versionedPackages;
4928    }
4929
4930    @Override
4931    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4932        if (!sUserManager.exists(userId)) return null;
4933        final int callingUid = Binder.getCallingUid();
4934        flags = updateFlagsForComponent(flags, userId, component);
4935        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4936                false /* requireFullPermission */, false /* checkShell */, "get service info");
4937        synchronized (mPackages) {
4938            PackageParser.Service s = mServices.mServices.get(component);
4939            if (DEBUG_PACKAGE_INFO) Log.v(
4940                TAG, "getServiceInfo " + component + ": " + s);
4941            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4942                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4943                if (ps == null) return null;
4944                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4945                    return null;
4946                }
4947                return PackageParser.generateServiceInfo(
4948                        s, flags, ps.readUserState(userId), userId);
4949            }
4950        }
4951        return null;
4952    }
4953
4954    @Override
4955    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4956        if (!sUserManager.exists(userId)) return null;
4957        final int callingUid = Binder.getCallingUid();
4958        flags = updateFlagsForComponent(flags, userId, component);
4959        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4960                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4961        synchronized (mPackages) {
4962            PackageParser.Provider p = mProviders.mProviders.get(component);
4963            if (DEBUG_PACKAGE_INFO) Log.v(
4964                TAG, "getProviderInfo " + component + ": " + p);
4965            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4966                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4967                if (ps == null) return null;
4968                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4969                    return null;
4970                }
4971                return PackageParser.generateProviderInfo(
4972                        p, flags, ps.readUserState(userId), userId);
4973            }
4974        }
4975        return null;
4976    }
4977
4978    @Override
4979    public String[] getSystemSharedLibraryNames() {
4980        // allow instant applications
4981        synchronized (mPackages) {
4982            Set<String> libs = null;
4983            final int libCount = mSharedLibraries.size();
4984            for (int i = 0; i < libCount; i++) {
4985                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4986                if (versionedLib == null) {
4987                    continue;
4988                }
4989                final int versionCount = versionedLib.size();
4990                for (int j = 0; j < versionCount; j++) {
4991                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4992                    if (!libEntry.info.isStatic()) {
4993                        if (libs == null) {
4994                            libs = new ArraySet<>();
4995                        }
4996                        libs.add(libEntry.info.getName());
4997                        break;
4998                    }
4999                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5000                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5001                            UserHandle.getUserId(Binder.getCallingUid()),
5002                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5003                        if (libs == null) {
5004                            libs = new ArraySet<>();
5005                        }
5006                        libs.add(libEntry.info.getName());
5007                        break;
5008                    }
5009                }
5010            }
5011
5012            if (libs != null) {
5013                String[] libsArray = new String[libs.size()];
5014                libs.toArray(libsArray);
5015                return libsArray;
5016            }
5017
5018            return null;
5019        }
5020    }
5021
5022    @Override
5023    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5024        // allow instant applications
5025        synchronized (mPackages) {
5026            return mServicesSystemSharedLibraryPackageName;
5027        }
5028    }
5029
5030    @Override
5031    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5032        // allow instant applications
5033        synchronized (mPackages) {
5034            return mSharedSystemSharedLibraryPackageName;
5035        }
5036    }
5037
5038    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5039        for (int i = userList.length - 1; i >= 0; --i) {
5040            final int userId = userList[i];
5041            // don't add instant app to the list of updates
5042            if (pkgSetting.getInstantApp(userId)) {
5043                continue;
5044            }
5045            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5046            if (changedPackages == null) {
5047                changedPackages = new SparseArray<>();
5048                mChangedPackages.put(userId, changedPackages);
5049            }
5050            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5051            if (sequenceNumbers == null) {
5052                sequenceNumbers = new HashMap<>();
5053                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5054            }
5055            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5056            if (sequenceNumber != null) {
5057                changedPackages.remove(sequenceNumber);
5058            }
5059            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5060            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5061        }
5062        mChangedPackagesSequenceNumber++;
5063    }
5064
5065    @Override
5066    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5067        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5068            return null;
5069        }
5070        synchronized (mPackages) {
5071            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5072                return null;
5073            }
5074            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5075            if (changedPackages == null) {
5076                return null;
5077            }
5078            final List<String> packageNames =
5079                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5080            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5081                final String packageName = changedPackages.get(i);
5082                if (packageName != null) {
5083                    packageNames.add(packageName);
5084                }
5085            }
5086            return packageNames.isEmpty()
5087                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5088        }
5089    }
5090
5091    @Override
5092    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5093        // allow instant applications
5094        ArrayList<FeatureInfo> res;
5095        synchronized (mAvailableFeatures) {
5096            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5097            res.addAll(mAvailableFeatures.values());
5098        }
5099        final FeatureInfo fi = new FeatureInfo();
5100        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5101                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5102        res.add(fi);
5103
5104        return new ParceledListSlice<>(res);
5105    }
5106
5107    @Override
5108    public boolean hasSystemFeature(String name, int version) {
5109        // allow instant applications
5110        synchronized (mAvailableFeatures) {
5111            final FeatureInfo feat = mAvailableFeatures.get(name);
5112            if (feat == null) {
5113                return false;
5114            } else {
5115                return feat.version >= version;
5116            }
5117        }
5118    }
5119
5120    @Override
5121    public int checkPermission(String permName, String pkgName, int userId) {
5122        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5123    }
5124
5125    @Override
5126    public int checkUidPermission(String permName, int uid) {
5127        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5128    }
5129
5130    @Override
5131    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5132        if (UserHandle.getCallingUserId() != userId) {
5133            mContext.enforceCallingPermission(
5134                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5135                    "isPermissionRevokedByPolicy for user " + userId);
5136        }
5137
5138        if (checkPermission(permission, packageName, userId)
5139                == PackageManager.PERMISSION_GRANTED) {
5140            return false;
5141        }
5142
5143        final int callingUid = Binder.getCallingUid();
5144        if (getInstantAppPackageName(callingUid) != null) {
5145            if (!isCallerSameApp(packageName, callingUid)) {
5146                return false;
5147            }
5148        } else {
5149            if (isInstantApp(packageName, userId)) {
5150                return false;
5151            }
5152        }
5153
5154        final long identity = Binder.clearCallingIdentity();
5155        try {
5156            final int flags = getPermissionFlags(permission, packageName, userId);
5157            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5158        } finally {
5159            Binder.restoreCallingIdentity(identity);
5160        }
5161    }
5162
5163    @Override
5164    public String getPermissionControllerPackageName() {
5165        synchronized (mPackages) {
5166            return mRequiredInstallerPackage;
5167        }
5168    }
5169
5170    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5171        return mPermissionManager.addDynamicPermission(
5172                info, async, getCallingUid(), new PermissionCallback() {
5173                    @Override
5174                    public void onPermissionChanged() {
5175                        if (!async) {
5176                            mSettings.writeLPr();
5177                        } else {
5178                            scheduleWriteSettingsLocked();
5179                        }
5180                    }
5181                });
5182    }
5183
5184    @Override
5185    public boolean addPermission(PermissionInfo info) {
5186        synchronized (mPackages) {
5187            return addDynamicPermission(info, false);
5188        }
5189    }
5190
5191    @Override
5192    public boolean addPermissionAsync(PermissionInfo info) {
5193        synchronized (mPackages) {
5194            return addDynamicPermission(info, true);
5195        }
5196    }
5197
5198    @Override
5199    public void removePermission(String permName) {
5200        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5201    }
5202
5203    @Override
5204    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5205        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5206                getCallingUid(), userId, mPermissionCallback);
5207    }
5208
5209    @Override
5210    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5211        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5212                getCallingUid(), userId, mPermissionCallback);
5213    }
5214
5215    @Override
5216    public void resetRuntimePermissions() {
5217        mContext.enforceCallingOrSelfPermission(
5218                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5219                "revokeRuntimePermission");
5220
5221        int callingUid = Binder.getCallingUid();
5222        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5223            mContext.enforceCallingOrSelfPermission(
5224                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5225                    "resetRuntimePermissions");
5226        }
5227
5228        synchronized (mPackages) {
5229            mPermissionManager.updateAllPermissions(
5230                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5231                    mPermissionCallback);
5232            for (int userId : UserManagerService.getInstance().getUserIds()) {
5233                final int packageCount = mPackages.size();
5234                for (int i = 0; i < packageCount; i++) {
5235                    PackageParser.Package pkg = mPackages.valueAt(i);
5236                    if (!(pkg.mExtras instanceof PackageSetting)) {
5237                        continue;
5238                    }
5239                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5240                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5241                }
5242            }
5243        }
5244    }
5245
5246    @Override
5247    public int getPermissionFlags(String permName, String packageName, int userId) {
5248        return mPermissionManager.getPermissionFlags(
5249                permName, packageName, getCallingUid(), userId);
5250    }
5251
5252    @Override
5253    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5254            int flagValues, int userId) {
5255        mPermissionManager.updatePermissionFlags(
5256                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5257                mPermissionCallback);
5258    }
5259
5260    /**
5261     * Update the permission flags for all packages and runtime permissions of a user in order
5262     * to allow device or profile owner to remove POLICY_FIXED.
5263     */
5264    @Override
5265    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5266        synchronized (mPackages) {
5267            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5268                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5269                    mPermissionCallback);
5270            if (changed) {
5271                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5272            }
5273        }
5274    }
5275
5276    @Override
5277    public boolean shouldShowRequestPermissionRationale(String permissionName,
5278            String packageName, int userId) {
5279        if (UserHandle.getCallingUserId() != userId) {
5280            mContext.enforceCallingPermission(
5281                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5282                    "canShowRequestPermissionRationale for user " + userId);
5283        }
5284
5285        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5286        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5287            return false;
5288        }
5289
5290        if (checkPermission(permissionName, packageName, userId)
5291                == PackageManager.PERMISSION_GRANTED) {
5292            return false;
5293        }
5294
5295        final int flags;
5296
5297        final long identity = Binder.clearCallingIdentity();
5298        try {
5299            flags = getPermissionFlags(permissionName,
5300                    packageName, userId);
5301        } finally {
5302            Binder.restoreCallingIdentity(identity);
5303        }
5304
5305        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5306                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5307                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5308
5309        if ((flags & fixedFlags) != 0) {
5310            return false;
5311        }
5312
5313        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5314    }
5315
5316    @Override
5317    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5318        mContext.enforceCallingOrSelfPermission(
5319                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5320                "addOnPermissionsChangeListener");
5321
5322        synchronized (mPackages) {
5323            mOnPermissionChangeListeners.addListenerLocked(listener);
5324        }
5325    }
5326
5327    @Override
5328    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5329        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5330            throw new SecurityException("Instant applications don't have access to this method");
5331        }
5332        synchronized (mPackages) {
5333            mOnPermissionChangeListeners.removeListenerLocked(listener);
5334        }
5335    }
5336
5337    @Override
5338    public boolean isProtectedBroadcast(String actionName) {
5339        // allow instant applications
5340        synchronized (mProtectedBroadcasts) {
5341            if (mProtectedBroadcasts.contains(actionName)) {
5342                return true;
5343            } else if (actionName != null) {
5344                // TODO: remove these terrible hacks
5345                if (actionName.startsWith("android.net.netmon.lingerExpired")
5346                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5347                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5348                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5349                    return true;
5350                }
5351            }
5352        }
5353        return false;
5354    }
5355
5356    @Override
5357    public int checkSignatures(String pkg1, String pkg2) {
5358        synchronized (mPackages) {
5359            final PackageParser.Package p1 = mPackages.get(pkg1);
5360            final PackageParser.Package p2 = mPackages.get(pkg2);
5361            if (p1 == null || p1.mExtras == null
5362                    || p2 == null || p2.mExtras == null) {
5363                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5364            }
5365            final int callingUid = Binder.getCallingUid();
5366            final int callingUserId = UserHandle.getUserId(callingUid);
5367            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5368            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5369            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5370                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5371                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5372            }
5373            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5374        }
5375    }
5376
5377    @Override
5378    public int checkUidSignatures(int uid1, int uid2) {
5379        final int callingUid = Binder.getCallingUid();
5380        final int callingUserId = UserHandle.getUserId(callingUid);
5381        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5382        // Map to base uids.
5383        uid1 = UserHandle.getAppId(uid1);
5384        uid2 = UserHandle.getAppId(uid2);
5385        // reader
5386        synchronized (mPackages) {
5387            Signature[] s1;
5388            Signature[] s2;
5389            Object obj = mSettings.getUserIdLPr(uid1);
5390            if (obj != null) {
5391                if (obj instanceof SharedUserSetting) {
5392                    if (isCallerInstantApp) {
5393                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5394                    }
5395                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5396                } else if (obj instanceof PackageSetting) {
5397                    final PackageSetting ps = (PackageSetting) obj;
5398                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5399                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5400                    }
5401                    s1 = ps.signatures.mSignatures;
5402                } else {
5403                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5404                }
5405            } else {
5406                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5407            }
5408            obj = mSettings.getUserIdLPr(uid2);
5409            if (obj != null) {
5410                if (obj instanceof SharedUserSetting) {
5411                    if (isCallerInstantApp) {
5412                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5413                    }
5414                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5415                } else if (obj instanceof PackageSetting) {
5416                    final PackageSetting ps = (PackageSetting) obj;
5417                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5418                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5419                    }
5420                    s2 = ps.signatures.mSignatures;
5421                } else {
5422                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5423                }
5424            } else {
5425                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5426            }
5427            return compareSignatures(s1, s2);
5428        }
5429    }
5430
5431    /**
5432     * This method should typically only be used when granting or revoking
5433     * permissions, since the app may immediately restart after this call.
5434     * <p>
5435     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5436     * guard your work against the app being relaunched.
5437     */
5438    private void killUid(int appId, int userId, String reason) {
5439        final long identity = Binder.clearCallingIdentity();
5440        try {
5441            IActivityManager am = ActivityManager.getService();
5442            if (am != null) {
5443                try {
5444                    am.killUid(appId, userId, reason);
5445                } catch (RemoteException e) {
5446                    /* ignore - same process */
5447                }
5448            }
5449        } finally {
5450            Binder.restoreCallingIdentity(identity);
5451        }
5452    }
5453
5454    /**
5455     * If the database version for this type of package (internal storage or
5456     * external storage) is less than the version where package signatures
5457     * were updated, return true.
5458     */
5459    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5460        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5461        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5462    }
5463
5464    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5465        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5466        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5467    }
5468
5469    @Override
5470    public List<String> getAllPackages() {
5471        final int callingUid = Binder.getCallingUid();
5472        final int callingUserId = UserHandle.getUserId(callingUid);
5473        synchronized (mPackages) {
5474            if (canViewInstantApps(callingUid, callingUserId)) {
5475                return new ArrayList<String>(mPackages.keySet());
5476            }
5477            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5478            final List<String> result = new ArrayList<>();
5479            if (instantAppPkgName != null) {
5480                // caller is an instant application; filter unexposed applications
5481                for (PackageParser.Package pkg : mPackages.values()) {
5482                    if (!pkg.visibleToInstantApps) {
5483                        continue;
5484                    }
5485                    result.add(pkg.packageName);
5486                }
5487            } else {
5488                // caller is a normal application; filter instant applications
5489                for (PackageParser.Package pkg : mPackages.values()) {
5490                    final PackageSetting ps =
5491                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5492                    if (ps != null
5493                            && ps.getInstantApp(callingUserId)
5494                            && !mInstantAppRegistry.isInstantAccessGranted(
5495                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5496                        continue;
5497                    }
5498                    result.add(pkg.packageName);
5499                }
5500            }
5501            return result;
5502        }
5503    }
5504
5505    @Override
5506    public String[] getPackagesForUid(int uid) {
5507        final int callingUid = Binder.getCallingUid();
5508        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5509        final int userId = UserHandle.getUserId(uid);
5510        uid = UserHandle.getAppId(uid);
5511        // reader
5512        synchronized (mPackages) {
5513            Object obj = mSettings.getUserIdLPr(uid);
5514            if (obj instanceof SharedUserSetting) {
5515                if (isCallerInstantApp) {
5516                    return null;
5517                }
5518                final SharedUserSetting sus = (SharedUserSetting) obj;
5519                final int N = sus.packages.size();
5520                String[] res = new String[N];
5521                final Iterator<PackageSetting> it = sus.packages.iterator();
5522                int i = 0;
5523                while (it.hasNext()) {
5524                    PackageSetting ps = it.next();
5525                    if (ps.getInstalled(userId)) {
5526                        res[i++] = ps.name;
5527                    } else {
5528                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5529                    }
5530                }
5531                return res;
5532            } else if (obj instanceof PackageSetting) {
5533                final PackageSetting ps = (PackageSetting) obj;
5534                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5535                    return new String[]{ps.name};
5536                }
5537            }
5538        }
5539        return null;
5540    }
5541
5542    @Override
5543    public String getNameForUid(int uid) {
5544        final int callingUid = Binder.getCallingUid();
5545        if (getInstantAppPackageName(callingUid) != null) {
5546            return null;
5547        }
5548        synchronized (mPackages) {
5549            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5550            if (obj instanceof SharedUserSetting) {
5551                final SharedUserSetting sus = (SharedUserSetting) obj;
5552                return sus.name + ":" + sus.userId;
5553            } else if (obj instanceof PackageSetting) {
5554                final PackageSetting ps = (PackageSetting) obj;
5555                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5556                    return null;
5557                }
5558                return ps.name;
5559            }
5560            return null;
5561        }
5562    }
5563
5564    @Override
5565    public String[] getNamesForUids(int[] uids) {
5566        if (uids == null || uids.length == 0) {
5567            return null;
5568        }
5569        final int callingUid = Binder.getCallingUid();
5570        if (getInstantAppPackageName(callingUid) != null) {
5571            return null;
5572        }
5573        final String[] names = new String[uids.length];
5574        synchronized (mPackages) {
5575            for (int i = uids.length - 1; i >= 0; i--) {
5576                final int uid = uids[i];
5577                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5578                if (obj instanceof SharedUserSetting) {
5579                    final SharedUserSetting sus = (SharedUserSetting) obj;
5580                    names[i] = "shared:" + sus.name;
5581                } else if (obj instanceof PackageSetting) {
5582                    final PackageSetting ps = (PackageSetting) obj;
5583                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5584                        names[i] = null;
5585                    } else {
5586                        names[i] = ps.name;
5587                    }
5588                } else {
5589                    names[i] = null;
5590                }
5591            }
5592        }
5593        return names;
5594    }
5595
5596    @Override
5597    public int getUidForSharedUser(String sharedUserName) {
5598        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5599            return -1;
5600        }
5601        if (sharedUserName == null) {
5602            return -1;
5603        }
5604        // reader
5605        synchronized (mPackages) {
5606            SharedUserSetting suid;
5607            try {
5608                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5609                if (suid != null) {
5610                    return suid.userId;
5611                }
5612            } catch (PackageManagerException ignore) {
5613                // can't happen, but, still need to catch it
5614            }
5615            return -1;
5616        }
5617    }
5618
5619    @Override
5620    public int getFlagsForUid(int uid) {
5621        final int callingUid = Binder.getCallingUid();
5622        if (getInstantAppPackageName(callingUid) != null) {
5623            return 0;
5624        }
5625        synchronized (mPackages) {
5626            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5627            if (obj instanceof SharedUserSetting) {
5628                final SharedUserSetting sus = (SharedUserSetting) obj;
5629                return sus.pkgFlags;
5630            } else if (obj instanceof PackageSetting) {
5631                final PackageSetting ps = (PackageSetting) obj;
5632                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5633                    return 0;
5634                }
5635                return ps.pkgFlags;
5636            }
5637        }
5638        return 0;
5639    }
5640
5641    @Override
5642    public int getPrivateFlagsForUid(int uid) {
5643        final int callingUid = Binder.getCallingUid();
5644        if (getInstantAppPackageName(callingUid) != null) {
5645            return 0;
5646        }
5647        synchronized (mPackages) {
5648            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5649            if (obj instanceof SharedUserSetting) {
5650                final SharedUserSetting sus = (SharedUserSetting) obj;
5651                return sus.pkgPrivateFlags;
5652            } else if (obj instanceof PackageSetting) {
5653                final PackageSetting ps = (PackageSetting) obj;
5654                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5655                    return 0;
5656                }
5657                return ps.pkgPrivateFlags;
5658            }
5659        }
5660        return 0;
5661    }
5662
5663    @Override
5664    public boolean isUidPrivileged(int uid) {
5665        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5666            return false;
5667        }
5668        uid = UserHandle.getAppId(uid);
5669        // reader
5670        synchronized (mPackages) {
5671            Object obj = mSettings.getUserIdLPr(uid);
5672            if (obj instanceof SharedUserSetting) {
5673                final SharedUserSetting sus = (SharedUserSetting) obj;
5674                final Iterator<PackageSetting> it = sus.packages.iterator();
5675                while (it.hasNext()) {
5676                    if (it.next().isPrivileged()) {
5677                        return true;
5678                    }
5679                }
5680            } else if (obj instanceof PackageSetting) {
5681                final PackageSetting ps = (PackageSetting) obj;
5682                return ps.isPrivileged();
5683            }
5684        }
5685        return false;
5686    }
5687
5688    @Override
5689    public String[] getAppOpPermissionPackages(String permName) {
5690        return mPermissionManager.getAppOpPermissionPackages(permName);
5691    }
5692
5693    @Override
5694    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5695            int flags, int userId) {
5696        return resolveIntentInternal(
5697                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5698    }
5699
5700    /**
5701     * Normally instant apps can only be resolved when they're visible to the caller.
5702     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5703     * since we need to allow the system to start any installed application.
5704     */
5705    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5706            int flags, int userId, boolean resolveForStart) {
5707        try {
5708            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5709
5710            if (!sUserManager.exists(userId)) return null;
5711            final int callingUid = Binder.getCallingUid();
5712            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5713            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5714                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5715
5716            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5717            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5718                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5719            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5720
5721            final ResolveInfo bestChoice =
5722                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5723            return bestChoice;
5724        } finally {
5725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5726        }
5727    }
5728
5729    @Override
5730    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5731        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5732            throw new SecurityException(
5733                    "findPersistentPreferredActivity can only be run by the system");
5734        }
5735        if (!sUserManager.exists(userId)) {
5736            return null;
5737        }
5738        final int callingUid = Binder.getCallingUid();
5739        intent = updateIntentForResolve(intent);
5740        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5741        final int flags = updateFlagsForResolve(
5742                0, userId, intent, callingUid, false /*includeInstantApps*/);
5743        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5744                userId);
5745        synchronized (mPackages) {
5746            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5747                    userId);
5748        }
5749    }
5750
5751    @Override
5752    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5753            IntentFilter filter, int match, ComponentName activity) {
5754        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5755            return;
5756        }
5757        final int userId = UserHandle.getCallingUserId();
5758        if (DEBUG_PREFERRED) {
5759            Log.v(TAG, "setLastChosenActivity intent=" + intent
5760                + " resolvedType=" + resolvedType
5761                + " flags=" + flags
5762                + " filter=" + filter
5763                + " match=" + match
5764                + " activity=" + activity);
5765            filter.dump(new PrintStreamPrinter(System.out), "    ");
5766        }
5767        intent.setComponent(null);
5768        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5769                userId);
5770        // Find any earlier preferred or last chosen entries and nuke them
5771        findPreferredActivity(intent, resolvedType,
5772                flags, query, 0, false, true, false, userId);
5773        // Add the new activity as the last chosen for this filter
5774        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5775                "Setting last chosen");
5776    }
5777
5778    @Override
5779    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5780        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5781            return null;
5782        }
5783        final int userId = UserHandle.getCallingUserId();
5784        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5785        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5786                userId);
5787        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5788                false, false, false, userId);
5789    }
5790
5791    /**
5792     * Returns whether or not instant apps have been disabled remotely.
5793     */
5794    private boolean isEphemeralDisabled() {
5795        return mEphemeralAppsDisabled;
5796    }
5797
5798    private boolean isInstantAppAllowed(
5799            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5800            boolean skipPackageCheck) {
5801        if (mInstantAppResolverConnection == null) {
5802            return false;
5803        }
5804        if (mInstantAppInstallerActivity == null) {
5805            return false;
5806        }
5807        if (intent.getComponent() != null) {
5808            return false;
5809        }
5810        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5811            return false;
5812        }
5813        if (!skipPackageCheck && intent.getPackage() != null) {
5814            return false;
5815        }
5816        final boolean isWebUri = hasWebURI(intent);
5817        if (!isWebUri || intent.getData().getHost() == null) {
5818            return false;
5819        }
5820        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5821        // Or if there's already an ephemeral app installed that handles the action
5822        synchronized (mPackages) {
5823            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5824            for (int n = 0; n < count; n++) {
5825                final ResolveInfo info = resolvedActivities.get(n);
5826                final String packageName = info.activityInfo.packageName;
5827                final PackageSetting ps = mSettings.mPackages.get(packageName);
5828                if (ps != null) {
5829                    // only check domain verification status if the app is not a browser
5830                    if (!info.handleAllWebDataURI) {
5831                        // Try to get the status from User settings first
5832                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5833                        final int status = (int) (packedStatus >> 32);
5834                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5835                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5836                            if (DEBUG_EPHEMERAL) {
5837                                Slog.v(TAG, "DENY instant app;"
5838                                    + " pkg: " + packageName + ", status: " + status);
5839                            }
5840                            return false;
5841                        }
5842                    }
5843                    if (ps.getInstantApp(userId)) {
5844                        if (DEBUG_EPHEMERAL) {
5845                            Slog.v(TAG, "DENY instant app installed;"
5846                                    + " pkg: " + packageName);
5847                        }
5848                        return false;
5849                    }
5850                }
5851            }
5852        }
5853        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5854        return true;
5855    }
5856
5857    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5858            Intent origIntent, String resolvedType, String callingPackage,
5859            Bundle verificationBundle, int userId) {
5860        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5861                new InstantAppRequest(responseObj, origIntent, resolvedType,
5862                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5863        mHandler.sendMessage(msg);
5864    }
5865
5866    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5867            int flags, List<ResolveInfo> query, int userId) {
5868        if (query != null) {
5869            final int N = query.size();
5870            if (N == 1) {
5871                return query.get(0);
5872            } else if (N > 1) {
5873                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5874                // If there is more than one activity with the same priority,
5875                // then let the user decide between them.
5876                ResolveInfo r0 = query.get(0);
5877                ResolveInfo r1 = query.get(1);
5878                if (DEBUG_INTENT_MATCHING || debug) {
5879                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5880                            + r1.activityInfo.name + "=" + r1.priority);
5881                }
5882                // If the first activity has a higher priority, or a different
5883                // default, then it is always desirable to pick it.
5884                if (r0.priority != r1.priority
5885                        || r0.preferredOrder != r1.preferredOrder
5886                        || r0.isDefault != r1.isDefault) {
5887                    return query.get(0);
5888                }
5889                // If we have saved a preference for a preferred activity for
5890                // this Intent, use that.
5891                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5892                        flags, query, r0.priority, true, false, debug, userId);
5893                if (ri != null) {
5894                    return ri;
5895                }
5896                // If we have an ephemeral app, use it
5897                for (int i = 0; i < N; i++) {
5898                    ri = query.get(i);
5899                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5900                        final String packageName = ri.activityInfo.packageName;
5901                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5902                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5903                        final int status = (int)(packedStatus >> 32);
5904                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5905                            return ri;
5906                        }
5907                    }
5908                }
5909                ri = new ResolveInfo(mResolveInfo);
5910                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5911                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5912                // If all of the options come from the same package, show the application's
5913                // label and icon instead of the generic resolver's.
5914                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5915                // and then throw away the ResolveInfo itself, meaning that the caller loses
5916                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5917                // a fallback for this case; we only set the target package's resources on
5918                // the ResolveInfo, not the ActivityInfo.
5919                final String intentPackage = intent.getPackage();
5920                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5921                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5922                    ri.resolvePackageName = intentPackage;
5923                    if (userNeedsBadging(userId)) {
5924                        ri.noResourceId = true;
5925                    } else {
5926                        ri.icon = appi.icon;
5927                    }
5928                    ri.iconResourceId = appi.icon;
5929                    ri.labelRes = appi.labelRes;
5930                }
5931                ri.activityInfo.applicationInfo = new ApplicationInfo(
5932                        ri.activityInfo.applicationInfo);
5933                if (userId != 0) {
5934                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5935                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5936                }
5937                // Make sure that the resolver is displayable in car mode
5938                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5939                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5940                return ri;
5941            }
5942        }
5943        return null;
5944    }
5945
5946    /**
5947     * Return true if the given list is not empty and all of its contents have
5948     * an activityInfo with the given package name.
5949     */
5950    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5951        if (ArrayUtils.isEmpty(list)) {
5952            return false;
5953        }
5954        for (int i = 0, N = list.size(); i < N; i++) {
5955            final ResolveInfo ri = list.get(i);
5956            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5957            if (ai == null || !packageName.equals(ai.packageName)) {
5958                return false;
5959            }
5960        }
5961        return true;
5962    }
5963
5964    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5965            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5966        final int N = query.size();
5967        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5968                .get(userId);
5969        // Get the list of persistent preferred activities that handle the intent
5970        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5971        List<PersistentPreferredActivity> pprefs = ppir != null
5972                ? ppir.queryIntent(intent, resolvedType,
5973                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5974                        userId)
5975                : null;
5976        if (pprefs != null && pprefs.size() > 0) {
5977            final int M = pprefs.size();
5978            for (int i=0; i<M; i++) {
5979                final PersistentPreferredActivity ppa = pprefs.get(i);
5980                if (DEBUG_PREFERRED || debug) {
5981                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5982                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5983                            + "\n  component=" + ppa.mComponent);
5984                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5985                }
5986                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5987                        flags | MATCH_DISABLED_COMPONENTS, userId);
5988                if (DEBUG_PREFERRED || debug) {
5989                    Slog.v(TAG, "Found persistent preferred activity:");
5990                    if (ai != null) {
5991                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5992                    } else {
5993                        Slog.v(TAG, "  null");
5994                    }
5995                }
5996                if (ai == null) {
5997                    // This previously registered persistent preferred activity
5998                    // component is no longer known. Ignore it and do NOT remove it.
5999                    continue;
6000                }
6001                for (int j=0; j<N; j++) {
6002                    final ResolveInfo ri = query.get(j);
6003                    if (!ri.activityInfo.applicationInfo.packageName
6004                            .equals(ai.applicationInfo.packageName)) {
6005                        continue;
6006                    }
6007                    if (!ri.activityInfo.name.equals(ai.name)) {
6008                        continue;
6009                    }
6010                    //  Found a persistent preference that can handle the intent.
6011                    if (DEBUG_PREFERRED || debug) {
6012                        Slog.v(TAG, "Returning persistent preferred activity: " +
6013                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6014                    }
6015                    return ri;
6016                }
6017            }
6018        }
6019        return null;
6020    }
6021
6022    // TODO: handle preferred activities missing while user has amnesia
6023    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6024            List<ResolveInfo> query, int priority, boolean always,
6025            boolean removeMatches, boolean debug, int userId) {
6026        if (!sUserManager.exists(userId)) return null;
6027        final int callingUid = Binder.getCallingUid();
6028        flags = updateFlagsForResolve(
6029                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6030        intent = updateIntentForResolve(intent);
6031        // writer
6032        synchronized (mPackages) {
6033            // Try to find a matching persistent preferred activity.
6034            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6035                    debug, userId);
6036
6037            // If a persistent preferred activity matched, use it.
6038            if (pri != null) {
6039                return pri;
6040            }
6041
6042            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6043            // Get the list of preferred activities that handle the intent
6044            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6045            List<PreferredActivity> prefs = pir != null
6046                    ? pir.queryIntent(intent, resolvedType,
6047                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6048                            userId)
6049                    : null;
6050            if (prefs != null && prefs.size() > 0) {
6051                boolean changed = false;
6052                try {
6053                    // First figure out how good the original match set is.
6054                    // We will only allow preferred activities that came
6055                    // from the same match quality.
6056                    int match = 0;
6057
6058                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6059
6060                    final int N = query.size();
6061                    for (int j=0; j<N; j++) {
6062                        final ResolveInfo ri = query.get(j);
6063                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6064                                + ": 0x" + Integer.toHexString(match));
6065                        if (ri.match > match) {
6066                            match = ri.match;
6067                        }
6068                    }
6069
6070                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6071                            + Integer.toHexString(match));
6072
6073                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6074                    final int M = prefs.size();
6075                    for (int i=0; i<M; i++) {
6076                        final PreferredActivity pa = prefs.get(i);
6077                        if (DEBUG_PREFERRED || debug) {
6078                            Slog.v(TAG, "Checking PreferredActivity ds="
6079                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6080                                    + "\n  component=" + pa.mPref.mComponent);
6081                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6082                        }
6083                        if (pa.mPref.mMatch != match) {
6084                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6085                                    + Integer.toHexString(pa.mPref.mMatch));
6086                            continue;
6087                        }
6088                        // If it's not an "always" type preferred activity and that's what we're
6089                        // looking for, skip it.
6090                        if (always && !pa.mPref.mAlways) {
6091                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6092                            continue;
6093                        }
6094                        final ActivityInfo ai = getActivityInfo(
6095                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6096                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6097                                userId);
6098                        if (DEBUG_PREFERRED || debug) {
6099                            Slog.v(TAG, "Found preferred activity:");
6100                            if (ai != null) {
6101                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6102                            } else {
6103                                Slog.v(TAG, "  null");
6104                            }
6105                        }
6106                        if (ai == null) {
6107                            // This previously registered preferred activity
6108                            // component is no longer known.  Most likely an update
6109                            // to the app was installed and in the new version this
6110                            // component no longer exists.  Clean it up by removing
6111                            // it from the preferred activities list, and skip it.
6112                            Slog.w(TAG, "Removing dangling preferred activity: "
6113                                    + pa.mPref.mComponent);
6114                            pir.removeFilter(pa);
6115                            changed = true;
6116                            continue;
6117                        }
6118                        for (int j=0; j<N; j++) {
6119                            final ResolveInfo ri = query.get(j);
6120                            if (!ri.activityInfo.applicationInfo.packageName
6121                                    .equals(ai.applicationInfo.packageName)) {
6122                                continue;
6123                            }
6124                            if (!ri.activityInfo.name.equals(ai.name)) {
6125                                continue;
6126                            }
6127
6128                            if (removeMatches) {
6129                                pir.removeFilter(pa);
6130                                changed = true;
6131                                if (DEBUG_PREFERRED) {
6132                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6133                                }
6134                                break;
6135                            }
6136
6137                            // Okay we found a previously set preferred or last chosen app.
6138                            // If the result set is different from when this
6139                            // was created, and is not a subset of the preferred set, we need to
6140                            // clear it and re-ask the user their preference, if we're looking for
6141                            // an "always" type entry.
6142                            if (always && !pa.mPref.sameSet(query)) {
6143                                if (pa.mPref.isSuperset(query)) {
6144                                    // some components of the set are no longer present in
6145                                    // the query, but the preferred activity can still be reused
6146                                    if (DEBUG_PREFERRED) {
6147                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6148                                                + " still valid as only non-preferred components"
6149                                                + " were removed for " + intent + " type "
6150                                                + resolvedType);
6151                                    }
6152                                    // remove obsolete components and re-add the up-to-date filter
6153                                    PreferredActivity freshPa = new PreferredActivity(pa,
6154                                            pa.mPref.mMatch,
6155                                            pa.mPref.discardObsoleteComponents(query),
6156                                            pa.mPref.mComponent,
6157                                            pa.mPref.mAlways);
6158                                    pir.removeFilter(pa);
6159                                    pir.addFilter(freshPa);
6160                                    changed = true;
6161                                } else {
6162                                    Slog.i(TAG,
6163                                            "Result set changed, dropping preferred activity for "
6164                                                    + intent + " type " + resolvedType);
6165                                    if (DEBUG_PREFERRED) {
6166                                        Slog.v(TAG, "Removing preferred activity since set changed "
6167                                                + pa.mPref.mComponent);
6168                                    }
6169                                    pir.removeFilter(pa);
6170                                    // Re-add the filter as a "last chosen" entry (!always)
6171                                    PreferredActivity lastChosen = new PreferredActivity(
6172                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6173                                    pir.addFilter(lastChosen);
6174                                    changed = true;
6175                                    return null;
6176                                }
6177                            }
6178
6179                            // Yay! Either the set matched or we're looking for the last chosen
6180                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6181                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6182                            return ri;
6183                        }
6184                    }
6185                } finally {
6186                    if (changed) {
6187                        if (DEBUG_PREFERRED) {
6188                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6189                        }
6190                        scheduleWritePackageRestrictionsLocked(userId);
6191                    }
6192                }
6193            }
6194        }
6195        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6196        return null;
6197    }
6198
6199    /*
6200     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6201     */
6202    @Override
6203    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6204            int targetUserId) {
6205        mContext.enforceCallingOrSelfPermission(
6206                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6207        List<CrossProfileIntentFilter> matches =
6208                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6209        if (matches != null) {
6210            int size = matches.size();
6211            for (int i = 0; i < size; i++) {
6212                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6213            }
6214        }
6215        if (hasWebURI(intent)) {
6216            // cross-profile app linking works only towards the parent.
6217            final int callingUid = Binder.getCallingUid();
6218            final UserInfo parent = getProfileParent(sourceUserId);
6219            synchronized(mPackages) {
6220                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6221                        false /*includeInstantApps*/);
6222                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6223                        intent, resolvedType, flags, sourceUserId, parent.id);
6224                return xpDomainInfo != null;
6225            }
6226        }
6227        return false;
6228    }
6229
6230    private UserInfo getProfileParent(int userId) {
6231        final long identity = Binder.clearCallingIdentity();
6232        try {
6233            return sUserManager.getProfileParent(userId);
6234        } finally {
6235            Binder.restoreCallingIdentity(identity);
6236        }
6237    }
6238
6239    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6240            String resolvedType, int userId) {
6241        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6242        if (resolver != null) {
6243            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6244        }
6245        return null;
6246    }
6247
6248    @Override
6249    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6250            String resolvedType, int flags, int userId) {
6251        try {
6252            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6253
6254            return new ParceledListSlice<>(
6255                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6256        } finally {
6257            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6258        }
6259    }
6260
6261    /**
6262     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6263     * instant, returns {@code null}.
6264     */
6265    private String getInstantAppPackageName(int callingUid) {
6266        synchronized (mPackages) {
6267            // If the caller is an isolated app use the owner's uid for the lookup.
6268            if (Process.isIsolated(callingUid)) {
6269                callingUid = mIsolatedOwners.get(callingUid);
6270            }
6271            final int appId = UserHandle.getAppId(callingUid);
6272            final Object obj = mSettings.getUserIdLPr(appId);
6273            if (obj instanceof PackageSetting) {
6274                final PackageSetting ps = (PackageSetting) obj;
6275                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6276                return isInstantApp ? ps.pkg.packageName : null;
6277            }
6278        }
6279        return null;
6280    }
6281
6282    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6283            String resolvedType, int flags, int userId) {
6284        return queryIntentActivitiesInternal(
6285                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6286                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6287    }
6288
6289    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6290            String resolvedType, int flags, int filterCallingUid, int userId,
6291            boolean resolveForStart, boolean allowDynamicSplits) {
6292        if (!sUserManager.exists(userId)) return Collections.emptyList();
6293        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6294        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6295                false /* requireFullPermission */, false /* checkShell */,
6296                "query intent activities");
6297        final String pkgName = intent.getPackage();
6298        ComponentName comp = intent.getComponent();
6299        if (comp == null) {
6300            if (intent.getSelector() != null) {
6301                intent = intent.getSelector();
6302                comp = intent.getComponent();
6303            }
6304        }
6305
6306        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6307                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6308        if (comp != null) {
6309            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6310            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6311            if (ai != null) {
6312                // When specifying an explicit component, we prevent the activity from being
6313                // used when either 1) the calling package is normal and the activity is within
6314                // an ephemeral application or 2) the calling package is ephemeral and the
6315                // activity is not visible to ephemeral applications.
6316                final boolean matchInstantApp =
6317                        (flags & PackageManager.MATCH_INSTANT) != 0;
6318                final boolean matchVisibleToInstantAppOnly =
6319                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6320                final boolean matchExplicitlyVisibleOnly =
6321                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6322                final boolean isCallerInstantApp =
6323                        instantAppPkgName != null;
6324                final boolean isTargetSameInstantApp =
6325                        comp.getPackageName().equals(instantAppPkgName);
6326                final boolean isTargetInstantApp =
6327                        (ai.applicationInfo.privateFlags
6328                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6329                final boolean isTargetVisibleToInstantApp =
6330                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6331                final boolean isTargetExplicitlyVisibleToInstantApp =
6332                        isTargetVisibleToInstantApp
6333                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6334                final boolean isTargetHiddenFromInstantApp =
6335                        !isTargetVisibleToInstantApp
6336                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6337                final boolean blockResolution =
6338                        !isTargetSameInstantApp
6339                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6340                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6341                                        && isTargetHiddenFromInstantApp));
6342                if (!blockResolution) {
6343                    final ResolveInfo ri = new ResolveInfo();
6344                    ri.activityInfo = ai;
6345                    list.add(ri);
6346                }
6347            }
6348            return applyPostResolutionFilter(
6349                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6350        }
6351
6352        // reader
6353        boolean sortResult = false;
6354        boolean addEphemeral = false;
6355        List<ResolveInfo> result;
6356        final boolean ephemeralDisabled = isEphemeralDisabled();
6357        synchronized (mPackages) {
6358            if (pkgName == null) {
6359                List<CrossProfileIntentFilter> matchingFilters =
6360                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6361                // Check for results that need to skip the current profile.
6362                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6363                        resolvedType, flags, userId);
6364                if (xpResolveInfo != null) {
6365                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6366                    xpResult.add(xpResolveInfo);
6367                    return applyPostResolutionFilter(
6368                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6369                            allowDynamicSplits, filterCallingUid, userId);
6370                }
6371
6372                // Check for results in the current profile.
6373                result = filterIfNotSystemUser(mActivities.queryIntent(
6374                        intent, resolvedType, flags, userId), userId);
6375                addEphemeral = !ephemeralDisabled
6376                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6377                // Check for cross profile results.
6378                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6379                xpResolveInfo = queryCrossProfileIntents(
6380                        matchingFilters, intent, resolvedType, flags, userId,
6381                        hasNonNegativePriorityResult);
6382                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6383                    boolean isVisibleToUser = filterIfNotSystemUser(
6384                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6385                    if (isVisibleToUser) {
6386                        result.add(xpResolveInfo);
6387                        sortResult = true;
6388                    }
6389                }
6390                if (hasWebURI(intent)) {
6391                    CrossProfileDomainInfo xpDomainInfo = null;
6392                    final UserInfo parent = getProfileParent(userId);
6393                    if (parent != null) {
6394                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6395                                flags, userId, parent.id);
6396                    }
6397                    if (xpDomainInfo != null) {
6398                        if (xpResolveInfo != null) {
6399                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6400                            // in the result.
6401                            result.remove(xpResolveInfo);
6402                        }
6403                        if (result.size() == 0 && !addEphemeral) {
6404                            // No result in current profile, but found candidate in parent user.
6405                            // And we are not going to add emphemeral app, so we can return the
6406                            // result straight away.
6407                            result.add(xpDomainInfo.resolveInfo);
6408                            return applyPostResolutionFilter(result, instantAppPkgName,
6409                                    allowDynamicSplits, filterCallingUid, userId);
6410                        }
6411                    } else if (result.size() <= 1 && !addEphemeral) {
6412                        // No result in parent user and <= 1 result in current profile, and we
6413                        // are not going to add emphemeral app, so we can return the result without
6414                        // further processing.
6415                        return applyPostResolutionFilter(result, instantAppPkgName,
6416                                allowDynamicSplits, filterCallingUid, userId);
6417                    }
6418                    // We have more than one candidate (combining results from current and parent
6419                    // profile), so we need filtering and sorting.
6420                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6421                            intent, flags, result, xpDomainInfo, userId);
6422                    sortResult = true;
6423                }
6424            } else {
6425                final PackageParser.Package pkg = mPackages.get(pkgName);
6426                result = null;
6427                if (pkg != null) {
6428                    result = filterIfNotSystemUser(
6429                            mActivities.queryIntentForPackage(
6430                                    intent, resolvedType, flags, pkg.activities, userId),
6431                            userId);
6432                }
6433                if (result == null || result.size() == 0) {
6434                    // the caller wants to resolve for a particular package; however, there
6435                    // were no installed results, so, try to find an ephemeral result
6436                    addEphemeral = !ephemeralDisabled
6437                            && isInstantAppAllowed(
6438                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6439                    if (result == null) {
6440                        result = new ArrayList<>();
6441                    }
6442                }
6443            }
6444        }
6445        if (addEphemeral) {
6446            result = maybeAddInstantAppInstaller(
6447                    result, intent, resolvedType, flags, userId, resolveForStart);
6448        }
6449        if (sortResult) {
6450            Collections.sort(result, mResolvePrioritySorter);
6451        }
6452        return applyPostResolutionFilter(
6453                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6454    }
6455
6456    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6457            String resolvedType, int flags, int userId, boolean resolveForStart) {
6458        // first, check to see if we've got an instant app already installed
6459        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6460        ResolveInfo localInstantApp = null;
6461        boolean blockResolution = false;
6462        if (!alreadyResolvedLocally) {
6463            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6464                    flags
6465                        | PackageManager.GET_RESOLVED_FILTER
6466                        | PackageManager.MATCH_INSTANT
6467                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6468                    userId);
6469            for (int i = instantApps.size() - 1; i >= 0; --i) {
6470                final ResolveInfo info = instantApps.get(i);
6471                final String packageName = info.activityInfo.packageName;
6472                final PackageSetting ps = mSettings.mPackages.get(packageName);
6473                if (ps.getInstantApp(userId)) {
6474                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6475                    final int status = (int)(packedStatus >> 32);
6476                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6477                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6478                        // there's a local instant application installed, but, the user has
6479                        // chosen to never use it; skip resolution and don't acknowledge
6480                        // an instant application is even available
6481                        if (DEBUG_EPHEMERAL) {
6482                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6483                        }
6484                        blockResolution = true;
6485                        break;
6486                    } else {
6487                        // we have a locally installed instant application; skip resolution
6488                        // but acknowledge there's an instant application available
6489                        if (DEBUG_EPHEMERAL) {
6490                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6491                        }
6492                        localInstantApp = info;
6493                        break;
6494                    }
6495                }
6496            }
6497        }
6498        // no app installed, let's see if one's available
6499        AuxiliaryResolveInfo auxiliaryResponse = null;
6500        if (!blockResolution) {
6501            if (localInstantApp == null) {
6502                // we don't have an instant app locally, resolve externally
6503                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6504                final InstantAppRequest requestObject = new InstantAppRequest(
6505                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6506                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6507                        resolveForStart);
6508                auxiliaryResponse =
6509                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6510                                mContext, mInstantAppResolverConnection, requestObject);
6511                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6512            } else {
6513                // we have an instant application locally, but, we can't admit that since
6514                // callers shouldn't be able to determine prior browsing. create a dummy
6515                // auxiliary response so the downstream code behaves as if there's an
6516                // instant application available externally. when it comes time to start
6517                // the instant application, we'll do the right thing.
6518                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6519                auxiliaryResponse = new AuxiliaryResolveInfo(
6520                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6521                        ai.versionCode, null /*failureIntent*/);
6522            }
6523        }
6524        if (auxiliaryResponse != null) {
6525            if (DEBUG_EPHEMERAL) {
6526                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6527            }
6528            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6529            final PackageSetting ps =
6530                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6531            if (ps != null) {
6532                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6533                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6534                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6535                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6536                // make sure this resolver is the default
6537                ephemeralInstaller.isDefault = true;
6538                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6539                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6540                // add a non-generic filter
6541                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6542                ephemeralInstaller.filter.addDataPath(
6543                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6544                ephemeralInstaller.isInstantAppAvailable = true;
6545                result.add(ephemeralInstaller);
6546            }
6547        }
6548        return result;
6549    }
6550
6551    private static class CrossProfileDomainInfo {
6552        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6553        ResolveInfo resolveInfo;
6554        /* Best domain verification status of the activities found in the other profile */
6555        int bestDomainVerificationStatus;
6556    }
6557
6558    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6559            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6560        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6561                sourceUserId)) {
6562            return null;
6563        }
6564        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6565                resolvedType, flags, parentUserId);
6566
6567        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6568            return null;
6569        }
6570        CrossProfileDomainInfo result = null;
6571        int size = resultTargetUser.size();
6572        for (int i = 0; i < size; i++) {
6573            ResolveInfo riTargetUser = resultTargetUser.get(i);
6574            // Intent filter verification is only for filters that specify a host. So don't return
6575            // those that handle all web uris.
6576            if (riTargetUser.handleAllWebDataURI) {
6577                continue;
6578            }
6579            String packageName = riTargetUser.activityInfo.packageName;
6580            PackageSetting ps = mSettings.mPackages.get(packageName);
6581            if (ps == null) {
6582                continue;
6583            }
6584            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6585            int status = (int)(verificationState >> 32);
6586            if (result == null) {
6587                result = new CrossProfileDomainInfo();
6588                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6589                        sourceUserId, parentUserId);
6590                result.bestDomainVerificationStatus = status;
6591            } else {
6592                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6593                        result.bestDomainVerificationStatus);
6594            }
6595        }
6596        // Don't consider matches with status NEVER across profiles.
6597        if (result != null && result.bestDomainVerificationStatus
6598                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6599            return null;
6600        }
6601        return result;
6602    }
6603
6604    /**
6605     * Verification statuses are ordered from the worse to the best, except for
6606     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6607     */
6608    private int bestDomainVerificationStatus(int status1, int status2) {
6609        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6610            return status2;
6611        }
6612        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6613            return status1;
6614        }
6615        return (int) MathUtils.max(status1, status2);
6616    }
6617
6618    private boolean isUserEnabled(int userId) {
6619        long callingId = Binder.clearCallingIdentity();
6620        try {
6621            UserInfo userInfo = sUserManager.getUserInfo(userId);
6622            return userInfo != null && userInfo.isEnabled();
6623        } finally {
6624            Binder.restoreCallingIdentity(callingId);
6625        }
6626    }
6627
6628    /**
6629     * Filter out activities with systemUserOnly flag set, when current user is not System.
6630     *
6631     * @return filtered list
6632     */
6633    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6634        if (userId == UserHandle.USER_SYSTEM) {
6635            return resolveInfos;
6636        }
6637        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6638            ResolveInfo info = resolveInfos.get(i);
6639            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6640                resolveInfos.remove(i);
6641            }
6642        }
6643        return resolveInfos;
6644    }
6645
6646    /**
6647     * Filters out ephemeral activities.
6648     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6649     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6650     *
6651     * @param resolveInfos The pre-filtered list of resolved activities
6652     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6653     *          is performed.
6654     * @return A filtered list of resolved activities.
6655     */
6656    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6657            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6658        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6659            final ResolveInfo info = resolveInfos.get(i);
6660            // allow activities that are defined in the provided package
6661            if (allowDynamicSplits
6662                    && info.activityInfo.splitName != null
6663                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6664                            info.activityInfo.splitName)) {
6665                if (mInstantAppInstallerInfo == null) {
6666                    if (DEBUG_INSTALL) {
6667                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6668                    }
6669                    resolveInfos.remove(i);
6670                    continue;
6671                }
6672                // requested activity is defined in a split that hasn't been installed yet.
6673                // add the installer to the resolve list
6674                if (DEBUG_INSTALL) {
6675                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6676                }
6677                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6678                final ComponentName installFailureActivity = findInstallFailureActivity(
6679                        info.activityInfo.packageName,  filterCallingUid, userId);
6680                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6681                        info.activityInfo.packageName, info.activityInfo.splitName,
6682                        installFailureActivity,
6683                        info.activityInfo.applicationInfo.versionCode,
6684                        null /*failureIntent*/);
6685                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6686                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6687                // add a non-generic filter
6688                installerInfo.filter = new IntentFilter();
6689
6690                // This resolve info may appear in the chooser UI, so let us make it
6691                // look as the one it replaces as far as the user is concerned which
6692                // requires loading the correct label and icon for the resolve info.
6693                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6694                installerInfo.labelRes = info.resolveLabelResId();
6695                installerInfo.icon = info.resolveIconResId();
6696
6697                // propagate priority/preferred order/default
6698                installerInfo.priority = info.priority;
6699                installerInfo.preferredOrder = info.preferredOrder;
6700                installerInfo.isDefault = info.isDefault;
6701                resolveInfos.set(i, installerInfo);
6702                continue;
6703            }
6704            // caller is a full app, don't need to apply any other filtering
6705            if (ephemeralPkgName == null) {
6706                continue;
6707            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6708                // caller is same app; don't need to apply any other filtering
6709                continue;
6710            }
6711            // allow activities that have been explicitly exposed to ephemeral apps
6712            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6713            if (!isEphemeralApp
6714                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6715                continue;
6716            }
6717            resolveInfos.remove(i);
6718        }
6719        return resolveInfos;
6720    }
6721
6722    /**
6723     * Returns the activity component that can handle install failures.
6724     * <p>By default, the instant application installer handles failures. However, an
6725     * application may want to handle failures on its own. Applications do this by
6726     * creating an activity with an intent filter that handles the action
6727     * {@link Intent#ACTION_INSTALL_FAILURE}.
6728     */
6729    private @Nullable ComponentName findInstallFailureActivity(
6730            String packageName, int filterCallingUid, int userId) {
6731        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6732        failureActivityIntent.setPackage(packageName);
6733        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6734        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6735                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6736                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6737        final int NR = result.size();
6738        if (NR > 0) {
6739            for (int i = 0; i < NR; i++) {
6740                final ResolveInfo info = result.get(i);
6741                if (info.activityInfo.splitName != null) {
6742                    continue;
6743                }
6744                return new ComponentName(packageName, info.activityInfo.name);
6745            }
6746        }
6747        return null;
6748    }
6749
6750    /**
6751     * @param resolveInfos list of resolve infos in descending priority order
6752     * @return if the list contains a resolve info with non-negative priority
6753     */
6754    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6755        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6756    }
6757
6758    private static boolean hasWebURI(Intent intent) {
6759        if (intent.getData() == null) {
6760            return false;
6761        }
6762        final String scheme = intent.getScheme();
6763        if (TextUtils.isEmpty(scheme)) {
6764            return false;
6765        }
6766        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6767    }
6768
6769    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6770            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6771            int userId) {
6772        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6773
6774        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6775            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6776                    candidates.size());
6777        }
6778
6779        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6780        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6781        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6782        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6783        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6784        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6785
6786        synchronized (mPackages) {
6787            final int count = candidates.size();
6788            // First, try to use linked apps. Partition the candidates into four lists:
6789            // one for the final results, one for the "do not use ever", one for "undefined status"
6790            // and finally one for "browser app type".
6791            for (int n=0; n<count; n++) {
6792                ResolveInfo info = candidates.get(n);
6793                String packageName = info.activityInfo.packageName;
6794                PackageSetting ps = mSettings.mPackages.get(packageName);
6795                if (ps != null) {
6796                    // Add to the special match all list (Browser use case)
6797                    if (info.handleAllWebDataURI) {
6798                        matchAllList.add(info);
6799                        continue;
6800                    }
6801                    // Try to get the status from User settings first
6802                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6803                    int status = (int)(packedStatus >> 32);
6804                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6805                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6806                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6807                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6808                                    + " : linkgen=" + linkGeneration);
6809                        }
6810                        // Use link-enabled generation as preferredOrder, i.e.
6811                        // prefer newly-enabled over earlier-enabled.
6812                        info.preferredOrder = linkGeneration;
6813                        alwaysList.add(info);
6814                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6815                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6816                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6817                        }
6818                        neverList.add(info);
6819                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6820                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6821                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6822                        }
6823                        alwaysAskList.add(info);
6824                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6825                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6826                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6827                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6828                        }
6829                        undefinedList.add(info);
6830                    }
6831                }
6832            }
6833
6834            // We'll want to include browser possibilities in a few cases
6835            boolean includeBrowser = false;
6836
6837            // First try to add the "always" resolution(s) for the current user, if any
6838            if (alwaysList.size() > 0) {
6839                result.addAll(alwaysList);
6840            } else {
6841                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6842                result.addAll(undefinedList);
6843                // Maybe add one for the other profile.
6844                if (xpDomainInfo != null && (
6845                        xpDomainInfo.bestDomainVerificationStatus
6846                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6847                    result.add(xpDomainInfo.resolveInfo);
6848                }
6849                includeBrowser = true;
6850            }
6851
6852            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6853            // If there were 'always' entries their preferred order has been set, so we also
6854            // back that off to make the alternatives equivalent
6855            if (alwaysAskList.size() > 0) {
6856                for (ResolveInfo i : result) {
6857                    i.preferredOrder = 0;
6858                }
6859                result.addAll(alwaysAskList);
6860                includeBrowser = true;
6861            }
6862
6863            if (includeBrowser) {
6864                // Also add browsers (all of them or only the default one)
6865                if (DEBUG_DOMAIN_VERIFICATION) {
6866                    Slog.v(TAG, "   ...including browsers in candidate set");
6867                }
6868                if ((matchFlags & MATCH_ALL) != 0) {
6869                    result.addAll(matchAllList);
6870                } else {
6871                    // Browser/generic handling case.  If there's a default browser, go straight
6872                    // to that (but only if there is no other higher-priority match).
6873                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6874                    int maxMatchPrio = 0;
6875                    ResolveInfo defaultBrowserMatch = null;
6876                    final int numCandidates = matchAllList.size();
6877                    for (int n = 0; n < numCandidates; n++) {
6878                        ResolveInfo info = matchAllList.get(n);
6879                        // track the highest overall match priority...
6880                        if (info.priority > maxMatchPrio) {
6881                            maxMatchPrio = info.priority;
6882                        }
6883                        // ...and the highest-priority default browser match
6884                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6885                            if (defaultBrowserMatch == null
6886                                    || (defaultBrowserMatch.priority < info.priority)) {
6887                                if (debug) {
6888                                    Slog.v(TAG, "Considering default browser match " + info);
6889                                }
6890                                defaultBrowserMatch = info;
6891                            }
6892                        }
6893                    }
6894                    if (defaultBrowserMatch != null
6895                            && defaultBrowserMatch.priority >= maxMatchPrio
6896                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6897                    {
6898                        if (debug) {
6899                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6900                        }
6901                        result.add(defaultBrowserMatch);
6902                    } else {
6903                        result.addAll(matchAllList);
6904                    }
6905                }
6906
6907                // If there is nothing selected, add all candidates and remove the ones that the user
6908                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6909                if (result.size() == 0) {
6910                    result.addAll(candidates);
6911                    result.removeAll(neverList);
6912                }
6913            }
6914        }
6915        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6916            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6917                    result.size());
6918            for (ResolveInfo info : result) {
6919                Slog.v(TAG, "  + " + info.activityInfo);
6920            }
6921        }
6922        return result;
6923    }
6924
6925    // Returns a packed value as a long:
6926    //
6927    // high 'int'-sized word: link status: undefined/ask/never/always.
6928    // low 'int'-sized word: relative priority among 'always' results.
6929    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6930        long result = ps.getDomainVerificationStatusForUser(userId);
6931        // if none available, get the master status
6932        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6933            if (ps.getIntentFilterVerificationInfo() != null) {
6934                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6935            }
6936        }
6937        return result;
6938    }
6939
6940    private ResolveInfo querySkipCurrentProfileIntents(
6941            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6942            int flags, int sourceUserId) {
6943        if (matchingFilters != null) {
6944            int size = matchingFilters.size();
6945            for (int i = 0; i < size; i ++) {
6946                CrossProfileIntentFilter filter = matchingFilters.get(i);
6947                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6948                    // Checking if there are activities in the target user that can handle the
6949                    // intent.
6950                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6951                            resolvedType, flags, sourceUserId);
6952                    if (resolveInfo != null) {
6953                        return resolveInfo;
6954                    }
6955                }
6956            }
6957        }
6958        return null;
6959    }
6960
6961    // Return matching ResolveInfo in target user if any.
6962    private ResolveInfo queryCrossProfileIntents(
6963            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6964            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6965        if (matchingFilters != null) {
6966            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6967            // match the same intent. For performance reasons, it is better not to
6968            // run queryIntent twice for the same userId
6969            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6970            int size = matchingFilters.size();
6971            for (int i = 0; i < size; i++) {
6972                CrossProfileIntentFilter filter = matchingFilters.get(i);
6973                int targetUserId = filter.getTargetUserId();
6974                boolean skipCurrentProfile =
6975                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6976                boolean skipCurrentProfileIfNoMatchFound =
6977                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6978                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6979                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6980                    // Checking if there are activities in the target user that can handle the
6981                    // intent.
6982                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6983                            resolvedType, flags, sourceUserId);
6984                    if (resolveInfo != null) return resolveInfo;
6985                    alreadyTriedUserIds.put(targetUserId, true);
6986                }
6987            }
6988        }
6989        return null;
6990    }
6991
6992    /**
6993     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6994     * will forward the intent to the filter's target user.
6995     * Otherwise, returns null.
6996     */
6997    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6998            String resolvedType, int flags, int sourceUserId) {
6999        int targetUserId = filter.getTargetUserId();
7000        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7001                resolvedType, flags, targetUserId);
7002        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7003            // If all the matches in the target profile are suspended, return null.
7004            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7005                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7006                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7007                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7008                            targetUserId);
7009                }
7010            }
7011        }
7012        return null;
7013    }
7014
7015    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7016            int sourceUserId, int targetUserId) {
7017        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7018        long ident = Binder.clearCallingIdentity();
7019        boolean targetIsProfile;
7020        try {
7021            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7022        } finally {
7023            Binder.restoreCallingIdentity(ident);
7024        }
7025        String className;
7026        if (targetIsProfile) {
7027            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7028        } else {
7029            className = FORWARD_INTENT_TO_PARENT;
7030        }
7031        ComponentName forwardingActivityComponentName = new ComponentName(
7032                mAndroidApplication.packageName, className);
7033        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7034                sourceUserId);
7035        if (!targetIsProfile) {
7036            forwardingActivityInfo.showUserIcon = targetUserId;
7037            forwardingResolveInfo.noResourceId = true;
7038        }
7039        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7040        forwardingResolveInfo.priority = 0;
7041        forwardingResolveInfo.preferredOrder = 0;
7042        forwardingResolveInfo.match = 0;
7043        forwardingResolveInfo.isDefault = true;
7044        forwardingResolveInfo.filter = filter;
7045        forwardingResolveInfo.targetUserId = targetUserId;
7046        return forwardingResolveInfo;
7047    }
7048
7049    @Override
7050    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7051            Intent[] specifics, String[] specificTypes, Intent intent,
7052            String resolvedType, int flags, int userId) {
7053        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7054                specificTypes, intent, resolvedType, flags, userId));
7055    }
7056
7057    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7058            Intent[] specifics, String[] specificTypes, Intent intent,
7059            String resolvedType, int flags, int userId) {
7060        if (!sUserManager.exists(userId)) return Collections.emptyList();
7061        final int callingUid = Binder.getCallingUid();
7062        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7063                false /*includeInstantApps*/);
7064        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7065                false /*requireFullPermission*/, false /*checkShell*/,
7066                "query intent activity options");
7067        final String resultsAction = intent.getAction();
7068
7069        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7070                | PackageManager.GET_RESOLVED_FILTER, userId);
7071
7072        if (DEBUG_INTENT_MATCHING) {
7073            Log.v(TAG, "Query " + intent + ": " + results);
7074        }
7075
7076        int specificsPos = 0;
7077        int N;
7078
7079        // todo: note that the algorithm used here is O(N^2).  This
7080        // isn't a problem in our current environment, but if we start running
7081        // into situations where we have more than 5 or 10 matches then this
7082        // should probably be changed to something smarter...
7083
7084        // First we go through and resolve each of the specific items
7085        // that were supplied, taking care of removing any corresponding
7086        // duplicate items in the generic resolve list.
7087        if (specifics != null) {
7088            for (int i=0; i<specifics.length; i++) {
7089                final Intent sintent = specifics[i];
7090                if (sintent == null) {
7091                    continue;
7092                }
7093
7094                if (DEBUG_INTENT_MATCHING) {
7095                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7096                }
7097
7098                String action = sintent.getAction();
7099                if (resultsAction != null && resultsAction.equals(action)) {
7100                    // If this action was explicitly requested, then don't
7101                    // remove things that have it.
7102                    action = null;
7103                }
7104
7105                ResolveInfo ri = null;
7106                ActivityInfo ai = null;
7107
7108                ComponentName comp = sintent.getComponent();
7109                if (comp == null) {
7110                    ri = resolveIntent(
7111                        sintent,
7112                        specificTypes != null ? specificTypes[i] : null,
7113                            flags, userId);
7114                    if (ri == null) {
7115                        continue;
7116                    }
7117                    if (ri == mResolveInfo) {
7118                        // ACK!  Must do something better with this.
7119                    }
7120                    ai = ri.activityInfo;
7121                    comp = new ComponentName(ai.applicationInfo.packageName,
7122                            ai.name);
7123                } else {
7124                    ai = getActivityInfo(comp, flags, userId);
7125                    if (ai == null) {
7126                        continue;
7127                    }
7128                }
7129
7130                // Look for any generic query activities that are duplicates
7131                // of this specific one, and remove them from the results.
7132                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7133                N = results.size();
7134                int j;
7135                for (j=specificsPos; j<N; j++) {
7136                    ResolveInfo sri = results.get(j);
7137                    if ((sri.activityInfo.name.equals(comp.getClassName())
7138                            && sri.activityInfo.applicationInfo.packageName.equals(
7139                                    comp.getPackageName()))
7140                        || (action != null && sri.filter.matchAction(action))) {
7141                        results.remove(j);
7142                        if (DEBUG_INTENT_MATCHING) Log.v(
7143                            TAG, "Removing duplicate item from " + j
7144                            + " due to specific " + specificsPos);
7145                        if (ri == null) {
7146                            ri = sri;
7147                        }
7148                        j--;
7149                        N--;
7150                    }
7151                }
7152
7153                // Add this specific item to its proper place.
7154                if (ri == null) {
7155                    ri = new ResolveInfo();
7156                    ri.activityInfo = ai;
7157                }
7158                results.add(specificsPos, ri);
7159                ri.specificIndex = i;
7160                specificsPos++;
7161            }
7162        }
7163
7164        // Now we go through the remaining generic results and remove any
7165        // duplicate actions that are found here.
7166        N = results.size();
7167        for (int i=specificsPos; i<N-1; i++) {
7168            final ResolveInfo rii = results.get(i);
7169            if (rii.filter == null) {
7170                continue;
7171            }
7172
7173            // Iterate over all of the actions of this result's intent
7174            // filter...  typically this should be just one.
7175            final Iterator<String> it = rii.filter.actionsIterator();
7176            if (it == null) {
7177                continue;
7178            }
7179            while (it.hasNext()) {
7180                final String action = it.next();
7181                if (resultsAction != null && resultsAction.equals(action)) {
7182                    // If this action was explicitly requested, then don't
7183                    // remove things that have it.
7184                    continue;
7185                }
7186                for (int j=i+1; j<N; j++) {
7187                    final ResolveInfo rij = results.get(j);
7188                    if (rij.filter != null && rij.filter.hasAction(action)) {
7189                        results.remove(j);
7190                        if (DEBUG_INTENT_MATCHING) Log.v(
7191                            TAG, "Removing duplicate item from " + j
7192                            + " due to action " + action + " at " + i);
7193                        j--;
7194                        N--;
7195                    }
7196                }
7197            }
7198
7199            // If the caller didn't request filter information, drop it now
7200            // so we don't have to marshall/unmarshall it.
7201            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7202                rii.filter = null;
7203            }
7204        }
7205
7206        // Filter out the caller activity if so requested.
7207        if (caller != null) {
7208            N = results.size();
7209            for (int i=0; i<N; i++) {
7210                ActivityInfo ainfo = results.get(i).activityInfo;
7211                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7212                        && caller.getClassName().equals(ainfo.name)) {
7213                    results.remove(i);
7214                    break;
7215                }
7216            }
7217        }
7218
7219        // If the caller didn't request filter information,
7220        // drop them now so we don't have to
7221        // marshall/unmarshall it.
7222        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7223            N = results.size();
7224            for (int i=0; i<N; i++) {
7225                results.get(i).filter = null;
7226            }
7227        }
7228
7229        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7230        return results;
7231    }
7232
7233    @Override
7234    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7235            String resolvedType, int flags, int userId) {
7236        return new ParceledListSlice<>(
7237                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7238                        false /*allowDynamicSplits*/));
7239    }
7240
7241    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7242            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7243        if (!sUserManager.exists(userId)) return Collections.emptyList();
7244        final int callingUid = Binder.getCallingUid();
7245        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7246                false /*requireFullPermission*/, false /*checkShell*/,
7247                "query intent receivers");
7248        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7249        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7250                false /*includeInstantApps*/);
7251        ComponentName comp = intent.getComponent();
7252        if (comp == null) {
7253            if (intent.getSelector() != null) {
7254                intent = intent.getSelector();
7255                comp = intent.getComponent();
7256            }
7257        }
7258        if (comp != null) {
7259            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7260            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7261            if (ai != null) {
7262                // When specifying an explicit component, we prevent the activity from being
7263                // used when either 1) the calling package is normal and the activity is within
7264                // an instant application or 2) the calling package is ephemeral and the
7265                // activity is not visible to instant applications.
7266                final boolean matchInstantApp =
7267                        (flags & PackageManager.MATCH_INSTANT) != 0;
7268                final boolean matchVisibleToInstantAppOnly =
7269                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7270                final boolean matchExplicitlyVisibleOnly =
7271                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7272                final boolean isCallerInstantApp =
7273                        instantAppPkgName != null;
7274                final boolean isTargetSameInstantApp =
7275                        comp.getPackageName().equals(instantAppPkgName);
7276                final boolean isTargetInstantApp =
7277                        (ai.applicationInfo.privateFlags
7278                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7279                final boolean isTargetVisibleToInstantApp =
7280                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7281                final boolean isTargetExplicitlyVisibleToInstantApp =
7282                        isTargetVisibleToInstantApp
7283                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7284                final boolean isTargetHiddenFromInstantApp =
7285                        !isTargetVisibleToInstantApp
7286                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7287                final boolean blockResolution =
7288                        !isTargetSameInstantApp
7289                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7290                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7291                                        && isTargetHiddenFromInstantApp));
7292                if (!blockResolution) {
7293                    ResolveInfo ri = new ResolveInfo();
7294                    ri.activityInfo = ai;
7295                    list.add(ri);
7296                }
7297            }
7298            return applyPostResolutionFilter(
7299                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7300        }
7301
7302        // reader
7303        synchronized (mPackages) {
7304            String pkgName = intent.getPackage();
7305            if (pkgName == null) {
7306                final List<ResolveInfo> result =
7307                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7308                return applyPostResolutionFilter(
7309                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7310            }
7311            final PackageParser.Package pkg = mPackages.get(pkgName);
7312            if (pkg != null) {
7313                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7314                        intent, resolvedType, flags, pkg.receivers, userId);
7315                return applyPostResolutionFilter(
7316                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7317            }
7318            return Collections.emptyList();
7319        }
7320    }
7321
7322    @Override
7323    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7324        final int callingUid = Binder.getCallingUid();
7325        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7326    }
7327
7328    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7329            int userId, int callingUid) {
7330        if (!sUserManager.exists(userId)) return null;
7331        flags = updateFlagsForResolve(
7332                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7333        List<ResolveInfo> query = queryIntentServicesInternal(
7334                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7335        if (query != null) {
7336            if (query.size() >= 1) {
7337                // If there is more than one service with the same priority,
7338                // just arbitrarily pick the first one.
7339                return query.get(0);
7340            }
7341        }
7342        return null;
7343    }
7344
7345    @Override
7346    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7347            String resolvedType, int flags, int userId) {
7348        final int callingUid = Binder.getCallingUid();
7349        return new ParceledListSlice<>(queryIntentServicesInternal(
7350                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7351    }
7352
7353    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7354            String resolvedType, int flags, int userId, int callingUid,
7355            boolean includeInstantApps) {
7356        if (!sUserManager.exists(userId)) return Collections.emptyList();
7357        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7358                false /*requireFullPermission*/, false /*checkShell*/,
7359                "query intent receivers");
7360        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7361        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7362        ComponentName comp = intent.getComponent();
7363        if (comp == null) {
7364            if (intent.getSelector() != null) {
7365                intent = intent.getSelector();
7366                comp = intent.getComponent();
7367            }
7368        }
7369        if (comp != null) {
7370            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7371            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7372            if (si != null) {
7373                // When specifying an explicit component, we prevent the service from being
7374                // used when either 1) the service is in an instant application and the
7375                // caller is not the same instant application or 2) the calling package is
7376                // ephemeral and the activity is not visible to ephemeral applications.
7377                final boolean matchInstantApp =
7378                        (flags & PackageManager.MATCH_INSTANT) != 0;
7379                final boolean matchVisibleToInstantAppOnly =
7380                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7381                final boolean isCallerInstantApp =
7382                        instantAppPkgName != null;
7383                final boolean isTargetSameInstantApp =
7384                        comp.getPackageName().equals(instantAppPkgName);
7385                final boolean isTargetInstantApp =
7386                        (si.applicationInfo.privateFlags
7387                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7388                final boolean isTargetHiddenFromInstantApp =
7389                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7390                final boolean blockResolution =
7391                        !isTargetSameInstantApp
7392                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7393                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7394                                        && isTargetHiddenFromInstantApp));
7395                if (!blockResolution) {
7396                    final ResolveInfo ri = new ResolveInfo();
7397                    ri.serviceInfo = si;
7398                    list.add(ri);
7399                }
7400            }
7401            return list;
7402        }
7403
7404        // reader
7405        synchronized (mPackages) {
7406            String pkgName = intent.getPackage();
7407            if (pkgName == null) {
7408                return applyPostServiceResolutionFilter(
7409                        mServices.queryIntent(intent, resolvedType, flags, userId),
7410                        instantAppPkgName);
7411            }
7412            final PackageParser.Package pkg = mPackages.get(pkgName);
7413            if (pkg != null) {
7414                return applyPostServiceResolutionFilter(
7415                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7416                                userId),
7417                        instantAppPkgName);
7418            }
7419            return Collections.emptyList();
7420        }
7421    }
7422
7423    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7424            String instantAppPkgName) {
7425        if (instantAppPkgName == null) {
7426            return resolveInfos;
7427        }
7428        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7429            final ResolveInfo info = resolveInfos.get(i);
7430            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7431            // allow services that are defined in the provided package
7432            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7433                if (info.serviceInfo.splitName != null
7434                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7435                                info.serviceInfo.splitName)) {
7436                    // requested service is defined in a split that hasn't been installed yet.
7437                    // add the installer to the resolve list
7438                    if (DEBUG_EPHEMERAL) {
7439                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7440                    }
7441                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7442                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7443                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7444                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7445                            null /*failureIntent*/);
7446                    // make sure this resolver is the default
7447                    installerInfo.isDefault = true;
7448                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7449                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7450                    // add a non-generic filter
7451                    installerInfo.filter = new IntentFilter();
7452                    // load resources from the correct package
7453                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7454                    resolveInfos.set(i, installerInfo);
7455                }
7456                continue;
7457            }
7458            // allow services that have been explicitly exposed to ephemeral apps
7459            if (!isEphemeralApp
7460                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7461                continue;
7462            }
7463            resolveInfos.remove(i);
7464        }
7465        return resolveInfos;
7466    }
7467
7468    @Override
7469    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7470            String resolvedType, int flags, int userId) {
7471        return new ParceledListSlice<>(
7472                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7473    }
7474
7475    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7476            Intent intent, String resolvedType, int flags, int userId) {
7477        if (!sUserManager.exists(userId)) return Collections.emptyList();
7478        final int callingUid = Binder.getCallingUid();
7479        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7480        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7481                false /*includeInstantApps*/);
7482        ComponentName comp = intent.getComponent();
7483        if (comp == null) {
7484            if (intent.getSelector() != null) {
7485                intent = intent.getSelector();
7486                comp = intent.getComponent();
7487            }
7488        }
7489        if (comp != null) {
7490            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7491            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7492            if (pi != null) {
7493                // When specifying an explicit component, we prevent the provider from being
7494                // used when either 1) the provider is in an instant application and the
7495                // caller is not the same instant application or 2) the calling package is an
7496                // instant application and the provider is not visible to instant applications.
7497                final boolean matchInstantApp =
7498                        (flags & PackageManager.MATCH_INSTANT) != 0;
7499                final boolean matchVisibleToInstantAppOnly =
7500                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7501                final boolean isCallerInstantApp =
7502                        instantAppPkgName != null;
7503                final boolean isTargetSameInstantApp =
7504                        comp.getPackageName().equals(instantAppPkgName);
7505                final boolean isTargetInstantApp =
7506                        (pi.applicationInfo.privateFlags
7507                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7508                final boolean isTargetHiddenFromInstantApp =
7509                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7510                final boolean blockResolution =
7511                        !isTargetSameInstantApp
7512                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7513                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7514                                        && isTargetHiddenFromInstantApp));
7515                if (!blockResolution) {
7516                    final ResolveInfo ri = new ResolveInfo();
7517                    ri.providerInfo = pi;
7518                    list.add(ri);
7519                }
7520            }
7521            return list;
7522        }
7523
7524        // reader
7525        synchronized (mPackages) {
7526            String pkgName = intent.getPackage();
7527            if (pkgName == null) {
7528                return applyPostContentProviderResolutionFilter(
7529                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7530                        instantAppPkgName);
7531            }
7532            final PackageParser.Package pkg = mPackages.get(pkgName);
7533            if (pkg != null) {
7534                return applyPostContentProviderResolutionFilter(
7535                        mProviders.queryIntentForPackage(
7536                        intent, resolvedType, flags, pkg.providers, userId),
7537                        instantAppPkgName);
7538            }
7539            return Collections.emptyList();
7540        }
7541    }
7542
7543    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7544            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7545        if (instantAppPkgName == null) {
7546            return resolveInfos;
7547        }
7548        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7549            final ResolveInfo info = resolveInfos.get(i);
7550            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7551            // allow providers that are defined in the provided package
7552            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7553                if (info.providerInfo.splitName != null
7554                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7555                                info.providerInfo.splitName)) {
7556                    // requested provider is defined in a split that hasn't been installed yet.
7557                    // add the installer to the resolve list
7558                    if (DEBUG_EPHEMERAL) {
7559                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7560                    }
7561                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7562                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7563                            info.providerInfo.packageName, info.providerInfo.splitName,
7564                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7565                            null /*failureIntent*/);
7566                    // make sure this resolver is the default
7567                    installerInfo.isDefault = true;
7568                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7569                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7570                    // add a non-generic filter
7571                    installerInfo.filter = new IntentFilter();
7572                    // load resources from the correct package
7573                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7574                    resolveInfos.set(i, installerInfo);
7575                }
7576                continue;
7577            }
7578            // allow providers that have been explicitly exposed to instant applications
7579            if (!isEphemeralApp
7580                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7581                continue;
7582            }
7583            resolveInfos.remove(i);
7584        }
7585        return resolveInfos;
7586    }
7587
7588    @Override
7589    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7590        final int callingUid = Binder.getCallingUid();
7591        if (getInstantAppPackageName(callingUid) != null) {
7592            return ParceledListSlice.emptyList();
7593        }
7594        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7595        flags = updateFlagsForPackage(flags, userId, null);
7596        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7597        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7598                true /* requireFullPermission */, false /* checkShell */,
7599                "get installed packages");
7600
7601        // writer
7602        synchronized (mPackages) {
7603            ArrayList<PackageInfo> list;
7604            if (listUninstalled) {
7605                list = new ArrayList<>(mSettings.mPackages.size());
7606                for (PackageSetting ps : mSettings.mPackages.values()) {
7607                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7608                        continue;
7609                    }
7610                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7611                        continue;
7612                    }
7613                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7614                    if (pi != null) {
7615                        list.add(pi);
7616                    }
7617                }
7618            } else {
7619                list = new ArrayList<>(mPackages.size());
7620                for (PackageParser.Package p : mPackages.values()) {
7621                    final PackageSetting ps = (PackageSetting) p.mExtras;
7622                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7623                        continue;
7624                    }
7625                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7626                        continue;
7627                    }
7628                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7629                            p.mExtras, flags, userId);
7630                    if (pi != null) {
7631                        list.add(pi);
7632                    }
7633                }
7634            }
7635
7636            return new ParceledListSlice<>(list);
7637        }
7638    }
7639
7640    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7641            String[] permissions, boolean[] tmp, int flags, int userId) {
7642        int numMatch = 0;
7643        final PermissionsState permissionsState = ps.getPermissionsState();
7644        for (int i=0; i<permissions.length; i++) {
7645            final String permission = permissions[i];
7646            if (permissionsState.hasPermission(permission, userId)) {
7647                tmp[i] = true;
7648                numMatch++;
7649            } else {
7650                tmp[i] = false;
7651            }
7652        }
7653        if (numMatch == 0) {
7654            return;
7655        }
7656        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7657
7658        // The above might return null in cases of uninstalled apps or install-state
7659        // skew across users/profiles.
7660        if (pi != null) {
7661            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7662                if (numMatch == permissions.length) {
7663                    pi.requestedPermissions = permissions;
7664                } else {
7665                    pi.requestedPermissions = new String[numMatch];
7666                    numMatch = 0;
7667                    for (int i=0; i<permissions.length; i++) {
7668                        if (tmp[i]) {
7669                            pi.requestedPermissions[numMatch] = permissions[i];
7670                            numMatch++;
7671                        }
7672                    }
7673                }
7674            }
7675            list.add(pi);
7676        }
7677    }
7678
7679    @Override
7680    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7681            String[] permissions, int flags, int userId) {
7682        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7683        flags = updateFlagsForPackage(flags, userId, permissions);
7684        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7685                true /* requireFullPermission */, false /* checkShell */,
7686                "get packages holding permissions");
7687        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7688
7689        // writer
7690        synchronized (mPackages) {
7691            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7692            boolean[] tmpBools = new boolean[permissions.length];
7693            if (listUninstalled) {
7694                for (PackageSetting ps : mSettings.mPackages.values()) {
7695                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7696                            userId);
7697                }
7698            } else {
7699                for (PackageParser.Package pkg : mPackages.values()) {
7700                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7701                    if (ps != null) {
7702                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7703                                userId);
7704                    }
7705                }
7706            }
7707
7708            return new ParceledListSlice<PackageInfo>(list);
7709        }
7710    }
7711
7712    @Override
7713    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7714        final int callingUid = Binder.getCallingUid();
7715        if (getInstantAppPackageName(callingUid) != null) {
7716            return ParceledListSlice.emptyList();
7717        }
7718        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7719        flags = updateFlagsForApplication(flags, userId, null);
7720        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7721
7722        // writer
7723        synchronized (mPackages) {
7724            ArrayList<ApplicationInfo> list;
7725            if (listUninstalled) {
7726                list = new ArrayList<>(mSettings.mPackages.size());
7727                for (PackageSetting ps : mSettings.mPackages.values()) {
7728                    ApplicationInfo ai;
7729                    int effectiveFlags = flags;
7730                    if (ps.isSystem()) {
7731                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7732                    }
7733                    if (ps.pkg != null) {
7734                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7735                            continue;
7736                        }
7737                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7738                            continue;
7739                        }
7740                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7741                                ps.readUserState(userId), userId);
7742                        if (ai != null) {
7743                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7744                        }
7745                    } else {
7746                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7747                        // and already converts to externally visible package name
7748                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7749                                callingUid, effectiveFlags, userId);
7750                    }
7751                    if (ai != null) {
7752                        list.add(ai);
7753                    }
7754                }
7755            } else {
7756                list = new ArrayList<>(mPackages.size());
7757                for (PackageParser.Package p : mPackages.values()) {
7758                    if (p.mExtras != null) {
7759                        PackageSetting ps = (PackageSetting) p.mExtras;
7760                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7761                            continue;
7762                        }
7763                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7764                            continue;
7765                        }
7766                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7767                                ps.readUserState(userId), userId);
7768                        if (ai != null) {
7769                            ai.packageName = resolveExternalPackageNameLPr(p);
7770                            list.add(ai);
7771                        }
7772                    }
7773                }
7774            }
7775
7776            return new ParceledListSlice<>(list);
7777        }
7778    }
7779
7780    @Override
7781    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7782        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7783            return null;
7784        }
7785        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7786            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7787                    "getEphemeralApplications");
7788        }
7789        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7790                true /* requireFullPermission */, false /* checkShell */,
7791                "getEphemeralApplications");
7792        synchronized (mPackages) {
7793            List<InstantAppInfo> instantApps = mInstantAppRegistry
7794                    .getInstantAppsLPr(userId);
7795            if (instantApps != null) {
7796                return new ParceledListSlice<>(instantApps);
7797            }
7798        }
7799        return null;
7800    }
7801
7802    @Override
7803    public boolean isInstantApp(String packageName, int userId) {
7804        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7805                true /* requireFullPermission */, false /* checkShell */,
7806                "isInstantApp");
7807        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7808            return false;
7809        }
7810
7811        synchronized (mPackages) {
7812            int callingUid = Binder.getCallingUid();
7813            if (Process.isIsolated(callingUid)) {
7814                callingUid = mIsolatedOwners.get(callingUid);
7815            }
7816            final PackageSetting ps = mSettings.mPackages.get(packageName);
7817            PackageParser.Package pkg = mPackages.get(packageName);
7818            final boolean returnAllowed =
7819                    ps != null
7820                    && (isCallerSameApp(packageName, callingUid)
7821                            || canViewInstantApps(callingUid, userId)
7822                            || mInstantAppRegistry.isInstantAccessGranted(
7823                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7824            if (returnAllowed) {
7825                return ps.getInstantApp(userId);
7826            }
7827        }
7828        return false;
7829    }
7830
7831    @Override
7832    public byte[] getInstantAppCookie(String packageName, int userId) {
7833        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7834            return null;
7835        }
7836
7837        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7838                true /* requireFullPermission */, false /* checkShell */,
7839                "getInstantAppCookie");
7840        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7841            return null;
7842        }
7843        synchronized (mPackages) {
7844            return mInstantAppRegistry.getInstantAppCookieLPw(
7845                    packageName, userId);
7846        }
7847    }
7848
7849    @Override
7850    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7851        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7852            return true;
7853        }
7854
7855        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7856                true /* requireFullPermission */, true /* checkShell */,
7857                "setInstantAppCookie");
7858        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7859            return false;
7860        }
7861        synchronized (mPackages) {
7862            return mInstantAppRegistry.setInstantAppCookieLPw(
7863                    packageName, cookie, userId);
7864        }
7865    }
7866
7867    @Override
7868    public Bitmap getInstantAppIcon(String packageName, int userId) {
7869        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7870            return null;
7871        }
7872
7873        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7874            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7875                    "getInstantAppIcon");
7876        }
7877        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7878                true /* requireFullPermission */, false /* checkShell */,
7879                "getInstantAppIcon");
7880
7881        synchronized (mPackages) {
7882            return mInstantAppRegistry.getInstantAppIconLPw(
7883                    packageName, userId);
7884        }
7885    }
7886
7887    private boolean isCallerSameApp(String packageName, int uid) {
7888        PackageParser.Package pkg = mPackages.get(packageName);
7889        return pkg != null
7890                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7891    }
7892
7893    @Override
7894    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7895        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7896            return ParceledListSlice.emptyList();
7897        }
7898        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7899    }
7900
7901    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7902        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7903
7904        // reader
7905        synchronized (mPackages) {
7906            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7907            final int userId = UserHandle.getCallingUserId();
7908            while (i.hasNext()) {
7909                final PackageParser.Package p = i.next();
7910                if (p.applicationInfo == null) continue;
7911
7912                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7913                        && !p.applicationInfo.isDirectBootAware();
7914                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7915                        && p.applicationInfo.isDirectBootAware();
7916
7917                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7918                        && (!mSafeMode || isSystemApp(p))
7919                        && (matchesUnaware || matchesAware)) {
7920                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7921                    if (ps != null) {
7922                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7923                                ps.readUserState(userId), userId);
7924                        if (ai != null) {
7925                            finalList.add(ai);
7926                        }
7927                    }
7928                }
7929            }
7930        }
7931
7932        return finalList;
7933    }
7934
7935    @Override
7936    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7937        return resolveContentProviderInternal(name, flags, userId);
7938    }
7939
7940    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7941        if (!sUserManager.exists(userId)) return null;
7942        flags = updateFlagsForComponent(flags, userId, name);
7943        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7944        // reader
7945        synchronized (mPackages) {
7946            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7947            PackageSetting ps = provider != null
7948                    ? mSettings.mPackages.get(provider.owner.packageName)
7949                    : null;
7950            if (ps != null) {
7951                final boolean isInstantApp = ps.getInstantApp(userId);
7952                // normal application; filter out instant application provider
7953                if (instantAppPkgName == null && isInstantApp) {
7954                    return null;
7955                }
7956                // instant application; filter out other instant applications
7957                if (instantAppPkgName != null
7958                        && isInstantApp
7959                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7960                    return null;
7961                }
7962                // instant application; filter out non-exposed provider
7963                if (instantAppPkgName != null
7964                        && !isInstantApp
7965                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7966                    return null;
7967                }
7968                // provider not enabled
7969                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7970                    return null;
7971                }
7972                return PackageParser.generateProviderInfo(
7973                        provider, flags, ps.readUserState(userId), userId);
7974            }
7975            return null;
7976        }
7977    }
7978
7979    /**
7980     * @deprecated
7981     */
7982    @Deprecated
7983    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7984        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7985            return;
7986        }
7987        // reader
7988        synchronized (mPackages) {
7989            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7990                    .entrySet().iterator();
7991            final int userId = UserHandle.getCallingUserId();
7992            while (i.hasNext()) {
7993                Map.Entry<String, PackageParser.Provider> entry = i.next();
7994                PackageParser.Provider p = entry.getValue();
7995                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7996
7997                if (ps != null && p.syncable
7998                        && (!mSafeMode || (p.info.applicationInfo.flags
7999                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8000                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8001                            ps.readUserState(userId), userId);
8002                    if (info != null) {
8003                        outNames.add(entry.getKey());
8004                        outInfo.add(info);
8005                    }
8006                }
8007            }
8008        }
8009    }
8010
8011    @Override
8012    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8013            int uid, int flags, String metaDataKey) {
8014        final int callingUid = Binder.getCallingUid();
8015        final int userId = processName != null ? UserHandle.getUserId(uid)
8016                : UserHandle.getCallingUserId();
8017        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8018        flags = updateFlagsForComponent(flags, userId, processName);
8019        ArrayList<ProviderInfo> finalList = null;
8020        // reader
8021        synchronized (mPackages) {
8022            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8023            while (i.hasNext()) {
8024                final PackageParser.Provider p = i.next();
8025                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8026                if (ps != null && p.info.authority != null
8027                        && (processName == null
8028                                || (p.info.processName.equals(processName)
8029                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8030                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8031
8032                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8033                    // parameter.
8034                    if (metaDataKey != null
8035                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8036                        continue;
8037                    }
8038                    final ComponentName component =
8039                            new ComponentName(p.info.packageName, p.info.name);
8040                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8041                        continue;
8042                    }
8043                    if (finalList == null) {
8044                        finalList = new ArrayList<ProviderInfo>(3);
8045                    }
8046                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8047                            ps.readUserState(userId), userId);
8048                    if (info != null) {
8049                        finalList.add(info);
8050                    }
8051                }
8052            }
8053        }
8054
8055        if (finalList != null) {
8056            Collections.sort(finalList, mProviderInitOrderSorter);
8057            return new ParceledListSlice<ProviderInfo>(finalList);
8058        }
8059
8060        return ParceledListSlice.emptyList();
8061    }
8062
8063    @Override
8064    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8065        // reader
8066        synchronized (mPackages) {
8067            final int callingUid = Binder.getCallingUid();
8068            final int callingUserId = UserHandle.getUserId(callingUid);
8069            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8070            if (ps == null) return null;
8071            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8072                return null;
8073            }
8074            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8075            return PackageParser.generateInstrumentationInfo(i, flags);
8076        }
8077    }
8078
8079    @Override
8080    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8081            String targetPackage, int flags) {
8082        final int callingUid = Binder.getCallingUid();
8083        final int callingUserId = UserHandle.getUserId(callingUid);
8084        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8085        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8086            return ParceledListSlice.emptyList();
8087        }
8088        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8089    }
8090
8091    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8092            int flags) {
8093        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8094
8095        // reader
8096        synchronized (mPackages) {
8097            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8098            while (i.hasNext()) {
8099                final PackageParser.Instrumentation p = i.next();
8100                if (targetPackage == null
8101                        || targetPackage.equals(p.info.targetPackage)) {
8102                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8103                            flags);
8104                    if (ii != null) {
8105                        finalList.add(ii);
8106                    }
8107                }
8108            }
8109        }
8110
8111        return finalList;
8112    }
8113
8114    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8115        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8116        try {
8117            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8118        } finally {
8119            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8120        }
8121    }
8122
8123    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8124        final File[] files = scanDir.listFiles();
8125        if (ArrayUtils.isEmpty(files)) {
8126            Log.d(TAG, "No files in app dir " + scanDir);
8127            return;
8128        }
8129
8130        if (DEBUG_PACKAGE_SCANNING) {
8131            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8132                    + " flags=0x" + Integer.toHexString(parseFlags));
8133        }
8134        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8135                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8136                mParallelPackageParserCallback)) {
8137            // Submit files for parsing in parallel
8138            int fileCount = 0;
8139            for (File file : files) {
8140                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8141                        && !PackageInstallerService.isStageName(file.getName());
8142                if (!isPackage) {
8143                    // Ignore entries which are not packages
8144                    continue;
8145                }
8146                parallelPackageParser.submit(file, parseFlags);
8147                fileCount++;
8148            }
8149
8150            // Process results one by one
8151            for (; fileCount > 0; fileCount--) {
8152                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8153                Throwable throwable = parseResult.throwable;
8154                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8155
8156                if (throwable == null) {
8157                    // TODO(toddke): move lower in the scan chain
8158                    // Static shared libraries have synthetic package names
8159                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8160                        renameStaticSharedLibraryPackage(parseResult.pkg);
8161                    }
8162                    try {
8163                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8164                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8165                                    currentTime, null);
8166                        }
8167                    } catch (PackageManagerException e) {
8168                        errorCode = e.error;
8169                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8170                    }
8171                } else if (throwable instanceof PackageParser.PackageParserException) {
8172                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8173                            throwable;
8174                    errorCode = e.error;
8175                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8176                } else {
8177                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8178                            + parseResult.scanFile, throwable);
8179                }
8180
8181                // Delete invalid userdata apps
8182                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8183                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8184                    logCriticalInfo(Log.WARN,
8185                            "Deleting invalid package at " + parseResult.scanFile);
8186                    removeCodePathLI(parseResult.scanFile);
8187                }
8188            }
8189        }
8190    }
8191
8192    public static void reportSettingsProblem(int priority, String msg) {
8193        logCriticalInfo(priority, msg);
8194    }
8195
8196    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8197            final @ParseFlags int parseFlags, boolean forceCollect) throws PackageManagerException {
8198        // When upgrading from pre-N MR1, verify the package time stamp using the package
8199        // directory and not the APK file.
8200        final long lastModifiedTime = mIsPreNMR1Upgrade
8201                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8202        if (ps != null && !forceCollect
8203                && ps.codePathString.equals(pkg.codePath)
8204                && ps.timeStamp == lastModifiedTime
8205                && !isCompatSignatureUpdateNeeded(pkg)
8206                && !isRecoverSignatureUpdateNeeded(pkg)) {
8207            if (ps.signatures.mSignatures != null
8208                    && ps.signatures.mSignatures.length != 0
8209                    && ps.signatures.mSignatureSchemeVersion != SignatureSchemeVersion.UNKNOWN) {
8210                // Optimization: reuse the existing cached signing data
8211                // if the package appears to be unchanged.
8212                try {
8213                    pkg.mSigningDetails = new PackageParser.SigningDetails(ps.signatures.mSignatures,
8214                            ps.signatures.mSignatureSchemeVersion);
8215                    return;
8216                } catch (CertificateException e) {
8217                    Slog.e(TAG, "Attempt to read public keys from persisted signatures failed for "
8218                                    + ps.name, e);
8219                }
8220            }
8221
8222            Slog.w(TAG, "PackageSetting for " + ps.name
8223                    + " is missing signatures.  Collecting certs again to recover them.");
8224        } else {
8225            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8226                    (forceCollect ? " (forced)" : ""));
8227        }
8228
8229        try {
8230            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8231            PackageParser.collectCertificates(pkg, parseFlags);
8232        } catch (PackageParserException e) {
8233            throw PackageManagerException.from(e);
8234        } finally {
8235            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8236        }
8237    }
8238
8239    /**
8240     *  Traces a package scan.
8241     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8242     */
8243    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8244            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8245        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8246        try {
8247            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8248        } finally {
8249            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8250        }
8251    }
8252
8253    /**
8254     *  Scans a package and returns the newly parsed package.
8255     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8256     */
8257    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8258            long currentTime, UserHandle user) throws PackageManagerException {
8259        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8260        PackageParser pp = new PackageParser();
8261        pp.setSeparateProcesses(mSeparateProcesses);
8262        pp.setOnlyCoreApps(mOnlyCore);
8263        pp.setDisplayMetrics(mMetrics);
8264        pp.setCallback(mPackageParserCallback);
8265
8266        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8267        final PackageParser.Package pkg;
8268        try {
8269            pkg = pp.parsePackage(scanFile, parseFlags);
8270        } catch (PackageParserException e) {
8271            throw PackageManagerException.from(e);
8272        } finally {
8273            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8274        }
8275
8276        // Static shared libraries have synthetic package names
8277        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8278            renameStaticSharedLibraryPackage(pkg);
8279        }
8280
8281        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8282    }
8283
8284    /**
8285     *  Scans a package and returns the newly parsed package.
8286     *  @throws PackageManagerException on a parse error.
8287     */
8288    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8289            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8290            @Nullable UserHandle user)
8291                    throws PackageManagerException {
8292        // If the package has children and this is the first dive in the function
8293        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8294        // packages (parent and children) would be successfully scanned before the
8295        // actual scan since scanning mutates internal state and we want to atomically
8296        // install the package and its children.
8297        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8298            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8299                scanFlags |= SCAN_CHECK_ONLY;
8300            }
8301        } else {
8302            scanFlags &= ~SCAN_CHECK_ONLY;
8303        }
8304
8305        // Scan the parent
8306        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8307                scanFlags, currentTime, user);
8308
8309        // Scan the children
8310        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8311        for (int i = 0; i < childCount; i++) {
8312            PackageParser.Package childPackage = pkg.childPackages.get(i);
8313            addForInitLI(childPackage, parseFlags, scanFlags,
8314                    currentTime, user);
8315        }
8316
8317
8318        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8319            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8320        }
8321
8322        return scannedPkg;
8323    }
8324
8325    // Temporary to catch potential issues with refactoring
8326    private static boolean REFACTOR_DEBUG = true;
8327    /**
8328     * Adds a new package to the internal data structures during platform initialization.
8329     * <p>After adding, the package is known to the system and available for querying.
8330     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8331     * etc...], additional checks are performed. Basic verification [such as ensuring
8332     * matching signatures, checking version codes, etc...] occurs if the package is
8333     * identical to a previously known package. If the package fails a signature check,
8334     * the version installed on /data will be removed. If the version of the new package
8335     * is less than or equal than the version on /data, it will be ignored.
8336     * <p>Regardless of the package location, the results are applied to the internal
8337     * structures and the package is made available to the rest of the system.
8338     * <p>NOTE: The return value should be removed. It's the passed in package object.
8339     */
8340    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8341            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8342            @Nullable UserHandle user)
8343                    throws PackageManagerException {
8344        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8345        final String renamedPkgName;
8346        final PackageSetting disabledPkgSetting;
8347        final boolean isSystemPkgUpdated;
8348        final boolean pkgAlreadyExists;
8349        PackageSetting pkgSetting;
8350
8351        // NOTE: installPackageLI() has the same code to setup the package's
8352        // application info. This probably should be done lower in the call
8353        // stack [such as scanPackageOnly()]. However, we verify the application
8354        // info prior to that [in scanPackageNew()] and thus have to setup
8355        // the application info early.
8356        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8357        pkg.setApplicationInfoCodePath(pkg.codePath);
8358        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8359        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8360        pkg.setApplicationInfoResourcePath(pkg.codePath);
8361        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8362        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8363
8364        synchronized (mPackages) {
8365            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8366            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8367if (REFACTOR_DEBUG) {
8368Slog.e("TODD",
8369        "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName));
8370}
8371            if (realPkgName != null) {
8372                ensurePackageRenamed(pkg, renamedPkgName);
8373            }
8374            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8375            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8376            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8377            pkgAlreadyExists = pkgSetting != null;
8378            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8379            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8380            isSystemPkgUpdated = disabledPkgSetting != null;
8381
8382            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8383                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8384            }
8385if (REFACTOR_DEBUG) {
8386Slog.e("TODD",
8387        "SSP? " + scanSystemPartition
8388        + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"")
8389        + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():""));
8390}
8391
8392            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8393                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8394                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8395                    : null;
8396            if (DEBUG_PACKAGE_SCANNING
8397                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8398                    && sharedUserSetting != null) {
8399                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8400                        + " (uid=" + sharedUserSetting.userId + "):"
8401                        + " packages=" + sharedUserSetting.packages);
8402if (REFACTOR_DEBUG) {
8403Slog.e("TODD",
8404        "Shared UserID " + pkg.mSharedUserId
8405        + " (uid=" + sharedUserSetting.userId + "):"
8406        + " packages=" + sharedUserSetting.packages);
8407}
8408            }
8409
8410            if (scanSystemPartition) {
8411                // Potentially prune child packages. If the application on the /system
8412                // partition has been updated via OTA, but, is still disabled by a
8413                // version on /data, cycle through all of its children packages and
8414                // remove children that are no longer defined.
8415                if (isSystemPkgUpdated) {
8416if (REFACTOR_DEBUG) {
8417Slog.e("TODD",
8418        "Disable child packages");
8419}
8420                    final int scannedChildCount = (pkg.childPackages != null)
8421                            ? pkg.childPackages.size() : 0;
8422                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8423                            ? disabledPkgSetting.childPackageNames.size() : 0;
8424                    for (int i = 0; i < disabledChildCount; i++) {
8425                        String disabledChildPackageName =
8426                                disabledPkgSetting.childPackageNames.get(i);
8427                        boolean disabledPackageAvailable = false;
8428                        for (int j = 0; j < scannedChildCount; j++) {
8429                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8430                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8431if (REFACTOR_DEBUG) {
8432Slog.e("TODD",
8433        "Ignore " + disabledChildPackageName);
8434}
8435                                disabledPackageAvailable = true;
8436                                break;
8437                            }
8438                        }
8439                        if (!disabledPackageAvailable) {
8440if (REFACTOR_DEBUG) {
8441Slog.e("TODD",
8442        "Disable " + disabledChildPackageName);
8443}
8444                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8445                        }
8446                    }
8447                    // we're updating the disabled package, so, scan it as the package setting
8448                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8449                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8450                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8451                            (pkg == mPlatformPackage), user);
8452if (REFACTOR_DEBUG) {
8453Slog.e("TODD",
8454        "Scan disabled system package");
8455Slog.e("TODD",
8456        "Pre: " + request.pkgSetting.dumpState_temp());
8457}
8458final ScanResult result =
8459                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8460if (REFACTOR_DEBUG) {
8461Slog.e("TODD",
8462        "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan"));
8463}
8464                }
8465            }
8466        }
8467
8468        final boolean newPkgChangedPaths =
8469                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8470if (REFACTOR_DEBUG) {
8471Slog.e("TODD",
8472        "paths changed? " + newPkgChangedPaths
8473        + "; old: " + pkg.codePath
8474        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString));
8475}
8476        final boolean newPkgVersionGreater =
8477                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8478if (REFACTOR_DEBUG) {
8479Slog.e("TODD",
8480        "version greater? " + newPkgVersionGreater
8481        + "; old: " + pkg.getLongVersionCode()
8482        + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode));
8483}
8484        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8485                && newPkgChangedPaths && newPkgVersionGreater;
8486if (REFACTOR_DEBUG) {
8487    Slog.e("TODD",
8488            "system better? " + isSystemPkgBetter);
8489}
8490        if (isSystemPkgBetter) {
8491            // The version of the application on /system is greater than the version on
8492            // /data. Switch back to the application on /system.
8493            // It's safe to assume the application on /system will correctly scan. If not,
8494            // there won't be a working copy of the application.
8495            synchronized (mPackages) {
8496                // just remove the loaded entries from package lists
8497                mPackages.remove(pkgSetting.name);
8498            }
8499
8500            logCriticalInfo(Log.WARN,
8501                    "System package updated;"
8502                    + " name: " + pkgSetting.name
8503                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8504                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8505if (REFACTOR_DEBUG) {
8506Slog.e("TODD",
8507        "System package changed;"
8508        + " name: " + pkgSetting.name
8509        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8510        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8511}
8512
8513            final InstallArgs args = createInstallArgsForExisting(
8514                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8515                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8516            args.cleanUpResourcesLI();
8517            synchronized (mPackages) {
8518                mSettings.enableSystemPackageLPw(pkgSetting.name);
8519            }
8520        }
8521
8522        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8523if (REFACTOR_DEBUG) {
8524Slog.e("TODD",
8525        "THROW exception; system pkg version not good enough");
8526}
8527            // The version of the application on the /system partition is less than or
8528            // equal to the version on the /data partition. Throw an exception and use
8529            // the application already installed on the /data partition.
8530            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8531                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8532                    + " better than this " + pkg.getLongVersionCode());
8533        }
8534
8535        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8536        // force the verification. Full apk verification will happen unless apk verity is set up for
8537        // the file. In that case, only small part of the apk is verified upfront.
8538        collectCertificatesLI(pkgSetting, pkg, parseFlags,
8539                PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting));
8540
8541        boolean shouldHideSystemApp = false;
8542        // A new application appeared on /system, but, we already have a copy of
8543        // the application installed on /data.
8544        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8545                && !pkgSetting.isSystem()) {
8546            // if the signatures don't match, wipe the installed application and its data
8547            if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSigningDetails.signatures)
8548                    != PackageManager.SIGNATURE_MATCH) {
8549                logCriticalInfo(Log.WARN,
8550                        "System package signature mismatch;"
8551                        + " name: " + pkgSetting.name);
8552if (REFACTOR_DEBUG) {
8553Slog.e("TODD",
8554        "System package signature mismatch;"
8555        + " name: " + pkgSetting.name);
8556}
8557                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8558                        "scanPackageInternalLI")) {
8559                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8560                }
8561                pkgSetting = null;
8562            } else if (newPkgVersionGreater) {
8563                // The application on /system is newer than the application on /data.
8564                // Simply remove the application on /data [keeping application data]
8565                // and replace it with the version on /system.
8566                logCriticalInfo(Log.WARN,
8567                        "System package enabled;"
8568                        + " name: " + pkgSetting.name
8569                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8570                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8571if (REFACTOR_DEBUG) {
8572Slog.e("TODD",
8573        "System package enabled;"
8574        + " name: " + pkgSetting.name
8575        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8576        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8577}
8578                InstallArgs args = createInstallArgsForExisting(
8579                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8580                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8581                synchronized (mInstallLock) {
8582                    args.cleanUpResourcesLI();
8583                }
8584            } else {
8585                // The application on /system is older than the application on /data. Hide
8586                // the application on /system and the version on /data will be scanned later
8587                // and re-added like an update.
8588                shouldHideSystemApp = true;
8589                logCriticalInfo(Log.INFO,
8590                        "System package disabled;"
8591                        + " name: " + pkgSetting.name
8592                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8593                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8594if (REFACTOR_DEBUG) {
8595Slog.e("TODD",
8596        "System package disabled;"
8597        + " name: " + pkgSetting.name
8598        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8599        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8600}
8601            }
8602        }
8603
8604if (REFACTOR_DEBUG) {
8605Slog.e("TODD",
8606        "Scan package");
8607Slog.e("TODD",
8608        "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8609}
8610        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8611                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8612if (REFACTOR_DEBUG) {
8613pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8614Slog.e("TODD",
8615        "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp()));
8616}
8617
8618        if (shouldHideSystemApp) {
8619if (REFACTOR_DEBUG) {
8620Slog.e("TODD",
8621        "Disable package: " + pkg.packageName);
8622}
8623            synchronized (mPackages) {
8624                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8625            }
8626        }
8627        return scannedPkg;
8628    }
8629
8630    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8631        // Derive the new package synthetic package name
8632        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8633                + pkg.staticSharedLibVersion);
8634    }
8635
8636    private static String fixProcessName(String defProcessName,
8637            String processName) {
8638        if (processName == null) {
8639            return defProcessName;
8640        }
8641        return processName;
8642    }
8643
8644    /**
8645     * Enforces that only the system UID or root's UID can call a method exposed
8646     * via Binder.
8647     *
8648     * @param message used as message if SecurityException is thrown
8649     * @throws SecurityException if the caller is not system or root
8650     */
8651    private static final void enforceSystemOrRoot(String message) {
8652        final int uid = Binder.getCallingUid();
8653        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8654            throw new SecurityException(message);
8655        }
8656    }
8657
8658    @Override
8659    public void performFstrimIfNeeded() {
8660        enforceSystemOrRoot("Only the system can request fstrim");
8661
8662        // Before everything else, see whether we need to fstrim.
8663        try {
8664            IStorageManager sm = PackageHelper.getStorageManager();
8665            if (sm != null) {
8666                boolean doTrim = false;
8667                final long interval = android.provider.Settings.Global.getLong(
8668                        mContext.getContentResolver(),
8669                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8670                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8671                if (interval > 0) {
8672                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8673                    if (timeSinceLast > interval) {
8674                        doTrim = true;
8675                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8676                                + "; running immediately");
8677                    }
8678                }
8679                if (doTrim) {
8680                    final boolean dexOptDialogShown;
8681                    synchronized (mPackages) {
8682                        dexOptDialogShown = mDexOptDialogShown;
8683                    }
8684                    if (!isFirstBoot() && dexOptDialogShown) {
8685                        try {
8686                            ActivityManager.getService().showBootMessage(
8687                                    mContext.getResources().getString(
8688                                            R.string.android_upgrading_fstrim), true);
8689                        } catch (RemoteException e) {
8690                        }
8691                    }
8692                    sm.runMaintenance();
8693                }
8694            } else {
8695                Slog.e(TAG, "storageManager service unavailable!");
8696            }
8697        } catch (RemoteException e) {
8698            // Can't happen; StorageManagerService is local
8699        }
8700    }
8701
8702    @Override
8703    public void updatePackagesIfNeeded() {
8704        enforceSystemOrRoot("Only the system can request package update");
8705
8706        // We need to re-extract after an OTA.
8707        boolean causeUpgrade = isUpgrade();
8708
8709        // First boot or factory reset.
8710        // Note: we also handle devices that are upgrading to N right now as if it is their
8711        //       first boot, as they do not have profile data.
8712        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8713
8714        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8715        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8716
8717        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8718            return;
8719        }
8720
8721        List<PackageParser.Package> pkgs;
8722        synchronized (mPackages) {
8723            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8724        }
8725
8726        final long startTime = System.nanoTime();
8727        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8728                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8729                    false /* bootComplete */);
8730
8731        final int elapsedTimeSeconds =
8732                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8733
8734        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8735        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8736        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8737        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8738        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8739    }
8740
8741    /*
8742     * Return the prebuilt profile path given a package base code path.
8743     */
8744    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8745        return pkg.baseCodePath + ".prof";
8746    }
8747
8748    /**
8749     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8750     * containing statistics about the invocation. The array consists of three elements,
8751     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8752     * and {@code numberOfPackagesFailed}.
8753     */
8754    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8755            final String compilerFilter, boolean bootComplete) {
8756
8757        int numberOfPackagesVisited = 0;
8758        int numberOfPackagesOptimized = 0;
8759        int numberOfPackagesSkipped = 0;
8760        int numberOfPackagesFailed = 0;
8761        final int numberOfPackagesToDexopt = pkgs.size();
8762
8763        for (PackageParser.Package pkg : pkgs) {
8764            numberOfPackagesVisited++;
8765
8766            boolean useProfileForDexopt = false;
8767
8768            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8769                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8770                // that are already compiled.
8771                File profileFile = new File(getPrebuildProfilePath(pkg));
8772                // Copy profile if it exists.
8773                if (profileFile.exists()) {
8774                    try {
8775                        // We could also do this lazily before calling dexopt in
8776                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8777                        // is that we don't have a good way to say "do this only once".
8778                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8779                                pkg.applicationInfo.uid, pkg.packageName)) {
8780                            Log.e(TAG, "Installer failed to copy system profile!");
8781                        } else {
8782                            // Disabled as this causes speed-profile compilation during first boot
8783                            // even if things are already compiled.
8784                            // useProfileForDexopt = true;
8785                        }
8786                    } catch (Exception e) {
8787                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8788                                e);
8789                    }
8790                } else {
8791                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8792                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8793                    // minimize the number off apps being speed-profile compiled during first boot.
8794                    // The other paths will not change the filter.
8795                    if (disabledPs != null && disabledPs.pkg.isStub) {
8796                        // The package is the stub one, remove the stub suffix to get the normal
8797                        // package and APK names.
8798                        String systemProfilePath =
8799                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8800                        profileFile = new File(systemProfilePath);
8801                        // If we have a profile for a compressed APK, copy it to the reference
8802                        // location.
8803                        // Note that copying the profile here will cause it to override the
8804                        // reference profile every OTA even though the existing reference profile
8805                        // may have more data. We can't copy during decompression since the
8806                        // directories are not set up at that point.
8807                        if (profileFile.exists()) {
8808                            try {
8809                                // We could also do this lazily before calling dexopt in
8810                                // PackageDexOptimizer to prevent this happening on first boot. The
8811                                // issue is that we don't have a good way to say "do this only
8812                                // once".
8813                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8814                                        pkg.applicationInfo.uid, pkg.packageName)) {
8815                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8816                                } else {
8817                                    useProfileForDexopt = true;
8818                                }
8819                            } catch (Exception e) {
8820                                Log.e(TAG, "Failed to copy profile " +
8821                                        profileFile.getAbsolutePath() + " ", e);
8822                            }
8823                        }
8824                    }
8825                }
8826            }
8827
8828            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8829                if (DEBUG_DEXOPT) {
8830                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8831                }
8832                numberOfPackagesSkipped++;
8833                continue;
8834            }
8835
8836            if (DEBUG_DEXOPT) {
8837                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8838                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8839            }
8840
8841            if (showDialog) {
8842                try {
8843                    ActivityManager.getService().showBootMessage(
8844                            mContext.getResources().getString(R.string.android_upgrading_apk,
8845                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8846                } catch (RemoteException e) {
8847                }
8848                synchronized (mPackages) {
8849                    mDexOptDialogShown = true;
8850                }
8851            }
8852
8853            String pkgCompilerFilter = compilerFilter;
8854            if (useProfileForDexopt) {
8855                // Use background dexopt mode to try and use the profile. Note that this does not
8856                // guarantee usage of the profile.
8857                pkgCompilerFilter =
8858                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8859                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8860            }
8861
8862            // checkProfiles is false to avoid merging profiles during boot which
8863            // might interfere with background compilation (b/28612421).
8864            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8865            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8866            // trade-off worth doing to save boot time work.
8867            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8868            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8869                    pkg.packageName,
8870                    pkgCompilerFilter,
8871                    dexoptFlags));
8872
8873            switch (primaryDexOptStaus) {
8874                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8875                    numberOfPackagesOptimized++;
8876                    break;
8877                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8878                    numberOfPackagesSkipped++;
8879                    break;
8880                case PackageDexOptimizer.DEX_OPT_FAILED:
8881                    numberOfPackagesFailed++;
8882                    break;
8883                default:
8884                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8885                    break;
8886            }
8887        }
8888
8889        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8890                numberOfPackagesFailed };
8891    }
8892
8893    @Override
8894    public void notifyPackageUse(String packageName, int reason) {
8895        synchronized (mPackages) {
8896            final int callingUid = Binder.getCallingUid();
8897            final int callingUserId = UserHandle.getUserId(callingUid);
8898            if (getInstantAppPackageName(callingUid) != null) {
8899                if (!isCallerSameApp(packageName, callingUid)) {
8900                    return;
8901                }
8902            } else {
8903                if (isInstantApp(packageName, callingUserId)) {
8904                    return;
8905                }
8906            }
8907            notifyPackageUseLocked(packageName, reason);
8908        }
8909    }
8910
8911    private void notifyPackageUseLocked(String packageName, int reason) {
8912        final PackageParser.Package p = mPackages.get(packageName);
8913        if (p == null) {
8914            return;
8915        }
8916        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8917    }
8918
8919    @Override
8920    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8921            List<String> classPaths, String loaderIsa) {
8922        int userId = UserHandle.getCallingUserId();
8923        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8924        if (ai == null) {
8925            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8926                + loadingPackageName + ", user=" + userId);
8927            return;
8928        }
8929        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8930    }
8931
8932    @Override
8933    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8934            IDexModuleRegisterCallback callback) {
8935        int userId = UserHandle.getCallingUserId();
8936        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8937        DexManager.RegisterDexModuleResult result;
8938        if (ai == null) {
8939            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8940                     " calling user. package=" + packageName + ", user=" + userId);
8941            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8942        } else {
8943            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8944        }
8945
8946        if (callback != null) {
8947            mHandler.post(() -> {
8948                try {
8949                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8950                } catch (RemoteException e) {
8951                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8952                }
8953            });
8954        }
8955    }
8956
8957    /**
8958     * Ask the package manager to perform a dex-opt with the given compiler filter.
8959     *
8960     * Note: exposed only for the shell command to allow moving packages explicitly to a
8961     *       definite state.
8962     */
8963    @Override
8964    public boolean performDexOptMode(String packageName,
8965            boolean checkProfiles, String targetCompilerFilter, boolean force,
8966            boolean bootComplete, String splitName) {
8967        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8968                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8969                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8970        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8971                splitName, flags));
8972    }
8973
8974    /**
8975     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8976     * secondary dex files belonging to the given package.
8977     *
8978     * Note: exposed only for the shell command to allow moving packages explicitly to a
8979     *       definite state.
8980     */
8981    @Override
8982    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8983            boolean force) {
8984        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8985                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8986                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8987                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8988        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8989    }
8990
8991    /*package*/ boolean performDexOpt(DexoptOptions options) {
8992        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8993            return false;
8994        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8995            return false;
8996        }
8997
8998        if (options.isDexoptOnlySecondaryDex()) {
8999            return mDexManager.dexoptSecondaryDex(options);
9000        } else {
9001            int dexoptStatus = performDexOptWithStatus(options);
9002            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9003        }
9004    }
9005
9006    /**
9007     * Perform dexopt on the given package and return one of following result:
9008     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9009     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9010     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9011     */
9012    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9013        return performDexOptTraced(options);
9014    }
9015
9016    private int performDexOptTraced(DexoptOptions options) {
9017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9018        try {
9019            return performDexOptInternal(options);
9020        } finally {
9021            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9022        }
9023    }
9024
9025    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9026    // if the package can now be considered up to date for the given filter.
9027    private int performDexOptInternal(DexoptOptions options) {
9028        PackageParser.Package p;
9029        synchronized (mPackages) {
9030            p = mPackages.get(options.getPackageName());
9031            if (p == null) {
9032                // Package could not be found. Report failure.
9033                return PackageDexOptimizer.DEX_OPT_FAILED;
9034            }
9035            mPackageUsage.maybeWriteAsync(mPackages);
9036            mCompilerStats.maybeWriteAsync();
9037        }
9038        long callingId = Binder.clearCallingIdentity();
9039        try {
9040            synchronized (mInstallLock) {
9041                return performDexOptInternalWithDependenciesLI(p, options);
9042            }
9043        } finally {
9044            Binder.restoreCallingIdentity(callingId);
9045        }
9046    }
9047
9048    public ArraySet<String> getOptimizablePackages() {
9049        ArraySet<String> pkgs = new ArraySet<String>();
9050        synchronized (mPackages) {
9051            for (PackageParser.Package p : mPackages.values()) {
9052                if (PackageDexOptimizer.canOptimizePackage(p)) {
9053                    pkgs.add(p.packageName);
9054                }
9055            }
9056        }
9057        return pkgs;
9058    }
9059
9060    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9061            DexoptOptions options) {
9062        // Select the dex optimizer based on the force parameter.
9063        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9064        //       allocate an object here.
9065        PackageDexOptimizer pdo = options.isForce()
9066                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9067                : mPackageDexOptimizer;
9068
9069        // Dexopt all dependencies first. Note: we ignore the return value and march on
9070        // on errors.
9071        // Note that we are going to call performDexOpt on those libraries as many times as
9072        // they are referenced in packages. When we do a batch of performDexOpt (for example
9073        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9074        // and the first package that uses the library will dexopt it. The
9075        // others will see that the compiled code for the library is up to date.
9076        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9077        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9078        if (!deps.isEmpty()) {
9079            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9080                    options.getCompilerFilter(), options.getSplitName(),
9081                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9082            for (PackageParser.Package depPackage : deps) {
9083                // TODO: Analyze and investigate if we (should) profile libraries.
9084                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9085                        getOrCreateCompilerPackageStats(depPackage),
9086                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9087            }
9088        }
9089        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9090                getOrCreateCompilerPackageStats(p),
9091                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9092    }
9093
9094    /**
9095     * Reconcile the information we have about the secondary dex files belonging to
9096     * {@code packagName} and the actual dex files. For all dex files that were
9097     * deleted, update the internal records and delete the generated oat files.
9098     */
9099    @Override
9100    public void reconcileSecondaryDexFiles(String packageName) {
9101        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9102            return;
9103        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9104            return;
9105        }
9106        mDexManager.reconcileSecondaryDexFiles(packageName);
9107    }
9108
9109    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9110    // a reference there.
9111    /*package*/ DexManager getDexManager() {
9112        return mDexManager;
9113    }
9114
9115    /**
9116     * Execute the background dexopt job immediately.
9117     */
9118    @Override
9119    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9120        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9121            return false;
9122        }
9123        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9124    }
9125
9126    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9127        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9128                || p.usesStaticLibraries != null) {
9129            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9130            Set<String> collectedNames = new HashSet<>();
9131            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9132
9133            retValue.remove(p);
9134
9135            return retValue;
9136        } else {
9137            return Collections.emptyList();
9138        }
9139    }
9140
9141    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9142            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9143        if (!collectedNames.contains(p.packageName)) {
9144            collectedNames.add(p.packageName);
9145            collected.add(p);
9146
9147            if (p.usesLibraries != null) {
9148                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9149                        null, collected, collectedNames);
9150            }
9151            if (p.usesOptionalLibraries != null) {
9152                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9153                        null, collected, collectedNames);
9154            }
9155            if (p.usesStaticLibraries != null) {
9156                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9157                        p.usesStaticLibrariesVersions, collected, collectedNames);
9158            }
9159        }
9160    }
9161
9162    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9163            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9164        final int libNameCount = libs.size();
9165        for (int i = 0; i < libNameCount; i++) {
9166            String libName = libs.get(i);
9167            long version = (versions != null && versions.length == libNameCount)
9168                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9169            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9170            if (libPkg != null) {
9171                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9172            }
9173        }
9174    }
9175
9176    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9177        synchronized (mPackages) {
9178            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9179            if (libEntry != null) {
9180                return mPackages.get(libEntry.apk);
9181            }
9182            return null;
9183        }
9184    }
9185
9186    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9187        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9188        if (versionedLib == null) {
9189            return null;
9190        }
9191        return versionedLib.get(version);
9192    }
9193
9194    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9195        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9196                pkg.staticSharedLibName);
9197        if (versionedLib == null) {
9198            return null;
9199        }
9200        long previousLibVersion = -1;
9201        final int versionCount = versionedLib.size();
9202        for (int i = 0; i < versionCount; i++) {
9203            final long libVersion = versionedLib.keyAt(i);
9204            if (libVersion < pkg.staticSharedLibVersion) {
9205                previousLibVersion = Math.max(previousLibVersion, libVersion);
9206            }
9207        }
9208        if (previousLibVersion >= 0) {
9209            return versionedLib.get(previousLibVersion);
9210        }
9211        return null;
9212    }
9213
9214    public void shutdown() {
9215        mPackageUsage.writeNow(mPackages);
9216        mCompilerStats.writeNow();
9217        mDexManager.writePackageDexUsageNow();
9218    }
9219
9220    @Override
9221    public void dumpProfiles(String packageName) {
9222        PackageParser.Package pkg;
9223        synchronized (mPackages) {
9224            pkg = mPackages.get(packageName);
9225            if (pkg == null) {
9226                throw new IllegalArgumentException("Unknown package: " + packageName);
9227            }
9228        }
9229        /* Only the shell, root, or the app user should be able to dump profiles. */
9230        int callingUid = Binder.getCallingUid();
9231        if (callingUid != Process.SHELL_UID &&
9232            callingUid != Process.ROOT_UID &&
9233            callingUid != pkg.applicationInfo.uid) {
9234            throw new SecurityException("dumpProfiles");
9235        }
9236
9237        synchronized (mInstallLock) {
9238            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9239            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9240            try {
9241                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9242                String codePaths = TextUtils.join(";", allCodePaths);
9243                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9244            } catch (InstallerException e) {
9245                Slog.w(TAG, "Failed to dump profiles", e);
9246            }
9247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9248        }
9249    }
9250
9251    @Override
9252    public void forceDexOpt(String packageName) {
9253        enforceSystemOrRoot("forceDexOpt");
9254
9255        PackageParser.Package pkg;
9256        synchronized (mPackages) {
9257            pkg = mPackages.get(packageName);
9258            if (pkg == null) {
9259                throw new IllegalArgumentException("Unknown package: " + packageName);
9260            }
9261        }
9262
9263        synchronized (mInstallLock) {
9264            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9265
9266            // Whoever is calling forceDexOpt wants a compiled package.
9267            // Don't use profiles since that may cause compilation to be skipped.
9268            final int res = performDexOptInternalWithDependenciesLI(
9269                    pkg,
9270                    new DexoptOptions(packageName,
9271                            getDefaultCompilerFilter(),
9272                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9273
9274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9275            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9276                throw new IllegalStateException("Failed to dexopt: " + res);
9277            }
9278        }
9279    }
9280
9281    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9282        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9283            Slog.w(TAG, "Unable to update from " + oldPkg.name
9284                    + " to " + newPkg.packageName
9285                    + ": old package not in system partition");
9286            return false;
9287        } else if (mPackages.get(oldPkg.name) != null) {
9288            Slog.w(TAG, "Unable to update from " + oldPkg.name
9289                    + " to " + newPkg.packageName
9290                    + ": old package still exists");
9291            return false;
9292        }
9293        return true;
9294    }
9295
9296    void removeCodePathLI(File codePath) {
9297        if (codePath.isDirectory()) {
9298            try {
9299                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9300            } catch (InstallerException e) {
9301                Slog.w(TAG, "Failed to remove code path", e);
9302            }
9303        } else {
9304            codePath.delete();
9305        }
9306    }
9307
9308    private int[] resolveUserIds(int userId) {
9309        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9310    }
9311
9312    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9313        if (pkg == null) {
9314            Slog.wtf(TAG, "Package was null!", new Throwable());
9315            return;
9316        }
9317        clearAppDataLeafLIF(pkg, userId, flags);
9318        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9319        for (int i = 0; i < childCount; i++) {
9320            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9321        }
9322    }
9323
9324    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9325        final PackageSetting ps;
9326        synchronized (mPackages) {
9327            ps = mSettings.mPackages.get(pkg.packageName);
9328        }
9329        for (int realUserId : resolveUserIds(userId)) {
9330            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9331            try {
9332                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9333                        ceDataInode);
9334            } catch (InstallerException e) {
9335                Slog.w(TAG, String.valueOf(e));
9336            }
9337        }
9338    }
9339
9340    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9341        if (pkg == null) {
9342            Slog.wtf(TAG, "Package was null!", new Throwable());
9343            return;
9344        }
9345        destroyAppDataLeafLIF(pkg, userId, flags);
9346        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9347        for (int i = 0; i < childCount; i++) {
9348            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9349        }
9350    }
9351
9352    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9353        final PackageSetting ps;
9354        synchronized (mPackages) {
9355            ps = mSettings.mPackages.get(pkg.packageName);
9356        }
9357        for (int realUserId : resolveUserIds(userId)) {
9358            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9359            try {
9360                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9361                        ceDataInode);
9362            } catch (InstallerException e) {
9363                Slog.w(TAG, String.valueOf(e));
9364            }
9365            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9366        }
9367    }
9368
9369    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9370        if (pkg == null) {
9371            Slog.wtf(TAG, "Package was null!", new Throwable());
9372            return;
9373        }
9374        destroyAppProfilesLeafLIF(pkg);
9375        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9376        for (int i = 0; i < childCount; i++) {
9377            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9378        }
9379    }
9380
9381    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9382        try {
9383            mInstaller.destroyAppProfiles(pkg.packageName);
9384        } catch (InstallerException e) {
9385            Slog.w(TAG, String.valueOf(e));
9386        }
9387    }
9388
9389    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9390        if (pkg == null) {
9391            Slog.wtf(TAG, "Package was null!", new Throwable());
9392            return;
9393        }
9394        clearAppProfilesLeafLIF(pkg);
9395        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9396        for (int i = 0; i < childCount; i++) {
9397            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9398        }
9399    }
9400
9401    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9402        try {
9403            mInstaller.clearAppProfiles(pkg.packageName);
9404        } catch (InstallerException e) {
9405            Slog.w(TAG, String.valueOf(e));
9406        }
9407    }
9408
9409    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9410            long lastUpdateTime) {
9411        // Set parent install/update time
9412        PackageSetting ps = (PackageSetting) pkg.mExtras;
9413        if (ps != null) {
9414            ps.firstInstallTime = firstInstallTime;
9415            ps.lastUpdateTime = lastUpdateTime;
9416        }
9417        // Set children install/update time
9418        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9419        for (int i = 0; i < childCount; i++) {
9420            PackageParser.Package childPkg = pkg.childPackages.get(i);
9421            ps = (PackageSetting) childPkg.mExtras;
9422            if (ps != null) {
9423                ps.firstInstallTime = firstInstallTime;
9424                ps.lastUpdateTime = lastUpdateTime;
9425            }
9426        }
9427    }
9428
9429    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9430            SharedLibraryEntry file,
9431            PackageParser.Package changingLib) {
9432        if (file.path != null) {
9433            usesLibraryFiles.add(file.path);
9434            return;
9435        }
9436        PackageParser.Package p = mPackages.get(file.apk);
9437        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9438            // If we are doing this while in the middle of updating a library apk,
9439            // then we need to make sure to use that new apk for determining the
9440            // dependencies here.  (We haven't yet finished committing the new apk
9441            // to the package manager state.)
9442            if (p == null || p.packageName.equals(changingLib.packageName)) {
9443                p = changingLib;
9444            }
9445        }
9446        if (p != null) {
9447            usesLibraryFiles.addAll(p.getAllCodePaths());
9448            if (p.usesLibraryFiles != null) {
9449                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9450            }
9451        }
9452    }
9453
9454    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9455            PackageParser.Package changingLib) throws PackageManagerException {
9456        if (pkg == null) {
9457            return;
9458        }
9459        // The collection used here must maintain the order of addition (so
9460        // that libraries are searched in the correct order) and must have no
9461        // duplicates.
9462        Set<String> usesLibraryFiles = null;
9463        if (pkg.usesLibraries != null) {
9464            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9465                    null, null, pkg.packageName, changingLib, true,
9466                    pkg.applicationInfo.targetSdkVersion, null);
9467        }
9468        if (pkg.usesStaticLibraries != null) {
9469            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9470                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9471                    pkg.packageName, changingLib, true,
9472                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9473        }
9474        if (pkg.usesOptionalLibraries != null) {
9475            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9476                    null, null, pkg.packageName, changingLib, false,
9477                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9478        }
9479        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9480            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9481        } else {
9482            pkg.usesLibraryFiles = null;
9483        }
9484    }
9485
9486    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9487            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9488            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9489            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9490            throws PackageManagerException {
9491        final int libCount = requestedLibraries.size();
9492        for (int i = 0; i < libCount; i++) {
9493            final String libName = requestedLibraries.get(i);
9494            final long libVersion = requiredVersions != null ? requiredVersions[i]
9495                    : SharedLibraryInfo.VERSION_UNDEFINED;
9496            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9497            if (libEntry == null) {
9498                if (required) {
9499                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9500                            "Package " + packageName + " requires unavailable shared library "
9501                                    + libName + "; failing!");
9502                } else if (DEBUG_SHARED_LIBRARIES) {
9503                    Slog.i(TAG, "Package " + packageName
9504                            + " desires unavailable shared library "
9505                            + libName + "; ignoring!");
9506                }
9507            } else {
9508                if (requiredVersions != null && requiredCertDigests != null) {
9509                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9510                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9511                            "Package " + packageName + " requires unavailable static shared"
9512                                    + " library " + libName + " version "
9513                                    + libEntry.info.getLongVersion() + "; failing!");
9514                    }
9515
9516                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9517                    if (libPkg == null) {
9518                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9519                                "Package " + packageName + " requires unavailable static shared"
9520                                        + " library; failing!");
9521                    }
9522
9523                    final String[] expectedCertDigests = requiredCertDigests[i];
9524                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9525                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9526                            ? PackageUtils.computeSignaturesSha256Digests(
9527                            libPkg.mSigningDetails.signatures)
9528                            : PackageUtils.computeSignaturesSha256Digests(
9529                                    new Signature[]{libPkg.mSigningDetails.signatures[0]});
9530
9531                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9532                    // target O we don't parse the "additional-certificate" tags similarly
9533                    // how we only consider all certs only for apps targeting O (see above).
9534                    // Therefore, the size check is safe to make.
9535                    if (expectedCertDigests.length != libCertDigests.length) {
9536                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9537                                "Package " + packageName + " requires differently signed" +
9538                                        " static shared library; failing!");
9539                    }
9540
9541                    // Use a predictable order as signature order may vary
9542                    Arrays.sort(libCertDigests);
9543                    Arrays.sort(expectedCertDigests);
9544
9545                    final int certCount = libCertDigests.length;
9546                    for (int j = 0; j < certCount; j++) {
9547                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9548                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9549                                    "Package " + packageName + " requires differently signed" +
9550                                            " static shared library; failing!");
9551                        }
9552                    }
9553                }
9554
9555                if (outUsedLibraries == null) {
9556                    // Use LinkedHashSet to preserve the order of files added to
9557                    // usesLibraryFiles while eliminating duplicates.
9558                    outUsedLibraries = new LinkedHashSet<>();
9559                }
9560                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9561            }
9562        }
9563        return outUsedLibraries;
9564    }
9565
9566    private static boolean hasString(List<String> list, List<String> which) {
9567        if (list == null) {
9568            return false;
9569        }
9570        for (int i=list.size()-1; i>=0; i--) {
9571            for (int j=which.size()-1; j>=0; j--) {
9572                if (which.get(j).equals(list.get(i))) {
9573                    return true;
9574                }
9575            }
9576        }
9577        return false;
9578    }
9579
9580    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9581            PackageParser.Package changingPkg) {
9582        ArrayList<PackageParser.Package> res = null;
9583        for (PackageParser.Package pkg : mPackages.values()) {
9584            if (changingPkg != null
9585                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9586                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9587                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9588                            changingPkg.staticSharedLibName)) {
9589                return null;
9590            }
9591            if (res == null) {
9592                res = new ArrayList<>();
9593            }
9594            res.add(pkg);
9595            try {
9596                updateSharedLibrariesLPr(pkg, changingPkg);
9597            } catch (PackageManagerException e) {
9598                // If a system app update or an app and a required lib missing we
9599                // delete the package and for updated system apps keep the data as
9600                // it is better for the user to reinstall than to be in an limbo
9601                // state. Also libs disappearing under an app should never happen
9602                // - just in case.
9603                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9604                    final int flags = pkg.isUpdatedSystemApp()
9605                            ? PackageManager.DELETE_KEEP_DATA : 0;
9606                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9607                            flags , null, true, null);
9608                }
9609                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9610            }
9611        }
9612        return res;
9613    }
9614
9615    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9616            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9617            @Nullable UserHandle user) throws PackageManagerException {
9618        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9619        // If the package has children and this is the first dive in the function
9620        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9621        // whether all packages (parent and children) would be successfully scanned
9622        // before the actual scan since scanning mutates internal state and we want
9623        // to atomically install the package and its children.
9624        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9625            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9626                scanFlags |= SCAN_CHECK_ONLY;
9627            }
9628        } else {
9629            scanFlags &= ~SCAN_CHECK_ONLY;
9630        }
9631
9632        final PackageParser.Package scannedPkg;
9633        try {
9634            // Scan the parent
9635            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9636            // Scan the children
9637            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9638            for (int i = 0; i < childCount; i++) {
9639                PackageParser.Package childPkg = pkg.childPackages.get(i);
9640                scanPackageNewLI(childPkg, parseFlags,
9641                        scanFlags, currentTime, user);
9642            }
9643        } finally {
9644            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9645        }
9646
9647        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9648            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9649        }
9650
9651        return scannedPkg;
9652    }
9653
9654    /** The result of a package scan. */
9655    private static class ScanResult {
9656        /** Whether or not the package scan was successful */
9657        public final boolean success;
9658        /**
9659         * The final package settings. This may be the same object passed in
9660         * the {@link ScanRequest}, but, with modified values.
9661         */
9662        @Nullable public final PackageSetting pkgSetting;
9663        /** ABI code paths that have changed in the package scan */
9664        @Nullable public final List<String> changedAbiCodePath;
9665        public ScanResult(
9666                boolean success,
9667                @Nullable PackageSetting pkgSetting,
9668                @Nullable List<String> changedAbiCodePath) {
9669            this.success = success;
9670            this.pkgSetting = pkgSetting;
9671            this.changedAbiCodePath = changedAbiCodePath;
9672        }
9673    }
9674
9675    /** A package to be scanned */
9676    private static class ScanRequest {
9677        /** The parsed package */
9678        @NonNull public final PackageParser.Package pkg;
9679        /** Shared user settings, if the package has a shared user */
9680        @Nullable public final SharedUserSetting sharedUserSetting;
9681        /**
9682         * Package settings of the currently installed version.
9683         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9684         * during scan.
9685         */
9686        @Nullable public final PackageSetting pkgSetting;
9687        /** A copy of the settings for the currently installed version */
9688        @Nullable public final PackageSetting oldPkgSetting;
9689        /** Package settings for the disabled version on the /system partition */
9690        @Nullable public final PackageSetting disabledPkgSetting;
9691        /** Package settings for the installed version under its original package name */
9692        @Nullable public final PackageSetting originalPkgSetting;
9693        /** The real package name of a renamed application */
9694        @Nullable public final String realPkgName;
9695        public final @ParseFlags int parseFlags;
9696        public final @ScanFlags int scanFlags;
9697        /** The user for which the package is being scanned */
9698        @Nullable public final UserHandle user;
9699        /** Whether or not the platform package is being scanned */
9700        public final boolean isPlatformPackage;
9701        public ScanRequest(
9702                @NonNull PackageParser.Package pkg,
9703                @Nullable SharedUserSetting sharedUserSetting,
9704                @Nullable PackageSetting pkgSetting,
9705                @Nullable PackageSetting disabledPkgSetting,
9706                @Nullable PackageSetting originalPkgSetting,
9707                @Nullable String realPkgName,
9708                @ParseFlags int parseFlags,
9709                @ScanFlags int scanFlags,
9710                boolean isPlatformPackage,
9711                @Nullable UserHandle user) {
9712            this.pkg = pkg;
9713            this.pkgSetting = pkgSetting;
9714            this.sharedUserSetting = sharedUserSetting;
9715            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9716            this.disabledPkgSetting = disabledPkgSetting;
9717            this.originalPkgSetting = originalPkgSetting;
9718            this.realPkgName = realPkgName;
9719            this.parseFlags = parseFlags;
9720            this.scanFlags = scanFlags;
9721            this.isPlatformPackage = isPlatformPackage;
9722            this.user = user;
9723        }
9724    }
9725
9726    /**
9727     * Returns the actual scan flags depending upon the state of the other settings.
9728     * <p>Updated system applications will not have the following flags set
9729     * by default and need to be adjusted after the fact:
9730     * <ul>
9731     * <li>{@link #SCAN_AS_SYSTEM}</li>
9732     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9733     * <li>{@link #SCAN_AS_OEM}</li>
9734     * <li>{@link #SCAN_AS_VENDOR}</li>
9735     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9736     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9737     * </ul>
9738     */
9739    private static @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9740            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user) {
9741        if (disabledPkgSetting != null) {
9742            // updated system application, must at least have SCAN_AS_SYSTEM
9743            scanFlags |= SCAN_AS_SYSTEM;
9744            if ((disabledPkgSetting.pkgPrivateFlags
9745                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9746                scanFlags |= SCAN_AS_PRIVILEGED;
9747            }
9748            if ((disabledPkgSetting.pkgPrivateFlags
9749                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9750                scanFlags |= SCAN_AS_OEM;
9751            }
9752            if ((disabledPkgSetting.pkgPrivateFlags
9753                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9754                scanFlags |= SCAN_AS_VENDOR;
9755            }
9756        }
9757        if (pkgSetting != null) {
9758            final int userId = ((user == null) ? 0 : user.getIdentifier());
9759            if (pkgSetting.getInstantApp(userId)) {
9760                scanFlags |= SCAN_AS_INSTANT_APP;
9761            }
9762            if (pkgSetting.getVirtulalPreload(userId)) {
9763                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9764            }
9765        }
9766        return scanFlags;
9767    }
9768
9769    @GuardedBy("mInstallLock")
9770    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9771            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9772            @Nullable UserHandle user) throws PackageManagerException {
9773
9774        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9775        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9776        if (realPkgName != null) {
9777            ensurePackageRenamed(pkg, renamedPkgName);
9778        }
9779        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9780        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9781        final PackageSetting disabledPkgSetting =
9782                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9783
9784        if (mTransferedPackages.contains(pkg.packageName)) {
9785            Slog.w(TAG, "Package " + pkg.packageName
9786                    + " was transferred to another, but its .apk remains");
9787        }
9788
9789        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user);
9790        synchronized (mPackages) {
9791            applyPolicy(pkg, parseFlags, scanFlags);
9792            assertPackageIsValid(pkg, parseFlags, scanFlags);
9793
9794            SharedUserSetting sharedUserSetting = null;
9795            if (pkg.mSharedUserId != null) {
9796                // SIDE EFFECTS; may potentially allocate a new shared user
9797                sharedUserSetting = mSettings.getSharedUserLPw(
9798                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9799                if (DEBUG_PACKAGE_SCANNING) {
9800                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9801                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9802                                + " (uid=" + sharedUserSetting.userId + "):"
9803                                + " packages=" + sharedUserSetting.packages);
9804                }
9805            }
9806
9807            boolean scanSucceeded = false;
9808            try {
9809                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9810                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9811                        (pkg == mPlatformPackage), user);
9812                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9813                if (result.success) {
9814                    commitScanResultsLocked(request, result);
9815                }
9816                scanSucceeded = true;
9817            } finally {
9818                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9819                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9820                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9821                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9822                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9823                  }
9824            }
9825        }
9826        return pkg;
9827    }
9828
9829    /**
9830     * Commits the package scan and modifies system state.
9831     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9832     * of committing the package, leaving the system in an inconsistent state.
9833     * This needs to be fixed so, once we get to this point, no errors are
9834     * possible and the system is not left in an inconsistent state.
9835     */
9836    @GuardedBy("mPackages")
9837    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9838            throws PackageManagerException {
9839        final PackageParser.Package pkg = request.pkg;
9840        final @ParseFlags int parseFlags = request.parseFlags;
9841        final @ScanFlags int scanFlags = request.scanFlags;
9842        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9843        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9844        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9845        final UserHandle user = request.user;
9846        final String realPkgName = request.realPkgName;
9847        final PackageSetting pkgSetting = result.pkgSetting;
9848        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9849        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9850
9851        if (newPkgSettingCreated) {
9852            if (originalPkgSetting != null) {
9853                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9854            }
9855            // THROWS: when we can't allocate a user id. add call to check if there's
9856            // enough space to ensure we won't throw; otherwise, don't modify state
9857            mSettings.addUserToSettingLPw(pkgSetting);
9858
9859            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
9860                mTransferedPackages.add(originalPkgSetting.name);
9861            }
9862        }
9863        // TODO(toddke): Consider a method specifically for modifying the Package object
9864        // post scan; or, moving this stuff out of the Package object since it has nothing
9865        // to do with the package on disk.
9866        // We need to have this here because addUserToSettingLPw() is sometimes responsible
9867        // for creating the application ID. If we did this earlier, we would be saving the
9868        // correct ID.
9869        pkg.applicationInfo.uid = pkgSetting.appId;
9870
9871        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9872
9873        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
9874            mTransferedPackages.add(pkg.packageName);
9875        }
9876
9877        // THROWS: when requested libraries that can't be found. it only changes
9878        // the state of the passed in pkg object, so, move to the top of the method
9879        // and allow it to abort
9880        if ((scanFlags & SCAN_BOOTING) == 0
9881                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9882            // Check all shared libraries and map to their actual file path.
9883            // We only do this here for apps not on a system dir, because those
9884            // are the only ones that can fail an install due to this.  We
9885            // will take care of the system apps by updating all of their
9886            // library paths after the scan is done. Also during the initial
9887            // scan don't update any libs as we do this wholesale after all
9888            // apps are scanned to avoid dependency based scanning.
9889            updateSharedLibrariesLPr(pkg, null);
9890        }
9891
9892        // All versions of a static shared library are referenced with the same
9893        // package name. Internally, we use a synthetic package name to allow
9894        // multiple versions of the same shared library to be installed. So,
9895        // we need to generate the synthetic package name of the latest shared
9896        // library in order to compare signatures.
9897        PackageSetting signatureCheckPs = pkgSetting;
9898        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9899            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9900            if (libraryEntry != null) {
9901                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9902            }
9903        }
9904
9905        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9906        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9907            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9908                // We just determined the app is signed correctly, so bring
9909                // over the latest parsed certs.
9910                pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures;
9911            } else {
9912                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9913                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9914                            "Package " + pkg.packageName + " upgrade keys do not match the "
9915                                    + "previously installed version");
9916                } else {
9917                    pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures;
9918                    String msg = "System package " + pkg.packageName
9919                            + " signature changed; retaining data.";
9920                    reportSettingsProblem(Log.WARN, msg);
9921                }
9922            }
9923        } else {
9924            try {
9925                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9926                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9927                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
9928                        pkg.mSigningDetails, compareCompat, compareRecover);
9929                // The new KeySets will be re-added later in the scanning process.
9930                if (compatMatch) {
9931                    synchronized (mPackages) {
9932                        ksms.removeAppKeySetDataLPw(pkg.packageName);
9933                    }
9934                }
9935                // We just determined the app is signed correctly, so bring
9936                // over the latest parsed certs.
9937                pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures;
9938            } catch (PackageManagerException e) {
9939                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9940                    throw e;
9941                }
9942                // The signature has changed, but this package is in the system
9943                // image...  let's recover!
9944                pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures;
9945                // However...  if this package is part of a shared user, but it
9946                // doesn't match the signature of the shared user, let's fail.
9947                // What this means is that you can't change the signatures
9948                // associated with an overall shared user, which doesn't seem all
9949                // that unreasonable.
9950                if (signatureCheckPs.sharedUser != null) {
9951                    if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9952                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
9953                        throw new PackageManagerException(
9954                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9955                                "Signature mismatch for shared user: "
9956                                        + pkgSetting.sharedUser);
9957                    }
9958                }
9959                // File a report about this.
9960                String msg = "System package " + pkg.packageName
9961                        + " signature changed; retaining data.";
9962                reportSettingsProblem(Log.WARN, msg);
9963            }
9964        }
9965
9966        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9967            // This package wants to adopt ownership of permissions from
9968            // another package.
9969            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9970                final String origName = pkg.mAdoptPermissions.get(i);
9971                final PackageSetting orig = mSettings.getPackageLPr(origName);
9972                if (orig != null) {
9973                    if (verifyPackageUpdateLPr(orig, pkg)) {
9974                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
9975                                + pkg.packageName);
9976                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9977                    }
9978                }
9979            }
9980        }
9981
9982        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
9983            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
9984                final String codePathString = changedAbiCodePath.get(i);
9985                try {
9986                    mInstaller.rmdex(codePathString,
9987                            getDexCodeInstructionSet(getPreferredInstructionSet()));
9988                } catch (InstallerException ignored) {
9989                }
9990            }
9991        }
9992
9993        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9994            if (oldPkgSetting != null) {
9995                synchronized (mPackages) {
9996                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
9997                }
9998            }
9999        } else {
10000            final int userId = user == null ? 0 : user.getIdentifier();
10001            // Modify state for the given package setting
10002            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10003                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10004            if (pkgSetting.getInstantApp(userId)) {
10005                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10006            }
10007        }
10008    }
10009
10010    /**
10011     * Returns the "real" name of the package.
10012     * <p>This may differ from the package's actual name if the application has already
10013     * been installed under one of this package's original names.
10014     */
10015    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10016            @Nullable String renamedPkgName) {
10017        if (isPackageRenamed(pkg, renamedPkgName)) {
10018            return pkg.mRealPackage;
10019        }
10020        return null;
10021    }
10022
10023    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10024    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10025            @Nullable String renamedPkgName) {
10026        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10027    }
10028
10029    /**
10030     * Returns the original package setting.
10031     * <p>A package can migrate its name during an update. In this scenario, a package
10032     * designates a set of names that it considers as one of its original names.
10033     * <p>An original package must be signed identically and it must have the same
10034     * shared user [if any].
10035     */
10036    @GuardedBy("mPackages")
10037    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10038            @Nullable String renamedPkgName) {
10039        if (!isPackageRenamed(pkg, renamedPkgName)) {
10040            return null;
10041        }
10042        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10043            final PackageSetting originalPs =
10044                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10045            if (originalPs != null) {
10046                // the package is already installed under its original name...
10047                // but, should we use it?
10048                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10049                    // the new package is incompatible with the original
10050                    continue;
10051                } else if (originalPs.sharedUser != null) {
10052                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10053                        // the shared user id is incompatible with the original
10054                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10055                                + " to " + pkg.packageName + ": old uid "
10056                                + originalPs.sharedUser.name
10057                                + " differs from " + pkg.mSharedUserId);
10058                        continue;
10059                    }
10060                    // TODO: Add case when shared user id is added [b/28144775]
10061                } else {
10062                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10063                            + pkg.packageName + " to old name " + originalPs.name);
10064                }
10065                return originalPs;
10066            }
10067        }
10068        return null;
10069    }
10070
10071    /**
10072     * Renames the package if it was installed under a different name.
10073     * <p>When we've already installed the package under an original name, update
10074     * the new package so we can continue to have the old name.
10075     */
10076    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10077            @NonNull String renamedPackageName) {
10078        if (pkg.mOriginalPackages == null
10079                || !pkg.mOriginalPackages.contains(renamedPackageName)
10080                || pkg.packageName.equals(renamedPackageName)) {
10081            return;
10082        }
10083        pkg.setPackageName(renamedPackageName);
10084    }
10085
10086    /**
10087     * Just scans the package without any side effects.
10088     * <p>Not entirely true at the moment. There is still one side effect -- this
10089     * method potentially modifies a live {@link PackageSetting} object representing
10090     * the package being scanned. This will be resolved in the future.
10091     *
10092     * @param request Information about the package to be scanned
10093     * @param isUnderFactoryTest Whether or not the device is under factory test
10094     * @param currentTime The current time, in millis
10095     * @return The results of the scan
10096     */
10097    @GuardedBy("mInstallLock")
10098    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10099            boolean isUnderFactoryTest, long currentTime)
10100                    throws PackageManagerException {
10101        final PackageParser.Package pkg = request.pkg;
10102        PackageSetting pkgSetting = request.pkgSetting;
10103        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10104        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10105        final @ParseFlags int parseFlags = request.parseFlags;
10106        final @ScanFlags int scanFlags = request.scanFlags;
10107        final String realPkgName = request.realPkgName;
10108        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10109        final UserHandle user = request.user;
10110        final boolean isPlatformPackage = request.isPlatformPackage;
10111
10112        List<String> changedAbiCodePath = null;
10113
10114        if (DEBUG_PACKAGE_SCANNING) {
10115            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10116                Log.d(TAG, "Scanning package " + pkg.packageName);
10117        }
10118
10119        if (Build.IS_DEBUGGABLE &&
10120                pkg.isPrivileged() &&
10121                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10122            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10123        }
10124
10125        // Initialize package source and resource directories
10126        final File scanFile = new File(pkg.codePath);
10127        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10128        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10129
10130        // We keep references to the derived CPU Abis from settings in oder to reuse
10131        // them in the case where we're not upgrading or booting for the first time.
10132        String primaryCpuAbiFromSettings = null;
10133        String secondaryCpuAbiFromSettings = null;
10134        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10135
10136        if (!needToDeriveAbi) {
10137            if (pkgSetting != null) {
10138                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10139                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10140            } else {
10141                // Re-scanning a system package after uninstalling updates; need to derive ABI
10142                needToDeriveAbi = true;
10143            }
10144        }
10145
10146        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10147            PackageManagerService.reportSettingsProblem(Log.WARN,
10148                    "Package " + pkg.packageName + " shared user changed from "
10149                            + (pkgSetting.sharedUser != null
10150                            ? pkgSetting.sharedUser.name : "<nothing>")
10151                            + " to "
10152                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10153                            + "; replacing with new");
10154            pkgSetting = null;
10155        }
10156
10157        String[] usesStaticLibraries = null;
10158        if (pkg.usesStaticLibraries != null) {
10159            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10160            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10161        }
10162        final boolean createNewPackage = (pkgSetting == null);
10163        if (createNewPackage) {
10164            final String parentPackageName = (pkg.parentPackage != null)
10165                    ? pkg.parentPackage.packageName : null;
10166            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10167            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10168            // REMOVE SharedUserSetting from method; update in a separate call
10169            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10170                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10171                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10172                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10173                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10174                    user, true /*allowInstall*/, instantApp, virtualPreload,
10175                    parentPackageName, pkg.getChildPackageNames(),
10176                    UserManagerService.getInstance(), usesStaticLibraries,
10177                    pkg.usesStaticLibrariesVersions);
10178        } else {
10179            // REMOVE SharedUserSetting from method; update in a separate call.
10180            //
10181            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10182            // secondaryCpuAbi are not known at this point so we always update them
10183            // to null here, only to reset them at a later point.
10184            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10185                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10186                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10187                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10188                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10189                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10190        }
10191        if (createNewPackage && originalPkgSetting != null) {
10192            // This is the initial transition from the original package, so,
10193            // fix up the new package's name now. We must do this after looking
10194            // up the package under its new name, so getPackageLP takes care of
10195            // fiddling things correctly.
10196            pkg.setPackageName(originalPkgSetting.name);
10197
10198            // File a report about this.
10199            String msg = "New package " + pkgSetting.realName
10200                    + " renamed to replace old package " + pkgSetting.name;
10201            reportSettingsProblem(Log.WARN, msg);
10202        }
10203
10204        if (disabledPkgSetting != null) {
10205            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10206        }
10207
10208        SELinuxMMAC.assignSeInfoValue(pkg);
10209
10210        pkg.mExtras = pkgSetting;
10211        pkg.applicationInfo.processName = fixProcessName(
10212                pkg.applicationInfo.packageName,
10213                pkg.applicationInfo.processName);
10214
10215        if (!isPlatformPackage) {
10216            // Get all of our default paths setup
10217            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10218        }
10219
10220        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10221
10222        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10223            if (needToDeriveAbi) {
10224                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10225                final boolean extractNativeLibs = !pkg.isLibrary();
10226                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10227                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10228
10229                // Some system apps still use directory structure for native libraries
10230                // in which case we might end up not detecting abi solely based on apk
10231                // structure. Try to detect abi based on directory structure.
10232                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10233                        pkg.applicationInfo.primaryCpuAbi == null) {
10234                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10235                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10236                }
10237            } else {
10238                // This is not a first boot or an upgrade, don't bother deriving the
10239                // ABI during the scan. Instead, trust the value that was stored in the
10240                // package setting.
10241                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10242                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10243
10244                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10245
10246                if (DEBUG_ABI_SELECTION) {
10247                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10248                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10249                            pkg.applicationInfo.secondaryCpuAbi);
10250                }
10251            }
10252        } else {
10253            if ((scanFlags & SCAN_MOVE) != 0) {
10254                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10255                // but we already have this packages package info in the PackageSetting. We just
10256                // use that and derive the native library path based on the new codepath.
10257                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10258                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10259            }
10260
10261            // Set native library paths again. For moves, the path will be updated based on the
10262            // ABIs we've determined above. For non-moves, the path will be updated based on the
10263            // ABIs we determined during compilation, but the path will depend on the final
10264            // package path (after the rename away from the stage path).
10265            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10266        }
10267
10268        // This is a special case for the "system" package, where the ABI is
10269        // dictated by the zygote configuration (and init.rc). We should keep track
10270        // of this ABI so that we can deal with "normal" applications that run under
10271        // the same UID correctly.
10272        if (isPlatformPackage) {
10273            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10274                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10275        }
10276
10277        // If there's a mismatch between the abi-override in the package setting
10278        // and the abiOverride specified for the install. Warn about this because we
10279        // would've already compiled the app without taking the package setting into
10280        // account.
10281        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10282            if (cpuAbiOverride == null && pkg.packageName != null) {
10283                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10284                        " for package " + pkg.packageName);
10285            }
10286        }
10287
10288        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10289        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10290        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10291
10292        // Copy the derived override back to the parsed package, so that we can
10293        // update the package settings accordingly.
10294        pkg.cpuAbiOverride = cpuAbiOverride;
10295
10296        if (DEBUG_ABI_SELECTION) {
10297            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10298                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10299                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10300        }
10301
10302        // Push the derived path down into PackageSettings so we know what to
10303        // clean up at uninstall time.
10304        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10305
10306        if (DEBUG_ABI_SELECTION) {
10307            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10308                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10309                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10310        }
10311
10312        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10313            // We don't do this here during boot because we can do it all
10314            // at once after scanning all existing packages.
10315            //
10316            // We also do this *before* we perform dexopt on this package, so that
10317            // we can avoid redundant dexopts, and also to make sure we've got the
10318            // code and package path correct.
10319            changedAbiCodePath =
10320                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10321        }
10322
10323        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10324                android.Manifest.permission.FACTORY_TEST)) {
10325            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10326        }
10327
10328        if (isSystemApp(pkg)) {
10329            pkgSetting.isOrphaned = true;
10330        }
10331
10332        // Take care of first install / last update times.
10333        final long scanFileTime = getLastModifiedTime(pkg);
10334        if (currentTime != 0) {
10335            if (pkgSetting.firstInstallTime == 0) {
10336                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10337            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10338                pkgSetting.lastUpdateTime = currentTime;
10339            }
10340        } else if (pkgSetting.firstInstallTime == 0) {
10341            // We need *something*.  Take time time stamp of the file.
10342            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10343        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10344            if (scanFileTime != pkgSetting.timeStamp) {
10345                // A package on the system image has changed; consider this
10346                // to be an update.
10347                pkgSetting.lastUpdateTime = scanFileTime;
10348            }
10349        }
10350        pkgSetting.setTimeStamp(scanFileTime);
10351
10352        pkgSetting.pkg = pkg;
10353        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10354        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10355            pkgSetting.versionCode = pkg.getLongVersionCode();
10356        }
10357        // Update volume if needed
10358        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10359        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10360            Slog.i(PackageManagerService.TAG,
10361                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10362                    + " package " + pkg.packageName
10363                    + " volume from " + pkgSetting.volumeUuid
10364                    + " to " + volumeUuid);
10365            pkgSetting.volumeUuid = volumeUuid;
10366        }
10367
10368        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10369    }
10370
10371    /**
10372     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10373     */
10374    private static boolean apkHasCode(String fileName) {
10375        StrictJarFile jarFile = null;
10376        try {
10377            jarFile = new StrictJarFile(fileName,
10378                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10379            return jarFile.findEntry("classes.dex") != null;
10380        } catch (IOException ignore) {
10381        } finally {
10382            try {
10383                if (jarFile != null) {
10384                    jarFile.close();
10385                }
10386            } catch (IOException ignore) {}
10387        }
10388        return false;
10389    }
10390
10391    /**
10392     * Enforces code policy for the package. This ensures that if an APK has
10393     * declared hasCode="true" in its manifest that the APK actually contains
10394     * code.
10395     *
10396     * @throws PackageManagerException If bytecode could not be found when it should exist
10397     */
10398    private static void assertCodePolicy(PackageParser.Package pkg)
10399            throws PackageManagerException {
10400        final boolean shouldHaveCode =
10401                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10402        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10403            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10404                    "Package " + pkg.baseCodePath + " code is missing");
10405        }
10406
10407        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10408            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10409                final boolean splitShouldHaveCode =
10410                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10411                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10412                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10413                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10414                }
10415            }
10416        }
10417    }
10418
10419    /**
10420     * Applies policy to the parsed package based upon the given policy flags.
10421     * Ensures the package is in a good state.
10422     * <p>
10423     * Implementation detail: This method must NOT have any side effect. It would
10424     * ideally be static, but, it requires locks to read system state.
10425     */
10426    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10427            final @ScanFlags int scanFlags) {
10428        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10429            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10430            if (pkg.applicationInfo.isDirectBootAware()) {
10431                // we're direct boot aware; set for all components
10432                for (PackageParser.Service s : pkg.services) {
10433                    s.info.encryptionAware = s.info.directBootAware = true;
10434                }
10435                for (PackageParser.Provider p : pkg.providers) {
10436                    p.info.encryptionAware = p.info.directBootAware = true;
10437                }
10438                for (PackageParser.Activity a : pkg.activities) {
10439                    a.info.encryptionAware = a.info.directBootAware = true;
10440                }
10441                for (PackageParser.Activity r : pkg.receivers) {
10442                    r.info.encryptionAware = r.info.directBootAware = true;
10443                }
10444            }
10445            if (compressedFileExists(pkg.codePath)) {
10446                pkg.isStub = true;
10447            }
10448        } else {
10449            // non system apps can't be flagged as core
10450            pkg.coreApp = false;
10451            // clear flags not applicable to regular apps
10452            pkg.applicationInfo.flags &=
10453                    ~ApplicationInfo.FLAG_PERSISTENT;
10454            pkg.applicationInfo.privateFlags &=
10455                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10456            pkg.applicationInfo.privateFlags &=
10457                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10458            // clear protected broadcasts
10459            pkg.protectedBroadcasts = null;
10460            // cap permission priorities
10461            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10462                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10463                    pkg.permissionGroups.get(i).info.priority = 0;
10464                }
10465            }
10466        }
10467        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10468            // ignore export request for single user receivers
10469            if (pkg.receivers != null) {
10470                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10471                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10472                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10473                        receiver.info.exported = false;
10474                    }
10475                }
10476            }
10477            // ignore export request for single user services
10478            if (pkg.services != null) {
10479                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10480                    final PackageParser.Service service = pkg.services.get(i);
10481                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10482                        service.info.exported = false;
10483                    }
10484                }
10485            }
10486            // ignore export request for single user providers
10487            if (pkg.providers != null) {
10488                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10489                    final PackageParser.Provider provider = pkg.providers.get(i);
10490                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10491                        provider.info.exported = false;
10492                    }
10493                }
10494            }
10495        }
10496        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10497
10498        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10499            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10500        }
10501
10502        if ((scanFlags & SCAN_AS_OEM) != 0) {
10503            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10504        }
10505
10506        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10507            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10508        }
10509
10510        if (!isSystemApp(pkg)) {
10511            // Only system apps can use these features.
10512            pkg.mOriginalPackages = null;
10513            pkg.mRealPackage = null;
10514            pkg.mAdoptPermissions = null;
10515        }
10516    }
10517
10518    /**
10519     * Asserts the parsed package is valid according to the given policy. If the
10520     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10521     * <p>
10522     * Implementation detail: This method must NOT have any side effects. It would
10523     * ideally be static, but, it requires locks to read system state.
10524     *
10525     * @throws PackageManagerException If the package fails any of the validation checks
10526     */
10527    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10528            final @ScanFlags int scanFlags)
10529                    throws PackageManagerException {
10530        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10531            assertCodePolicy(pkg);
10532        }
10533
10534        if (pkg.applicationInfo.getCodePath() == null ||
10535                pkg.applicationInfo.getResourcePath() == null) {
10536            // Bail out. The resource and code paths haven't been set.
10537            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10538                    "Code and resource paths haven't been set correctly");
10539        }
10540
10541        // Make sure we're not adding any bogus keyset info
10542        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10543        ksms.assertScannedPackageValid(pkg);
10544
10545        synchronized (mPackages) {
10546            // The special "android" package can only be defined once
10547            if (pkg.packageName.equals("android")) {
10548                if (mAndroidApplication != null) {
10549                    Slog.w(TAG, "*************************************************");
10550                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10551                    Slog.w(TAG, " codePath=" + pkg.codePath);
10552                    Slog.w(TAG, "*************************************************");
10553                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10554                            "Core android package being redefined.  Skipping.");
10555                }
10556            }
10557
10558            // A package name must be unique; don't allow duplicates
10559            if (mPackages.containsKey(pkg.packageName)) {
10560                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10561                        "Application package " + pkg.packageName
10562                        + " already installed.  Skipping duplicate.");
10563            }
10564
10565            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10566                // Static libs have a synthetic package name containing the version
10567                // but we still want the base name to be unique.
10568                if (mPackages.containsKey(pkg.manifestPackageName)) {
10569                    throw new PackageManagerException(
10570                            "Duplicate static shared lib provider package");
10571                }
10572
10573                // Static shared libraries should have at least O target SDK
10574                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10575                    throw new PackageManagerException(
10576                            "Packages declaring static-shared libs must target O SDK or higher");
10577                }
10578
10579                // Package declaring static a shared lib cannot be instant apps
10580                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10581                    throw new PackageManagerException(
10582                            "Packages declaring static-shared libs cannot be instant apps");
10583                }
10584
10585                // Package declaring static a shared lib cannot be renamed since the package
10586                // name is synthetic and apps can't code around package manager internals.
10587                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10588                    throw new PackageManagerException(
10589                            "Packages declaring static-shared libs cannot be renamed");
10590                }
10591
10592                // Package declaring static a shared lib cannot declare child packages
10593                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10594                    throw new PackageManagerException(
10595                            "Packages declaring static-shared libs cannot have child packages");
10596                }
10597
10598                // Package declaring static a shared lib cannot declare dynamic libs
10599                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10600                    throw new PackageManagerException(
10601                            "Packages declaring static-shared libs cannot declare dynamic libs");
10602                }
10603
10604                // Package declaring static a shared lib cannot declare shared users
10605                if (pkg.mSharedUserId != null) {
10606                    throw new PackageManagerException(
10607                            "Packages declaring static-shared libs cannot declare shared users");
10608                }
10609
10610                // Static shared libs cannot declare activities
10611                if (!pkg.activities.isEmpty()) {
10612                    throw new PackageManagerException(
10613                            "Static shared libs cannot declare activities");
10614                }
10615
10616                // Static shared libs cannot declare services
10617                if (!pkg.services.isEmpty()) {
10618                    throw new PackageManagerException(
10619                            "Static shared libs cannot declare services");
10620                }
10621
10622                // Static shared libs cannot declare providers
10623                if (!pkg.providers.isEmpty()) {
10624                    throw new PackageManagerException(
10625                            "Static shared libs cannot declare content providers");
10626                }
10627
10628                // Static shared libs cannot declare receivers
10629                if (!pkg.receivers.isEmpty()) {
10630                    throw new PackageManagerException(
10631                            "Static shared libs cannot declare broadcast receivers");
10632                }
10633
10634                // Static shared libs cannot declare permission groups
10635                if (!pkg.permissionGroups.isEmpty()) {
10636                    throw new PackageManagerException(
10637                            "Static shared libs cannot declare permission groups");
10638                }
10639
10640                // Static shared libs cannot declare permissions
10641                if (!pkg.permissions.isEmpty()) {
10642                    throw new PackageManagerException(
10643                            "Static shared libs cannot declare permissions");
10644                }
10645
10646                // Static shared libs cannot declare protected broadcasts
10647                if (pkg.protectedBroadcasts != null) {
10648                    throw new PackageManagerException(
10649                            "Static shared libs cannot declare protected broadcasts");
10650                }
10651
10652                // Static shared libs cannot be overlay targets
10653                if (pkg.mOverlayTarget != null) {
10654                    throw new PackageManagerException(
10655                            "Static shared libs cannot be overlay targets");
10656                }
10657
10658                // The version codes must be ordered as lib versions
10659                long minVersionCode = Long.MIN_VALUE;
10660                long maxVersionCode = Long.MAX_VALUE;
10661
10662                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10663                        pkg.staticSharedLibName);
10664                if (versionedLib != null) {
10665                    final int versionCount = versionedLib.size();
10666                    for (int i = 0; i < versionCount; i++) {
10667                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10668                        final long libVersionCode = libInfo.getDeclaringPackage()
10669                                .getLongVersionCode();
10670                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10671                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10672                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10673                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10674                        } else {
10675                            minVersionCode = maxVersionCode = libVersionCode;
10676                            break;
10677                        }
10678                    }
10679                }
10680                if (pkg.getLongVersionCode() < minVersionCode
10681                        || pkg.getLongVersionCode() > maxVersionCode) {
10682                    throw new PackageManagerException("Static shared"
10683                            + " lib version codes must be ordered as lib versions");
10684                }
10685            }
10686
10687            // Only privileged apps and updated privileged apps can add child packages.
10688            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10689                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10690                    throw new PackageManagerException("Only privileged apps can add child "
10691                            + "packages. Ignoring package " + pkg.packageName);
10692                }
10693                final int childCount = pkg.childPackages.size();
10694                for (int i = 0; i < childCount; i++) {
10695                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10696                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10697                            childPkg.packageName)) {
10698                        throw new PackageManagerException("Can't override child of "
10699                                + "another disabled app. Ignoring package " + pkg.packageName);
10700                    }
10701                }
10702            }
10703
10704            // If we're only installing presumed-existing packages, require that the
10705            // scanned APK is both already known and at the path previously established
10706            // for it.  Previously unknown packages we pick up normally, but if we have an
10707            // a priori expectation about this package's install presence, enforce it.
10708            // With a singular exception for new system packages. When an OTA contains
10709            // a new system package, we allow the codepath to change from a system location
10710            // to the user-installed location. If we don't allow this change, any newer,
10711            // user-installed version of the application will be ignored.
10712            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10713                if (mExpectingBetter.containsKey(pkg.packageName)) {
10714                    logCriticalInfo(Log.WARN,
10715                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10716                } else {
10717                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10718                    if (known != null) {
10719                        if (DEBUG_PACKAGE_SCANNING) {
10720                            Log.d(TAG, "Examining " + pkg.codePath
10721                                    + " and requiring known paths " + known.codePathString
10722                                    + " & " + known.resourcePathString);
10723                        }
10724                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10725                                || !pkg.applicationInfo.getResourcePath().equals(
10726                                        known.resourcePathString)) {
10727                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10728                                    "Application package " + pkg.packageName
10729                                    + " found at " + pkg.applicationInfo.getCodePath()
10730                                    + " but expected at " + known.codePathString
10731                                    + "; ignoring.");
10732                        }
10733                    } else {
10734                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10735                                "Application package " + pkg.packageName
10736                                + " not found; ignoring.");
10737                    }
10738                }
10739            }
10740
10741            // Verify that this new package doesn't have any content providers
10742            // that conflict with existing packages.  Only do this if the
10743            // package isn't already installed, since we don't want to break
10744            // things that are installed.
10745            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10746                final int N = pkg.providers.size();
10747                int i;
10748                for (i=0; i<N; i++) {
10749                    PackageParser.Provider p = pkg.providers.get(i);
10750                    if (p.info.authority != null) {
10751                        String names[] = p.info.authority.split(";");
10752                        for (int j = 0; j < names.length; j++) {
10753                            if (mProvidersByAuthority.containsKey(names[j])) {
10754                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10755                                final String otherPackageName =
10756                                        ((other != null && other.getComponentName() != null) ?
10757                                                other.getComponentName().getPackageName() : "?");
10758                                throw new PackageManagerException(
10759                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10760                                        "Can't install because provider name " + names[j]
10761                                                + " (in package " + pkg.applicationInfo.packageName
10762                                                + ") is already used by " + otherPackageName);
10763                            }
10764                        }
10765                    }
10766                }
10767            }
10768
10769            // Verify that packages sharing a user with a privileged app are marked as privileged.
10770            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10771                SharedUserSetting sharedUserSetting = null;
10772                try {
10773                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10774                } catch (PackageManagerException ignore) {}
10775                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10776                    // Exempt SharedUsers signed with the platform key.
10777                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10778                    if ((platformPkgSetting.signatures.mSignatures != null) &&
10779                            (compareSignatures(platformPkgSetting.signatures.mSignatures,
10780                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10781                        throw new PackageManagerException("Apps that share a user with a " +
10782                                "privileged app must themselves be marked as privileged. " +
10783                                pkg.packageName + " shares privileged user " +
10784                                pkg.mSharedUserId + ".");
10785                    }
10786                }
10787            }
10788        }
10789    }
10790
10791    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
10792            int type, String declaringPackageName, long declaringVersionCode) {
10793        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10794        if (versionedLib == null) {
10795            versionedLib = new LongSparseArray<>();
10796            mSharedLibraries.put(name, versionedLib);
10797            if (type == SharedLibraryInfo.TYPE_STATIC) {
10798                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10799            }
10800        } else if (versionedLib.indexOfKey(version) >= 0) {
10801            return false;
10802        }
10803        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10804                version, type, declaringPackageName, declaringVersionCode);
10805        versionedLib.put(version, libEntry);
10806        return true;
10807    }
10808
10809    private boolean removeSharedLibraryLPw(String name, long version) {
10810        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10811        if (versionedLib == null) {
10812            return false;
10813        }
10814        final int libIdx = versionedLib.indexOfKey(version);
10815        if (libIdx < 0) {
10816            return false;
10817        }
10818        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10819        versionedLib.remove(version);
10820        if (versionedLib.size() <= 0) {
10821            mSharedLibraries.remove(name);
10822            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10823                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10824                        .getPackageName());
10825            }
10826        }
10827        return true;
10828    }
10829
10830    /**
10831     * Adds a scanned package to the system. When this method is finished, the package will
10832     * be available for query, resolution, etc...
10833     */
10834    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10835            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
10836        final String pkgName = pkg.packageName;
10837        if (mCustomResolverComponentName != null &&
10838                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10839            setUpCustomResolverActivity(pkg);
10840        }
10841
10842        if (pkg.packageName.equals("android")) {
10843            synchronized (mPackages) {
10844                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10845                    // Set up information for our fall-back user intent resolution activity.
10846                    mPlatformPackage = pkg;
10847                    pkg.mVersionCode = mSdkVersion;
10848                    pkg.mVersionCodeMajor = 0;
10849                    mAndroidApplication = pkg.applicationInfo;
10850                    if (!mResolverReplaced) {
10851                        mResolveActivity.applicationInfo = mAndroidApplication;
10852                        mResolveActivity.name = ResolverActivity.class.getName();
10853                        mResolveActivity.packageName = mAndroidApplication.packageName;
10854                        mResolveActivity.processName = "system:ui";
10855                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10856                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10857                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10858                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10859                        mResolveActivity.exported = true;
10860                        mResolveActivity.enabled = true;
10861                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10862                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10863                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10864                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10865                                | ActivityInfo.CONFIG_ORIENTATION
10866                                | ActivityInfo.CONFIG_KEYBOARD
10867                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10868                        mResolveInfo.activityInfo = mResolveActivity;
10869                        mResolveInfo.priority = 0;
10870                        mResolveInfo.preferredOrder = 0;
10871                        mResolveInfo.match = 0;
10872                        mResolveComponentName = new ComponentName(
10873                                mAndroidApplication.packageName, mResolveActivity.name);
10874                    }
10875                }
10876            }
10877        }
10878
10879        ArrayList<PackageParser.Package> clientLibPkgs = null;
10880        // writer
10881        synchronized (mPackages) {
10882            boolean hasStaticSharedLibs = false;
10883
10884            // Any app can add new static shared libraries
10885            if (pkg.staticSharedLibName != null) {
10886                // Static shared libs don't allow renaming as they have synthetic package
10887                // names to allow install of multiple versions, so use name from manifest.
10888                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10889                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10890                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
10891                    hasStaticSharedLibs = true;
10892                } else {
10893                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10894                                + pkg.staticSharedLibName + " already exists; skipping");
10895                }
10896                // Static shared libs cannot be updated once installed since they
10897                // use synthetic package name which includes the version code, so
10898                // not need to update other packages's shared lib dependencies.
10899            }
10900
10901            if (!hasStaticSharedLibs
10902                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10903                // Only system apps can add new dynamic shared libraries.
10904                if (pkg.libraryNames != null) {
10905                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10906                        String name = pkg.libraryNames.get(i);
10907                        boolean allowed = false;
10908                        if (pkg.isUpdatedSystemApp()) {
10909                            // New library entries can only be added through the
10910                            // system image.  This is important to get rid of a lot
10911                            // of nasty edge cases: for example if we allowed a non-
10912                            // system update of the app to add a library, then uninstalling
10913                            // the update would make the library go away, and assumptions
10914                            // we made such as through app install filtering would now
10915                            // have allowed apps on the device which aren't compatible
10916                            // with it.  Better to just have the restriction here, be
10917                            // conservative, and create many fewer cases that can negatively
10918                            // impact the user experience.
10919                            final PackageSetting sysPs = mSettings
10920                                    .getDisabledSystemPkgLPr(pkg.packageName);
10921                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10922                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10923                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10924                                        allowed = true;
10925                                        break;
10926                                    }
10927                                }
10928                            }
10929                        } else {
10930                            allowed = true;
10931                        }
10932                        if (allowed) {
10933                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10934                                    SharedLibraryInfo.VERSION_UNDEFINED,
10935                                    SharedLibraryInfo.TYPE_DYNAMIC,
10936                                    pkg.packageName, pkg.getLongVersionCode())) {
10937                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10938                                        + name + " already exists; skipping");
10939                            }
10940                        } else {
10941                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10942                                    + name + " that is not declared on system image; skipping");
10943                        }
10944                    }
10945
10946                    if ((scanFlags & SCAN_BOOTING) == 0) {
10947                        // If we are not booting, we need to update any applications
10948                        // that are clients of our shared library.  If we are booting,
10949                        // this will all be done once the scan is complete.
10950                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10951                    }
10952                }
10953            }
10954        }
10955
10956        if ((scanFlags & SCAN_BOOTING) != 0) {
10957            // No apps can run during boot scan, so they don't need to be frozen
10958        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10959            // Caller asked to not kill app, so it's probably not frozen
10960        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10961            // Caller asked us to ignore frozen check for some reason; they
10962            // probably didn't know the package name
10963        } else {
10964            // We're doing major surgery on this package, so it better be frozen
10965            // right now to keep it from launching
10966            checkPackageFrozen(pkgName);
10967        }
10968
10969        // Also need to kill any apps that are dependent on the library.
10970        if (clientLibPkgs != null) {
10971            for (int i=0; i<clientLibPkgs.size(); i++) {
10972                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10973                killApplication(clientPkg.applicationInfo.packageName,
10974                        clientPkg.applicationInfo.uid, "update lib");
10975            }
10976        }
10977
10978        // writer
10979        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10980
10981        synchronized (mPackages) {
10982            // We don't expect installation to fail beyond this point
10983
10984            // Add the new setting to mSettings
10985            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10986            // Add the new setting to mPackages
10987            mPackages.put(pkg.applicationInfo.packageName, pkg);
10988            // Make sure we don't accidentally delete its data.
10989            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10990            while (iter.hasNext()) {
10991                PackageCleanItem item = iter.next();
10992                if (pkgName.equals(item.packageName)) {
10993                    iter.remove();
10994                }
10995            }
10996
10997            // Add the package's KeySets to the global KeySetManagerService
10998            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10999            ksms.addScannedPackageLPw(pkg);
11000
11001            int N = pkg.providers.size();
11002            StringBuilder r = null;
11003            int i;
11004            for (i=0; i<N; i++) {
11005                PackageParser.Provider p = pkg.providers.get(i);
11006                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11007                        p.info.processName);
11008                mProviders.addProvider(p);
11009                p.syncable = p.info.isSyncable;
11010                if (p.info.authority != null) {
11011                    String names[] = p.info.authority.split(";");
11012                    p.info.authority = null;
11013                    for (int j = 0; j < names.length; j++) {
11014                        if (j == 1 && p.syncable) {
11015                            // We only want the first authority for a provider to possibly be
11016                            // syncable, so if we already added this provider using a different
11017                            // authority clear the syncable flag. We copy the provider before
11018                            // changing it because the mProviders object contains a reference
11019                            // to a provider that we don't want to change.
11020                            // Only do this for the second authority since the resulting provider
11021                            // object can be the same for all future authorities for this provider.
11022                            p = new PackageParser.Provider(p);
11023                            p.syncable = false;
11024                        }
11025                        if (!mProvidersByAuthority.containsKey(names[j])) {
11026                            mProvidersByAuthority.put(names[j], p);
11027                            if (p.info.authority == null) {
11028                                p.info.authority = names[j];
11029                            } else {
11030                                p.info.authority = p.info.authority + ";" + names[j];
11031                            }
11032                            if (DEBUG_PACKAGE_SCANNING) {
11033                                if (chatty)
11034                                    Log.d(TAG, "Registered content provider: " + names[j]
11035                                            + ", className = " + p.info.name + ", isSyncable = "
11036                                            + p.info.isSyncable);
11037                            }
11038                        } else {
11039                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11040                            Slog.w(TAG, "Skipping provider name " + names[j] +
11041                                    " (in package " + pkg.applicationInfo.packageName +
11042                                    "): name already used by "
11043                                    + ((other != null && other.getComponentName() != null)
11044                                            ? other.getComponentName().getPackageName() : "?"));
11045                        }
11046                    }
11047                }
11048                if (chatty) {
11049                    if (r == null) {
11050                        r = new StringBuilder(256);
11051                    } else {
11052                        r.append(' ');
11053                    }
11054                    r.append(p.info.name);
11055                }
11056            }
11057            if (r != null) {
11058                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11059            }
11060
11061            N = pkg.services.size();
11062            r = null;
11063            for (i=0; i<N; i++) {
11064                PackageParser.Service s = pkg.services.get(i);
11065                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11066                        s.info.processName);
11067                mServices.addService(s);
11068                if (chatty) {
11069                    if (r == null) {
11070                        r = new StringBuilder(256);
11071                    } else {
11072                        r.append(' ');
11073                    }
11074                    r.append(s.info.name);
11075                }
11076            }
11077            if (r != null) {
11078                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11079            }
11080
11081            N = pkg.receivers.size();
11082            r = null;
11083            for (i=0; i<N; i++) {
11084                PackageParser.Activity a = pkg.receivers.get(i);
11085                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11086                        a.info.processName);
11087                mReceivers.addActivity(a, "receiver");
11088                if (chatty) {
11089                    if (r == null) {
11090                        r = new StringBuilder(256);
11091                    } else {
11092                        r.append(' ');
11093                    }
11094                    r.append(a.info.name);
11095                }
11096            }
11097            if (r != null) {
11098                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11099            }
11100
11101            N = pkg.activities.size();
11102            r = null;
11103            for (i=0; i<N; i++) {
11104                PackageParser.Activity a = pkg.activities.get(i);
11105                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11106                        a.info.processName);
11107                mActivities.addActivity(a, "activity");
11108                if (chatty) {
11109                    if (r == null) {
11110                        r = new StringBuilder(256);
11111                    } else {
11112                        r.append(' ');
11113                    }
11114                    r.append(a.info.name);
11115                }
11116            }
11117            if (r != null) {
11118                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11119            }
11120
11121            // Don't allow ephemeral applications to define new permissions groups.
11122            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11123                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11124                        + " ignored: instant apps cannot define new permission groups.");
11125            } else {
11126                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11127            }
11128
11129            // Don't allow ephemeral applications to define new permissions.
11130            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11131                Slog.w(TAG, "Permissions from package " + pkg.packageName
11132                        + " ignored: instant apps cannot define new permissions.");
11133            } else {
11134                mPermissionManager.addAllPermissions(pkg, chatty);
11135            }
11136
11137            N = pkg.instrumentation.size();
11138            r = null;
11139            for (i=0; i<N; i++) {
11140                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11141                a.info.packageName = pkg.applicationInfo.packageName;
11142                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11143                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11144                a.info.splitNames = pkg.splitNames;
11145                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11146                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11147                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11148                a.info.dataDir = pkg.applicationInfo.dataDir;
11149                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11150                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11151                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11152                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11153                mInstrumentation.put(a.getComponentName(), a);
11154                if (chatty) {
11155                    if (r == null) {
11156                        r = new StringBuilder(256);
11157                    } else {
11158                        r.append(' ');
11159                    }
11160                    r.append(a.info.name);
11161                }
11162            }
11163            if (r != null) {
11164                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11165            }
11166
11167            if (pkg.protectedBroadcasts != null) {
11168                N = pkg.protectedBroadcasts.size();
11169                synchronized (mProtectedBroadcasts) {
11170                    for (i = 0; i < N; i++) {
11171                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11172                    }
11173                }
11174            }
11175        }
11176
11177        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11178    }
11179
11180    /**
11181     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11182     * is derived purely on the basis of the contents of {@code scanFile} and
11183     * {@code cpuAbiOverride}.
11184     *
11185     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11186     */
11187    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11188            boolean extractLibs)
11189                    throws PackageManagerException {
11190        // Give ourselves some initial paths; we'll come back for another
11191        // pass once we've determined ABI below.
11192        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11193
11194        // We would never need to extract libs for forward-locked and external packages,
11195        // since the container service will do it for us. We shouldn't attempt to
11196        // extract libs from system app when it was not updated.
11197        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11198                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11199            extractLibs = false;
11200        }
11201
11202        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11203        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11204
11205        NativeLibraryHelper.Handle handle = null;
11206        try {
11207            handle = NativeLibraryHelper.Handle.create(pkg);
11208            // TODO(multiArch): This can be null for apps that didn't go through the
11209            // usual installation process. We can calculate it again, like we
11210            // do during install time.
11211            //
11212            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11213            // unnecessary.
11214            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11215
11216            // Null out the abis so that they can be recalculated.
11217            pkg.applicationInfo.primaryCpuAbi = null;
11218            pkg.applicationInfo.secondaryCpuAbi = null;
11219            if (isMultiArch(pkg.applicationInfo)) {
11220                // Warn if we've set an abiOverride for multi-lib packages..
11221                // By definition, we need to copy both 32 and 64 bit libraries for
11222                // such packages.
11223                if (pkg.cpuAbiOverride != null
11224                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11225                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11226                }
11227
11228                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11229                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11230                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11231                    if (extractLibs) {
11232                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11233                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11234                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11235                                useIsaSpecificSubdirs);
11236                    } else {
11237                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11238                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11239                    }
11240                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11241                }
11242
11243                // Shared library native code should be in the APK zip aligned
11244                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11245                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11246                            "Shared library native lib extraction not supported");
11247                }
11248
11249                maybeThrowExceptionForMultiArchCopy(
11250                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11251
11252                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11253                    if (extractLibs) {
11254                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11255                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11256                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11257                                useIsaSpecificSubdirs);
11258                    } else {
11259                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11260                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11261                    }
11262                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11263                }
11264
11265                maybeThrowExceptionForMultiArchCopy(
11266                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11267
11268                if (abi64 >= 0) {
11269                    // Shared library native libs should be in the APK zip aligned
11270                    if (extractLibs && pkg.isLibrary()) {
11271                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11272                                "Shared library native lib extraction not supported");
11273                    }
11274                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11275                }
11276
11277                if (abi32 >= 0) {
11278                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11279                    if (abi64 >= 0) {
11280                        if (pkg.use32bitAbi) {
11281                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11282                            pkg.applicationInfo.primaryCpuAbi = abi;
11283                        } else {
11284                            pkg.applicationInfo.secondaryCpuAbi = abi;
11285                        }
11286                    } else {
11287                        pkg.applicationInfo.primaryCpuAbi = abi;
11288                    }
11289                }
11290            } else {
11291                String[] abiList = (cpuAbiOverride != null) ?
11292                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11293
11294                // Enable gross and lame hacks for apps that are built with old
11295                // SDK tools. We must scan their APKs for renderscript bitcode and
11296                // not launch them if it's present. Don't bother checking on devices
11297                // that don't have 64 bit support.
11298                boolean needsRenderScriptOverride = false;
11299                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11300                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11301                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11302                    needsRenderScriptOverride = true;
11303                }
11304
11305                final int copyRet;
11306                if (extractLibs) {
11307                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11308                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11309                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11310                } else {
11311                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11312                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11313                }
11314                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11315
11316                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11317                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11318                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11319                }
11320
11321                if (copyRet >= 0) {
11322                    // Shared libraries that have native libs must be multi-architecture
11323                    if (pkg.isLibrary()) {
11324                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11325                                "Shared library with native libs must be multiarch");
11326                    }
11327                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11328                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11329                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11330                } else if (needsRenderScriptOverride) {
11331                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11332                }
11333            }
11334        } catch (IOException ioe) {
11335            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11336        } finally {
11337            IoUtils.closeQuietly(handle);
11338        }
11339
11340        // Now that we've calculated the ABIs and determined if it's an internal app,
11341        // we will go ahead and populate the nativeLibraryPath.
11342        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11343    }
11344
11345    /**
11346     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11347     * i.e, so that all packages can be run inside a single process if required.
11348     *
11349     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11350     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11351     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11352     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11353     * updating a package that belongs to a shared user.
11354     *
11355     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11356     * adds unnecessary complexity.
11357     */
11358    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11359            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11360        List<String> changedAbiCodePath = null;
11361        String requiredInstructionSet = null;
11362        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11363            requiredInstructionSet = VMRuntime.getInstructionSet(
11364                     scannedPackage.applicationInfo.primaryCpuAbi);
11365        }
11366
11367        PackageSetting requirer = null;
11368        for (PackageSetting ps : packagesForUser) {
11369            // If packagesForUser contains scannedPackage, we skip it. This will happen
11370            // when scannedPackage is an update of an existing package. Without this check,
11371            // we will never be able to change the ABI of any package belonging to a shared
11372            // user, even if it's compatible with other packages.
11373            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11374                if (ps.primaryCpuAbiString == null) {
11375                    continue;
11376                }
11377
11378                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11379                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11380                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11381                    // this but there's not much we can do.
11382                    String errorMessage = "Instruction set mismatch, "
11383                            + ((requirer == null) ? "[caller]" : requirer)
11384                            + " requires " + requiredInstructionSet + " whereas " + ps
11385                            + " requires " + instructionSet;
11386                    Slog.w(TAG, errorMessage);
11387                }
11388
11389                if (requiredInstructionSet == null) {
11390                    requiredInstructionSet = instructionSet;
11391                    requirer = ps;
11392                }
11393            }
11394        }
11395
11396        if (requiredInstructionSet != null) {
11397            String adjustedAbi;
11398            if (requirer != null) {
11399                // requirer != null implies that either scannedPackage was null or that scannedPackage
11400                // did not require an ABI, in which case we have to adjust scannedPackage to match
11401                // the ABI of the set (which is the same as requirer's ABI)
11402                adjustedAbi = requirer.primaryCpuAbiString;
11403                if (scannedPackage != null) {
11404                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11405                }
11406            } else {
11407                // requirer == null implies that we're updating all ABIs in the set to
11408                // match scannedPackage.
11409                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11410            }
11411
11412            for (PackageSetting ps : packagesForUser) {
11413                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11414                    if (ps.primaryCpuAbiString != null) {
11415                        continue;
11416                    }
11417
11418                    ps.primaryCpuAbiString = adjustedAbi;
11419                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11420                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11421                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11422                        if (DEBUG_ABI_SELECTION) {
11423                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11424                                    + " (requirer="
11425                                    + (requirer != null ? requirer.pkg : "null")
11426                                    + ", scannedPackage="
11427                                    + (scannedPackage != null ? scannedPackage : "null")
11428                                    + ")");
11429                        }
11430                        if (changedAbiCodePath == null) {
11431                            changedAbiCodePath = new ArrayList<>();
11432                        }
11433                        changedAbiCodePath.add(ps.codePathString);
11434                    }
11435                }
11436            }
11437        }
11438        return changedAbiCodePath;
11439    }
11440
11441    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11442        synchronized (mPackages) {
11443            mResolverReplaced = true;
11444            // Set up information for custom user intent resolution activity.
11445            mResolveActivity.applicationInfo = pkg.applicationInfo;
11446            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11447            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11448            mResolveActivity.processName = pkg.applicationInfo.packageName;
11449            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11450            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11451                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11452            mResolveActivity.theme = 0;
11453            mResolveActivity.exported = true;
11454            mResolveActivity.enabled = true;
11455            mResolveInfo.activityInfo = mResolveActivity;
11456            mResolveInfo.priority = 0;
11457            mResolveInfo.preferredOrder = 0;
11458            mResolveInfo.match = 0;
11459            mResolveComponentName = mCustomResolverComponentName;
11460            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11461                    mResolveComponentName);
11462        }
11463    }
11464
11465    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11466        if (installerActivity == null) {
11467            if (DEBUG_EPHEMERAL) {
11468                Slog.d(TAG, "Clear ephemeral installer activity");
11469            }
11470            mInstantAppInstallerActivity = null;
11471            return;
11472        }
11473
11474        if (DEBUG_EPHEMERAL) {
11475            Slog.d(TAG, "Set ephemeral installer activity: "
11476                    + installerActivity.getComponentName());
11477        }
11478        // Set up information for ephemeral installer activity
11479        mInstantAppInstallerActivity = installerActivity;
11480        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11481                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11482        mInstantAppInstallerActivity.exported = true;
11483        mInstantAppInstallerActivity.enabled = true;
11484        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11485        mInstantAppInstallerInfo.priority = 0;
11486        mInstantAppInstallerInfo.preferredOrder = 1;
11487        mInstantAppInstallerInfo.isDefault = true;
11488        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11489                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11490    }
11491
11492    private static String calculateBundledApkRoot(final String codePathString) {
11493        final File codePath = new File(codePathString);
11494        final File codeRoot;
11495        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11496            codeRoot = Environment.getRootDirectory();
11497        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11498            codeRoot = Environment.getOemDirectory();
11499        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11500            codeRoot = Environment.getVendorDirectory();
11501        } else {
11502            // Unrecognized code path; take its top real segment as the apk root:
11503            // e.g. /something/app/blah.apk => /something
11504            try {
11505                File f = codePath.getCanonicalFile();
11506                File parent = f.getParentFile();    // non-null because codePath is a file
11507                File tmp;
11508                while ((tmp = parent.getParentFile()) != null) {
11509                    f = parent;
11510                    parent = tmp;
11511                }
11512                codeRoot = f;
11513                Slog.w(TAG, "Unrecognized code path "
11514                        + codePath + " - using " + codeRoot);
11515            } catch (IOException e) {
11516                // Can't canonicalize the code path -- shenanigans?
11517                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11518                return Environment.getRootDirectory().getPath();
11519            }
11520        }
11521        return codeRoot.getPath();
11522    }
11523
11524    /**
11525     * Derive and set the location of native libraries for the given package,
11526     * which varies depending on where and how the package was installed.
11527     */
11528    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11529        final ApplicationInfo info = pkg.applicationInfo;
11530        final String codePath = pkg.codePath;
11531        final File codeFile = new File(codePath);
11532        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11533        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11534
11535        info.nativeLibraryRootDir = null;
11536        info.nativeLibraryRootRequiresIsa = false;
11537        info.nativeLibraryDir = null;
11538        info.secondaryNativeLibraryDir = null;
11539
11540        if (isApkFile(codeFile)) {
11541            // Monolithic install
11542            if (bundledApp) {
11543                // If "/system/lib64/apkname" exists, assume that is the per-package
11544                // native library directory to use; otherwise use "/system/lib/apkname".
11545                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11546                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11547                        getPrimaryInstructionSet(info));
11548
11549                // This is a bundled system app so choose the path based on the ABI.
11550                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11551                // is just the default path.
11552                final String apkName = deriveCodePathName(codePath);
11553                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11554                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11555                        apkName).getAbsolutePath();
11556
11557                if (info.secondaryCpuAbi != null) {
11558                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11559                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11560                            secondaryLibDir, apkName).getAbsolutePath();
11561                }
11562            } else if (asecApp) {
11563                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11564                        .getAbsolutePath();
11565            } else {
11566                final String apkName = deriveCodePathName(codePath);
11567                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11568                        .getAbsolutePath();
11569            }
11570
11571            info.nativeLibraryRootRequiresIsa = false;
11572            info.nativeLibraryDir = info.nativeLibraryRootDir;
11573        } else {
11574            // Cluster install
11575            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11576            info.nativeLibraryRootRequiresIsa = true;
11577
11578            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11579                    getPrimaryInstructionSet(info)).getAbsolutePath();
11580
11581            if (info.secondaryCpuAbi != null) {
11582                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11583                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11584            }
11585        }
11586    }
11587
11588    /**
11589     * Calculate the abis and roots for a bundled app. These can uniquely
11590     * be determined from the contents of the system partition, i.e whether
11591     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11592     * of this information, and instead assume that the system was built
11593     * sensibly.
11594     */
11595    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11596                                           PackageSetting pkgSetting) {
11597        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11598
11599        // If "/system/lib64/apkname" exists, assume that is the per-package
11600        // native library directory to use; otherwise use "/system/lib/apkname".
11601        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11602        setBundledAppAbi(pkg, apkRoot, apkName);
11603        // pkgSetting might be null during rescan following uninstall of updates
11604        // to a bundled app, so accommodate that possibility.  The settings in
11605        // that case will be established later from the parsed package.
11606        //
11607        // If the settings aren't null, sync them up with what we've just derived.
11608        // note that apkRoot isn't stored in the package settings.
11609        if (pkgSetting != null) {
11610            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11611            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11612        }
11613    }
11614
11615    /**
11616     * Deduces the ABI of a bundled app and sets the relevant fields on the
11617     * parsed pkg object.
11618     *
11619     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11620     *        under which system libraries are installed.
11621     * @param apkName the name of the installed package.
11622     */
11623    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11624        final File codeFile = new File(pkg.codePath);
11625
11626        final boolean has64BitLibs;
11627        final boolean has32BitLibs;
11628        if (isApkFile(codeFile)) {
11629            // Monolithic install
11630            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11631            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11632        } else {
11633            // Cluster install
11634            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11635            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11636                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11637                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11638                has64BitLibs = (new File(rootDir, isa)).exists();
11639            } else {
11640                has64BitLibs = false;
11641            }
11642            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11643                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11644                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11645                has32BitLibs = (new File(rootDir, isa)).exists();
11646            } else {
11647                has32BitLibs = false;
11648            }
11649        }
11650
11651        if (has64BitLibs && !has32BitLibs) {
11652            // The package has 64 bit libs, but not 32 bit libs. Its primary
11653            // ABI should be 64 bit. We can safely assume here that the bundled
11654            // native libraries correspond to the most preferred ABI in the list.
11655
11656            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11657            pkg.applicationInfo.secondaryCpuAbi = null;
11658        } else if (has32BitLibs && !has64BitLibs) {
11659            // The package has 32 bit libs but not 64 bit libs. Its primary
11660            // ABI should be 32 bit.
11661
11662            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11663            pkg.applicationInfo.secondaryCpuAbi = null;
11664        } else if (has32BitLibs && has64BitLibs) {
11665            // The application has both 64 and 32 bit bundled libraries. We check
11666            // here that the app declares multiArch support, and warn if it doesn't.
11667            //
11668            // We will be lenient here and record both ABIs. The primary will be the
11669            // ABI that's higher on the list, i.e, a device that's configured to prefer
11670            // 64 bit apps will see a 64 bit primary ABI,
11671
11672            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11673                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11674            }
11675
11676            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11677                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11678                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11679            } else {
11680                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11681                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11682            }
11683        } else {
11684            pkg.applicationInfo.primaryCpuAbi = null;
11685            pkg.applicationInfo.secondaryCpuAbi = null;
11686        }
11687    }
11688
11689    private void killApplication(String pkgName, int appId, String reason) {
11690        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11691    }
11692
11693    private void killApplication(String pkgName, int appId, int userId, String reason) {
11694        // Request the ActivityManager to kill the process(only for existing packages)
11695        // so that we do not end up in a confused state while the user is still using the older
11696        // version of the application while the new one gets installed.
11697        final long token = Binder.clearCallingIdentity();
11698        try {
11699            IActivityManager am = ActivityManager.getService();
11700            if (am != null) {
11701                try {
11702                    am.killApplication(pkgName, appId, userId, reason);
11703                } catch (RemoteException e) {
11704                }
11705            }
11706        } finally {
11707            Binder.restoreCallingIdentity(token);
11708        }
11709    }
11710
11711    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11712        // Remove the parent package setting
11713        PackageSetting ps = (PackageSetting) pkg.mExtras;
11714        if (ps != null) {
11715            removePackageLI(ps, chatty);
11716        }
11717        // Remove the child package setting
11718        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11719        for (int i = 0; i < childCount; i++) {
11720            PackageParser.Package childPkg = pkg.childPackages.get(i);
11721            ps = (PackageSetting) childPkg.mExtras;
11722            if (ps != null) {
11723                removePackageLI(ps, chatty);
11724            }
11725        }
11726    }
11727
11728    void removePackageLI(PackageSetting ps, boolean chatty) {
11729        if (DEBUG_INSTALL) {
11730            if (chatty)
11731                Log.d(TAG, "Removing package " + ps.name);
11732        }
11733
11734        // writer
11735        synchronized (mPackages) {
11736            mPackages.remove(ps.name);
11737            final PackageParser.Package pkg = ps.pkg;
11738            if (pkg != null) {
11739                cleanPackageDataStructuresLILPw(pkg, chatty);
11740            }
11741        }
11742    }
11743
11744    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11745        if (DEBUG_INSTALL) {
11746            if (chatty)
11747                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11748        }
11749
11750        // writer
11751        synchronized (mPackages) {
11752            // Remove the parent package
11753            mPackages.remove(pkg.applicationInfo.packageName);
11754            cleanPackageDataStructuresLILPw(pkg, chatty);
11755
11756            // Remove the child packages
11757            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11758            for (int i = 0; i < childCount; i++) {
11759                PackageParser.Package childPkg = pkg.childPackages.get(i);
11760                mPackages.remove(childPkg.applicationInfo.packageName);
11761                cleanPackageDataStructuresLILPw(childPkg, chatty);
11762            }
11763        }
11764    }
11765
11766    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11767        int N = pkg.providers.size();
11768        StringBuilder r = null;
11769        int i;
11770        for (i=0; i<N; i++) {
11771            PackageParser.Provider p = pkg.providers.get(i);
11772            mProviders.removeProvider(p);
11773            if (p.info.authority == null) {
11774
11775                /* There was another ContentProvider with this authority when
11776                 * this app was installed so this authority is null,
11777                 * Ignore it as we don't have to unregister the provider.
11778                 */
11779                continue;
11780            }
11781            String names[] = p.info.authority.split(";");
11782            for (int j = 0; j < names.length; j++) {
11783                if (mProvidersByAuthority.get(names[j]) == p) {
11784                    mProvidersByAuthority.remove(names[j]);
11785                    if (DEBUG_REMOVE) {
11786                        if (chatty)
11787                            Log.d(TAG, "Unregistered content provider: " + names[j]
11788                                    + ", className = " + p.info.name + ", isSyncable = "
11789                                    + p.info.isSyncable);
11790                    }
11791                }
11792            }
11793            if (DEBUG_REMOVE && chatty) {
11794                if (r == null) {
11795                    r = new StringBuilder(256);
11796                } else {
11797                    r.append(' ');
11798                }
11799                r.append(p.info.name);
11800            }
11801        }
11802        if (r != null) {
11803            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11804        }
11805
11806        N = pkg.services.size();
11807        r = null;
11808        for (i=0; i<N; i++) {
11809            PackageParser.Service s = pkg.services.get(i);
11810            mServices.removeService(s);
11811            if (chatty) {
11812                if (r == null) {
11813                    r = new StringBuilder(256);
11814                } else {
11815                    r.append(' ');
11816                }
11817                r.append(s.info.name);
11818            }
11819        }
11820        if (r != null) {
11821            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11822        }
11823
11824        N = pkg.receivers.size();
11825        r = null;
11826        for (i=0; i<N; i++) {
11827            PackageParser.Activity a = pkg.receivers.get(i);
11828            mReceivers.removeActivity(a, "receiver");
11829            if (DEBUG_REMOVE && chatty) {
11830                if (r == null) {
11831                    r = new StringBuilder(256);
11832                } else {
11833                    r.append(' ');
11834                }
11835                r.append(a.info.name);
11836            }
11837        }
11838        if (r != null) {
11839            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11840        }
11841
11842        N = pkg.activities.size();
11843        r = null;
11844        for (i=0; i<N; i++) {
11845            PackageParser.Activity a = pkg.activities.get(i);
11846            mActivities.removeActivity(a, "activity");
11847            if (DEBUG_REMOVE && chatty) {
11848                if (r == null) {
11849                    r = new StringBuilder(256);
11850                } else {
11851                    r.append(' ');
11852                }
11853                r.append(a.info.name);
11854            }
11855        }
11856        if (r != null) {
11857            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11858        }
11859
11860        mPermissionManager.removeAllPermissions(pkg, chatty);
11861
11862        N = pkg.instrumentation.size();
11863        r = null;
11864        for (i=0; i<N; i++) {
11865            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11866            mInstrumentation.remove(a.getComponentName());
11867            if (DEBUG_REMOVE && chatty) {
11868                if (r == null) {
11869                    r = new StringBuilder(256);
11870                } else {
11871                    r.append(' ');
11872                }
11873                r.append(a.info.name);
11874            }
11875        }
11876        if (r != null) {
11877            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11878        }
11879
11880        r = null;
11881        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11882            // Only system apps can hold shared libraries.
11883            if (pkg.libraryNames != null) {
11884                for (i = 0; i < pkg.libraryNames.size(); i++) {
11885                    String name = pkg.libraryNames.get(i);
11886                    if (removeSharedLibraryLPw(name, 0)) {
11887                        if (DEBUG_REMOVE && chatty) {
11888                            if (r == null) {
11889                                r = new StringBuilder(256);
11890                            } else {
11891                                r.append(' ');
11892                            }
11893                            r.append(name);
11894                        }
11895                    }
11896                }
11897            }
11898        }
11899
11900        r = null;
11901
11902        // Any package can hold static shared libraries.
11903        if (pkg.staticSharedLibName != null) {
11904            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11905                if (DEBUG_REMOVE && chatty) {
11906                    if (r == null) {
11907                        r = new StringBuilder(256);
11908                    } else {
11909                        r.append(' ');
11910                    }
11911                    r.append(pkg.staticSharedLibName);
11912                }
11913            }
11914        }
11915
11916        if (r != null) {
11917            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11918        }
11919    }
11920
11921
11922    final class ActivityIntentResolver
11923            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11924        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11925                boolean defaultOnly, int userId) {
11926            if (!sUserManager.exists(userId)) return null;
11927            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11928            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11929        }
11930
11931        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11932                int userId) {
11933            if (!sUserManager.exists(userId)) return null;
11934            mFlags = flags;
11935            return super.queryIntent(intent, resolvedType,
11936                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11937                    userId);
11938        }
11939
11940        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11941                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11942            if (!sUserManager.exists(userId)) return null;
11943            if (packageActivities == null) {
11944                return null;
11945            }
11946            mFlags = flags;
11947            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11948            final int N = packageActivities.size();
11949            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11950                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11951
11952            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11953            for (int i = 0; i < N; ++i) {
11954                intentFilters = packageActivities.get(i).intents;
11955                if (intentFilters != null && intentFilters.size() > 0) {
11956                    PackageParser.ActivityIntentInfo[] array =
11957                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11958                    intentFilters.toArray(array);
11959                    listCut.add(array);
11960                }
11961            }
11962            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11963        }
11964
11965        /**
11966         * Finds a privileged activity that matches the specified activity names.
11967         */
11968        private PackageParser.Activity findMatchingActivity(
11969                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11970            for (PackageParser.Activity sysActivity : activityList) {
11971                if (sysActivity.info.name.equals(activityInfo.name)) {
11972                    return sysActivity;
11973                }
11974                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11975                    return sysActivity;
11976                }
11977                if (sysActivity.info.targetActivity != null) {
11978                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11979                        return sysActivity;
11980                    }
11981                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11982                        return sysActivity;
11983                    }
11984                }
11985            }
11986            return null;
11987        }
11988
11989        public class IterGenerator<E> {
11990            public Iterator<E> generate(ActivityIntentInfo info) {
11991                return null;
11992            }
11993        }
11994
11995        public class ActionIterGenerator extends IterGenerator<String> {
11996            @Override
11997            public Iterator<String> generate(ActivityIntentInfo info) {
11998                return info.actionsIterator();
11999            }
12000        }
12001
12002        public class CategoriesIterGenerator extends IterGenerator<String> {
12003            @Override
12004            public Iterator<String> generate(ActivityIntentInfo info) {
12005                return info.categoriesIterator();
12006            }
12007        }
12008
12009        public class SchemesIterGenerator extends IterGenerator<String> {
12010            @Override
12011            public Iterator<String> generate(ActivityIntentInfo info) {
12012                return info.schemesIterator();
12013            }
12014        }
12015
12016        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12017            @Override
12018            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12019                return info.authoritiesIterator();
12020            }
12021        }
12022
12023        /**
12024         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12025         * MODIFIED. Do not pass in a list that should not be changed.
12026         */
12027        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12028                IterGenerator<T> generator, Iterator<T> searchIterator) {
12029            // loop through the set of actions; every one must be found in the intent filter
12030            while (searchIterator.hasNext()) {
12031                // we must have at least one filter in the list to consider a match
12032                if (intentList.size() == 0) {
12033                    break;
12034                }
12035
12036                final T searchAction = searchIterator.next();
12037
12038                // loop through the set of intent filters
12039                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12040                while (intentIter.hasNext()) {
12041                    final ActivityIntentInfo intentInfo = intentIter.next();
12042                    boolean selectionFound = false;
12043
12044                    // loop through the intent filter's selection criteria; at least one
12045                    // of them must match the searched criteria
12046                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12047                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12048                        final T intentSelection = intentSelectionIter.next();
12049                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12050                            selectionFound = true;
12051                            break;
12052                        }
12053                    }
12054
12055                    // the selection criteria wasn't found in this filter's set; this filter
12056                    // is not a potential match
12057                    if (!selectionFound) {
12058                        intentIter.remove();
12059                    }
12060                }
12061            }
12062        }
12063
12064        private boolean isProtectedAction(ActivityIntentInfo filter) {
12065            final Iterator<String> actionsIter = filter.actionsIterator();
12066            while (actionsIter != null && actionsIter.hasNext()) {
12067                final String filterAction = actionsIter.next();
12068                if (PROTECTED_ACTIONS.contains(filterAction)) {
12069                    return true;
12070                }
12071            }
12072            return false;
12073        }
12074
12075        /**
12076         * Adjusts the priority of the given intent filter according to policy.
12077         * <p>
12078         * <ul>
12079         * <li>The priority for non privileged applications is capped to '0'</li>
12080         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12081         * <li>The priority for unbundled updates to privileged applications is capped to the
12082         *      priority defined on the system partition</li>
12083         * </ul>
12084         * <p>
12085         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12086         * allowed to obtain any priority on any action.
12087         */
12088        private void adjustPriority(
12089                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12090            // nothing to do; priority is fine as-is
12091            if (intent.getPriority() <= 0) {
12092                return;
12093            }
12094
12095            final ActivityInfo activityInfo = intent.activity.info;
12096            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12097
12098            final boolean privilegedApp =
12099                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12100            if (!privilegedApp) {
12101                // non-privileged applications can never define a priority >0
12102                if (DEBUG_FILTERS) {
12103                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12104                            + " package: " + applicationInfo.packageName
12105                            + " activity: " + intent.activity.className
12106                            + " origPrio: " + intent.getPriority());
12107                }
12108                intent.setPriority(0);
12109                return;
12110            }
12111
12112            if (systemActivities == null) {
12113                // the system package is not disabled; we're parsing the system partition
12114                if (isProtectedAction(intent)) {
12115                    if (mDeferProtectedFilters) {
12116                        // We can't deal with these just yet. No component should ever obtain a
12117                        // >0 priority for a protected actions, with ONE exception -- the setup
12118                        // wizard. The setup wizard, however, cannot be known until we're able to
12119                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12120                        // until all intent filters have been processed. Chicken, meet egg.
12121                        // Let the filter temporarily have a high priority and rectify the
12122                        // priorities after all system packages have been scanned.
12123                        mProtectedFilters.add(intent);
12124                        if (DEBUG_FILTERS) {
12125                            Slog.i(TAG, "Protected action; save for later;"
12126                                    + " package: " + applicationInfo.packageName
12127                                    + " activity: " + intent.activity.className
12128                                    + " origPrio: " + intent.getPriority());
12129                        }
12130                        return;
12131                    } else {
12132                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12133                            Slog.i(TAG, "No setup wizard;"
12134                                + " All protected intents capped to priority 0");
12135                        }
12136                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12137                            if (DEBUG_FILTERS) {
12138                                Slog.i(TAG, "Found setup wizard;"
12139                                    + " allow priority " + intent.getPriority() + ";"
12140                                    + " package: " + intent.activity.info.packageName
12141                                    + " activity: " + intent.activity.className
12142                                    + " priority: " + intent.getPriority());
12143                            }
12144                            // setup wizard gets whatever it wants
12145                            return;
12146                        }
12147                        if (DEBUG_FILTERS) {
12148                            Slog.i(TAG, "Protected action; cap priority to 0;"
12149                                    + " package: " + intent.activity.info.packageName
12150                                    + " activity: " + intent.activity.className
12151                                    + " origPrio: " + intent.getPriority());
12152                        }
12153                        intent.setPriority(0);
12154                        return;
12155                    }
12156                }
12157                // privileged apps on the system image get whatever priority they request
12158                return;
12159            }
12160
12161            // privileged app unbundled update ... try to find the same activity
12162            final PackageParser.Activity foundActivity =
12163                    findMatchingActivity(systemActivities, activityInfo);
12164            if (foundActivity == null) {
12165                // this is a new activity; it cannot obtain >0 priority
12166                if (DEBUG_FILTERS) {
12167                    Slog.i(TAG, "New activity; cap priority to 0;"
12168                            + " package: " + applicationInfo.packageName
12169                            + " activity: " + intent.activity.className
12170                            + " origPrio: " + intent.getPriority());
12171                }
12172                intent.setPriority(0);
12173                return;
12174            }
12175
12176            // found activity, now check for filter equivalence
12177
12178            // a shallow copy is enough; we modify the list, not its contents
12179            final List<ActivityIntentInfo> intentListCopy =
12180                    new ArrayList<>(foundActivity.intents);
12181            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12182
12183            // find matching action subsets
12184            final Iterator<String> actionsIterator = intent.actionsIterator();
12185            if (actionsIterator != null) {
12186                getIntentListSubset(
12187                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12188                if (intentListCopy.size() == 0) {
12189                    // no more intents to match; we're not equivalent
12190                    if (DEBUG_FILTERS) {
12191                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12192                                + " package: " + applicationInfo.packageName
12193                                + " activity: " + intent.activity.className
12194                                + " origPrio: " + intent.getPriority());
12195                    }
12196                    intent.setPriority(0);
12197                    return;
12198                }
12199            }
12200
12201            // find matching category subsets
12202            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12203            if (categoriesIterator != null) {
12204                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12205                        categoriesIterator);
12206                if (intentListCopy.size() == 0) {
12207                    // no more intents to match; we're not equivalent
12208                    if (DEBUG_FILTERS) {
12209                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12210                                + " package: " + applicationInfo.packageName
12211                                + " activity: " + intent.activity.className
12212                                + " origPrio: " + intent.getPriority());
12213                    }
12214                    intent.setPriority(0);
12215                    return;
12216                }
12217            }
12218
12219            // find matching schemes subsets
12220            final Iterator<String> schemesIterator = intent.schemesIterator();
12221            if (schemesIterator != null) {
12222                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12223                        schemesIterator);
12224                if (intentListCopy.size() == 0) {
12225                    // no more intents to match; we're not equivalent
12226                    if (DEBUG_FILTERS) {
12227                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12228                                + " package: " + applicationInfo.packageName
12229                                + " activity: " + intent.activity.className
12230                                + " origPrio: " + intent.getPriority());
12231                    }
12232                    intent.setPriority(0);
12233                    return;
12234                }
12235            }
12236
12237            // find matching authorities subsets
12238            final Iterator<IntentFilter.AuthorityEntry>
12239                    authoritiesIterator = intent.authoritiesIterator();
12240            if (authoritiesIterator != null) {
12241                getIntentListSubset(intentListCopy,
12242                        new AuthoritiesIterGenerator(),
12243                        authoritiesIterator);
12244                if (intentListCopy.size() == 0) {
12245                    // no more intents to match; we're not equivalent
12246                    if (DEBUG_FILTERS) {
12247                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12248                                + " package: " + applicationInfo.packageName
12249                                + " activity: " + intent.activity.className
12250                                + " origPrio: " + intent.getPriority());
12251                    }
12252                    intent.setPriority(0);
12253                    return;
12254                }
12255            }
12256
12257            // we found matching filter(s); app gets the max priority of all intents
12258            int cappedPriority = 0;
12259            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12260                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12261            }
12262            if (intent.getPriority() > cappedPriority) {
12263                if (DEBUG_FILTERS) {
12264                    Slog.i(TAG, "Found matching filter(s);"
12265                            + " cap priority to " + cappedPriority + ";"
12266                            + " package: " + applicationInfo.packageName
12267                            + " activity: " + intent.activity.className
12268                            + " origPrio: " + intent.getPriority());
12269                }
12270                intent.setPriority(cappedPriority);
12271                return;
12272            }
12273            // all this for nothing; the requested priority was <= what was on the system
12274        }
12275
12276        public final void addActivity(PackageParser.Activity a, String type) {
12277            mActivities.put(a.getComponentName(), a);
12278            if (DEBUG_SHOW_INFO)
12279                Log.v(
12280                TAG, "  " + type + " " +
12281                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12282            if (DEBUG_SHOW_INFO)
12283                Log.v(TAG, "    Class=" + a.info.name);
12284            final int NI = a.intents.size();
12285            for (int j=0; j<NI; j++) {
12286                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12287                if ("activity".equals(type)) {
12288                    final PackageSetting ps =
12289                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12290                    final List<PackageParser.Activity> systemActivities =
12291                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12292                    adjustPriority(systemActivities, intent);
12293                }
12294                if (DEBUG_SHOW_INFO) {
12295                    Log.v(TAG, "    IntentFilter:");
12296                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12297                }
12298                if (!intent.debugCheck()) {
12299                    Log.w(TAG, "==> For Activity " + a.info.name);
12300                }
12301                addFilter(intent);
12302            }
12303        }
12304
12305        public final void removeActivity(PackageParser.Activity a, String type) {
12306            mActivities.remove(a.getComponentName());
12307            if (DEBUG_SHOW_INFO) {
12308                Log.v(TAG, "  " + type + " "
12309                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12310                                : a.info.name) + ":");
12311                Log.v(TAG, "    Class=" + a.info.name);
12312            }
12313            final int NI = a.intents.size();
12314            for (int j=0; j<NI; j++) {
12315                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12316                if (DEBUG_SHOW_INFO) {
12317                    Log.v(TAG, "    IntentFilter:");
12318                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12319                }
12320                removeFilter(intent);
12321            }
12322        }
12323
12324        @Override
12325        protected boolean allowFilterResult(
12326                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12327            ActivityInfo filterAi = filter.activity.info;
12328            for (int i=dest.size()-1; i>=0; i--) {
12329                ActivityInfo destAi = dest.get(i).activityInfo;
12330                if (destAi.name == filterAi.name
12331                        && destAi.packageName == filterAi.packageName) {
12332                    return false;
12333                }
12334            }
12335            return true;
12336        }
12337
12338        @Override
12339        protected ActivityIntentInfo[] newArray(int size) {
12340            return new ActivityIntentInfo[size];
12341        }
12342
12343        @Override
12344        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12345            if (!sUserManager.exists(userId)) return true;
12346            PackageParser.Package p = filter.activity.owner;
12347            if (p != null) {
12348                PackageSetting ps = (PackageSetting)p.mExtras;
12349                if (ps != null) {
12350                    // System apps are never considered stopped for purposes of
12351                    // filtering, because there may be no way for the user to
12352                    // actually re-launch them.
12353                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12354                            && ps.getStopped(userId);
12355                }
12356            }
12357            return false;
12358        }
12359
12360        @Override
12361        protected boolean isPackageForFilter(String packageName,
12362                PackageParser.ActivityIntentInfo info) {
12363            return packageName.equals(info.activity.owner.packageName);
12364        }
12365
12366        @Override
12367        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12368                int match, int userId) {
12369            if (!sUserManager.exists(userId)) return null;
12370            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12371                return null;
12372            }
12373            final PackageParser.Activity activity = info.activity;
12374            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12375            if (ps == null) {
12376                return null;
12377            }
12378            final PackageUserState userState = ps.readUserState(userId);
12379            ActivityInfo ai =
12380                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12381            if (ai == null) {
12382                return null;
12383            }
12384            final boolean matchExplicitlyVisibleOnly =
12385                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12386            final boolean matchVisibleToInstantApp =
12387                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12388            final boolean componentVisible =
12389                    matchVisibleToInstantApp
12390                    && info.isVisibleToInstantApp()
12391                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12392            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12393            // throw out filters that aren't visible to ephemeral apps
12394            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12395                return null;
12396            }
12397            // throw out instant app filters if we're not explicitly requesting them
12398            if (!matchInstantApp && userState.instantApp) {
12399                return null;
12400            }
12401            // throw out instant app filters if updates are available; will trigger
12402            // instant app resolution
12403            if (userState.instantApp && ps.isUpdateAvailable()) {
12404                return null;
12405            }
12406            final ResolveInfo res = new ResolveInfo();
12407            res.activityInfo = ai;
12408            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12409                res.filter = info;
12410            }
12411            if (info != null) {
12412                res.handleAllWebDataURI = info.handleAllWebDataURI();
12413            }
12414            res.priority = info.getPriority();
12415            res.preferredOrder = activity.owner.mPreferredOrder;
12416            //System.out.println("Result: " + res.activityInfo.className +
12417            //                   " = " + res.priority);
12418            res.match = match;
12419            res.isDefault = info.hasDefault;
12420            res.labelRes = info.labelRes;
12421            res.nonLocalizedLabel = info.nonLocalizedLabel;
12422            if (userNeedsBadging(userId)) {
12423                res.noResourceId = true;
12424            } else {
12425                res.icon = info.icon;
12426            }
12427            res.iconResourceId = info.icon;
12428            res.system = res.activityInfo.applicationInfo.isSystemApp();
12429            res.isInstantAppAvailable = userState.instantApp;
12430            return res;
12431        }
12432
12433        @Override
12434        protected void sortResults(List<ResolveInfo> results) {
12435            Collections.sort(results, mResolvePrioritySorter);
12436        }
12437
12438        @Override
12439        protected void dumpFilter(PrintWriter out, String prefix,
12440                PackageParser.ActivityIntentInfo filter) {
12441            out.print(prefix); out.print(
12442                    Integer.toHexString(System.identityHashCode(filter.activity)));
12443                    out.print(' ');
12444                    filter.activity.printComponentShortName(out);
12445                    out.print(" filter ");
12446                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12447        }
12448
12449        @Override
12450        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12451            return filter.activity;
12452        }
12453
12454        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12455            PackageParser.Activity activity = (PackageParser.Activity)label;
12456            out.print(prefix); out.print(
12457                    Integer.toHexString(System.identityHashCode(activity)));
12458                    out.print(' ');
12459                    activity.printComponentShortName(out);
12460            if (count > 1) {
12461                out.print(" ("); out.print(count); out.print(" filters)");
12462            }
12463            out.println();
12464        }
12465
12466        // Keys are String (activity class name), values are Activity.
12467        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12468                = new ArrayMap<ComponentName, PackageParser.Activity>();
12469        private int mFlags;
12470    }
12471
12472    private final class ServiceIntentResolver
12473            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12474        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12475                boolean defaultOnly, int userId) {
12476            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12477            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12478        }
12479
12480        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12481                int userId) {
12482            if (!sUserManager.exists(userId)) return null;
12483            mFlags = flags;
12484            return super.queryIntent(intent, resolvedType,
12485                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12486                    userId);
12487        }
12488
12489        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12490                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12491            if (!sUserManager.exists(userId)) return null;
12492            if (packageServices == null) {
12493                return null;
12494            }
12495            mFlags = flags;
12496            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12497            final int N = packageServices.size();
12498            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12499                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12500
12501            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12502            for (int i = 0; i < N; ++i) {
12503                intentFilters = packageServices.get(i).intents;
12504                if (intentFilters != null && intentFilters.size() > 0) {
12505                    PackageParser.ServiceIntentInfo[] array =
12506                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12507                    intentFilters.toArray(array);
12508                    listCut.add(array);
12509                }
12510            }
12511            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12512        }
12513
12514        public final void addService(PackageParser.Service s) {
12515            mServices.put(s.getComponentName(), s);
12516            if (DEBUG_SHOW_INFO) {
12517                Log.v(TAG, "  "
12518                        + (s.info.nonLocalizedLabel != null
12519                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12520                Log.v(TAG, "    Class=" + s.info.name);
12521            }
12522            final int NI = s.intents.size();
12523            int j;
12524            for (j=0; j<NI; j++) {
12525                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12526                if (DEBUG_SHOW_INFO) {
12527                    Log.v(TAG, "    IntentFilter:");
12528                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12529                }
12530                if (!intent.debugCheck()) {
12531                    Log.w(TAG, "==> For Service " + s.info.name);
12532                }
12533                addFilter(intent);
12534            }
12535        }
12536
12537        public final void removeService(PackageParser.Service s) {
12538            mServices.remove(s.getComponentName());
12539            if (DEBUG_SHOW_INFO) {
12540                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12541                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12542                Log.v(TAG, "    Class=" + s.info.name);
12543            }
12544            final int NI = s.intents.size();
12545            int j;
12546            for (j=0; j<NI; j++) {
12547                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12548                if (DEBUG_SHOW_INFO) {
12549                    Log.v(TAG, "    IntentFilter:");
12550                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12551                }
12552                removeFilter(intent);
12553            }
12554        }
12555
12556        @Override
12557        protected boolean allowFilterResult(
12558                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12559            ServiceInfo filterSi = filter.service.info;
12560            for (int i=dest.size()-1; i>=0; i--) {
12561                ServiceInfo destAi = dest.get(i).serviceInfo;
12562                if (destAi.name == filterSi.name
12563                        && destAi.packageName == filterSi.packageName) {
12564                    return false;
12565                }
12566            }
12567            return true;
12568        }
12569
12570        @Override
12571        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12572            return new PackageParser.ServiceIntentInfo[size];
12573        }
12574
12575        @Override
12576        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12577            if (!sUserManager.exists(userId)) return true;
12578            PackageParser.Package p = filter.service.owner;
12579            if (p != null) {
12580                PackageSetting ps = (PackageSetting)p.mExtras;
12581                if (ps != null) {
12582                    // System apps are never considered stopped for purposes of
12583                    // filtering, because there may be no way for the user to
12584                    // actually re-launch them.
12585                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12586                            && ps.getStopped(userId);
12587                }
12588            }
12589            return false;
12590        }
12591
12592        @Override
12593        protected boolean isPackageForFilter(String packageName,
12594                PackageParser.ServiceIntentInfo info) {
12595            return packageName.equals(info.service.owner.packageName);
12596        }
12597
12598        @Override
12599        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12600                int match, int userId) {
12601            if (!sUserManager.exists(userId)) return null;
12602            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12603            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12604                return null;
12605            }
12606            final PackageParser.Service service = info.service;
12607            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12608            if (ps == null) {
12609                return null;
12610            }
12611            final PackageUserState userState = ps.readUserState(userId);
12612            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12613                    userState, userId);
12614            if (si == null) {
12615                return null;
12616            }
12617            final boolean matchVisibleToInstantApp =
12618                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12619            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12620            // throw out filters that aren't visible to ephemeral apps
12621            if (matchVisibleToInstantApp
12622                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12623                return null;
12624            }
12625            // throw out ephemeral filters if we're not explicitly requesting them
12626            if (!isInstantApp && userState.instantApp) {
12627                return null;
12628            }
12629            // throw out instant app filters if updates are available; will trigger
12630            // instant app resolution
12631            if (userState.instantApp && ps.isUpdateAvailable()) {
12632                return null;
12633            }
12634            final ResolveInfo res = new ResolveInfo();
12635            res.serviceInfo = si;
12636            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12637                res.filter = filter;
12638            }
12639            res.priority = info.getPriority();
12640            res.preferredOrder = service.owner.mPreferredOrder;
12641            res.match = match;
12642            res.isDefault = info.hasDefault;
12643            res.labelRes = info.labelRes;
12644            res.nonLocalizedLabel = info.nonLocalizedLabel;
12645            res.icon = info.icon;
12646            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12647            return res;
12648        }
12649
12650        @Override
12651        protected void sortResults(List<ResolveInfo> results) {
12652            Collections.sort(results, mResolvePrioritySorter);
12653        }
12654
12655        @Override
12656        protected void dumpFilter(PrintWriter out, String prefix,
12657                PackageParser.ServiceIntentInfo filter) {
12658            out.print(prefix); out.print(
12659                    Integer.toHexString(System.identityHashCode(filter.service)));
12660                    out.print(' ');
12661                    filter.service.printComponentShortName(out);
12662                    out.print(" filter ");
12663                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12664                    if (filter.service.info.permission != null) {
12665                        out.print(" permission "); out.println(filter.service.info.permission);
12666                    } else {
12667                        out.println();
12668                    }
12669        }
12670
12671        @Override
12672        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12673            return filter.service;
12674        }
12675
12676        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12677            PackageParser.Service service = (PackageParser.Service)label;
12678            out.print(prefix); out.print(
12679                    Integer.toHexString(System.identityHashCode(service)));
12680                    out.print(' ');
12681                    service.printComponentShortName(out);
12682            if (count > 1) {
12683                out.print(" ("); out.print(count); out.print(" filters)");
12684            }
12685            out.println();
12686        }
12687
12688//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12689//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12690//            final List<ResolveInfo> retList = Lists.newArrayList();
12691//            while (i.hasNext()) {
12692//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12693//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12694//                    retList.add(resolveInfo);
12695//                }
12696//            }
12697//            return retList;
12698//        }
12699
12700        // Keys are String (activity class name), values are Activity.
12701        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12702                = new ArrayMap<ComponentName, PackageParser.Service>();
12703        private int mFlags;
12704    }
12705
12706    private final class ProviderIntentResolver
12707            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12708        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12709                boolean defaultOnly, int userId) {
12710            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12711            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12712        }
12713
12714        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12715                int userId) {
12716            if (!sUserManager.exists(userId))
12717                return null;
12718            mFlags = flags;
12719            return super.queryIntent(intent, resolvedType,
12720                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12721                    userId);
12722        }
12723
12724        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12725                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12726            if (!sUserManager.exists(userId))
12727                return null;
12728            if (packageProviders == null) {
12729                return null;
12730            }
12731            mFlags = flags;
12732            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12733            final int N = packageProviders.size();
12734            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12735                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12736
12737            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12738            for (int i = 0; i < N; ++i) {
12739                intentFilters = packageProviders.get(i).intents;
12740                if (intentFilters != null && intentFilters.size() > 0) {
12741                    PackageParser.ProviderIntentInfo[] array =
12742                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12743                    intentFilters.toArray(array);
12744                    listCut.add(array);
12745                }
12746            }
12747            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12748        }
12749
12750        public final void addProvider(PackageParser.Provider p) {
12751            if (mProviders.containsKey(p.getComponentName())) {
12752                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12753                return;
12754            }
12755
12756            mProviders.put(p.getComponentName(), p);
12757            if (DEBUG_SHOW_INFO) {
12758                Log.v(TAG, "  "
12759                        + (p.info.nonLocalizedLabel != null
12760                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12761                Log.v(TAG, "    Class=" + p.info.name);
12762            }
12763            final int NI = p.intents.size();
12764            int j;
12765            for (j = 0; j < NI; j++) {
12766                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12767                if (DEBUG_SHOW_INFO) {
12768                    Log.v(TAG, "    IntentFilter:");
12769                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12770                }
12771                if (!intent.debugCheck()) {
12772                    Log.w(TAG, "==> For Provider " + p.info.name);
12773                }
12774                addFilter(intent);
12775            }
12776        }
12777
12778        public final void removeProvider(PackageParser.Provider p) {
12779            mProviders.remove(p.getComponentName());
12780            if (DEBUG_SHOW_INFO) {
12781                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12782                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12783                Log.v(TAG, "    Class=" + p.info.name);
12784            }
12785            final int NI = p.intents.size();
12786            int j;
12787            for (j = 0; j < NI; j++) {
12788                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12789                if (DEBUG_SHOW_INFO) {
12790                    Log.v(TAG, "    IntentFilter:");
12791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12792                }
12793                removeFilter(intent);
12794            }
12795        }
12796
12797        @Override
12798        protected boolean allowFilterResult(
12799                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12800            ProviderInfo filterPi = filter.provider.info;
12801            for (int i = dest.size() - 1; i >= 0; i--) {
12802                ProviderInfo destPi = dest.get(i).providerInfo;
12803                if (destPi.name == filterPi.name
12804                        && destPi.packageName == filterPi.packageName) {
12805                    return false;
12806                }
12807            }
12808            return true;
12809        }
12810
12811        @Override
12812        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12813            return new PackageParser.ProviderIntentInfo[size];
12814        }
12815
12816        @Override
12817        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12818            if (!sUserManager.exists(userId))
12819                return true;
12820            PackageParser.Package p = filter.provider.owner;
12821            if (p != null) {
12822                PackageSetting ps = (PackageSetting) p.mExtras;
12823                if (ps != null) {
12824                    // System apps are never considered stopped for purposes of
12825                    // filtering, because there may be no way for the user to
12826                    // actually re-launch them.
12827                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12828                            && ps.getStopped(userId);
12829                }
12830            }
12831            return false;
12832        }
12833
12834        @Override
12835        protected boolean isPackageForFilter(String packageName,
12836                PackageParser.ProviderIntentInfo info) {
12837            return packageName.equals(info.provider.owner.packageName);
12838        }
12839
12840        @Override
12841        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12842                int match, int userId) {
12843            if (!sUserManager.exists(userId))
12844                return null;
12845            final PackageParser.ProviderIntentInfo info = filter;
12846            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12847                return null;
12848            }
12849            final PackageParser.Provider provider = info.provider;
12850            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12851            if (ps == null) {
12852                return null;
12853            }
12854            final PackageUserState userState = ps.readUserState(userId);
12855            final boolean matchVisibleToInstantApp =
12856                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12857            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12858            // throw out filters that aren't visible to instant applications
12859            if (matchVisibleToInstantApp
12860                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12861                return null;
12862            }
12863            // throw out instant application filters if we're not explicitly requesting them
12864            if (!isInstantApp && userState.instantApp) {
12865                return null;
12866            }
12867            // throw out instant application filters if updates are available; will trigger
12868            // instant application resolution
12869            if (userState.instantApp && ps.isUpdateAvailable()) {
12870                return null;
12871            }
12872            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12873                    userState, userId);
12874            if (pi == null) {
12875                return null;
12876            }
12877            final ResolveInfo res = new ResolveInfo();
12878            res.providerInfo = pi;
12879            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12880                res.filter = filter;
12881            }
12882            res.priority = info.getPriority();
12883            res.preferredOrder = provider.owner.mPreferredOrder;
12884            res.match = match;
12885            res.isDefault = info.hasDefault;
12886            res.labelRes = info.labelRes;
12887            res.nonLocalizedLabel = info.nonLocalizedLabel;
12888            res.icon = info.icon;
12889            res.system = res.providerInfo.applicationInfo.isSystemApp();
12890            return res;
12891        }
12892
12893        @Override
12894        protected void sortResults(List<ResolveInfo> results) {
12895            Collections.sort(results, mResolvePrioritySorter);
12896        }
12897
12898        @Override
12899        protected void dumpFilter(PrintWriter out, String prefix,
12900                PackageParser.ProviderIntentInfo filter) {
12901            out.print(prefix);
12902            out.print(
12903                    Integer.toHexString(System.identityHashCode(filter.provider)));
12904            out.print(' ');
12905            filter.provider.printComponentShortName(out);
12906            out.print(" filter ");
12907            out.println(Integer.toHexString(System.identityHashCode(filter)));
12908        }
12909
12910        @Override
12911        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12912            return filter.provider;
12913        }
12914
12915        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12916            PackageParser.Provider provider = (PackageParser.Provider)label;
12917            out.print(prefix); out.print(
12918                    Integer.toHexString(System.identityHashCode(provider)));
12919                    out.print(' ');
12920                    provider.printComponentShortName(out);
12921            if (count > 1) {
12922                out.print(" ("); out.print(count); out.print(" filters)");
12923            }
12924            out.println();
12925        }
12926
12927        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12928                = new ArrayMap<ComponentName, PackageParser.Provider>();
12929        private int mFlags;
12930    }
12931
12932    static final class EphemeralIntentResolver
12933            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12934        /**
12935         * The result that has the highest defined order. Ordering applies on a
12936         * per-package basis. Mapping is from package name to Pair of order and
12937         * EphemeralResolveInfo.
12938         * <p>
12939         * NOTE: This is implemented as a field variable for convenience and efficiency.
12940         * By having a field variable, we're able to track filter ordering as soon as
12941         * a non-zero order is defined. Otherwise, multiple loops across the result set
12942         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12943         * this needs to be contained entirely within {@link #filterResults}.
12944         */
12945        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12946
12947        @Override
12948        protected AuxiliaryResolveInfo[] newArray(int size) {
12949            return new AuxiliaryResolveInfo[size];
12950        }
12951
12952        @Override
12953        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12954            return true;
12955        }
12956
12957        @Override
12958        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12959                int userId) {
12960            if (!sUserManager.exists(userId)) {
12961                return null;
12962            }
12963            final String packageName = responseObj.resolveInfo.getPackageName();
12964            final Integer order = responseObj.getOrder();
12965            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12966                    mOrderResult.get(packageName);
12967            // ordering is enabled and this item's order isn't high enough
12968            if (lastOrderResult != null && lastOrderResult.first >= order) {
12969                return null;
12970            }
12971            final InstantAppResolveInfo res = responseObj.resolveInfo;
12972            if (order > 0) {
12973                // non-zero order, enable ordering
12974                mOrderResult.put(packageName, new Pair<>(order, res));
12975            }
12976            return responseObj;
12977        }
12978
12979        @Override
12980        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12981            // only do work if ordering is enabled [most of the time it won't be]
12982            if (mOrderResult.size() == 0) {
12983                return;
12984            }
12985            int resultSize = results.size();
12986            for (int i = 0; i < resultSize; i++) {
12987                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12988                final String packageName = info.getPackageName();
12989                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12990                if (savedInfo == null) {
12991                    // package doesn't having ordering
12992                    continue;
12993                }
12994                if (savedInfo.second == info) {
12995                    // circled back to the highest ordered item; remove from order list
12996                    mOrderResult.remove(packageName);
12997                    if (mOrderResult.size() == 0) {
12998                        // no more ordered items
12999                        break;
13000                    }
13001                    continue;
13002                }
13003                // item has a worse order, remove it from the result list
13004                results.remove(i);
13005                resultSize--;
13006                i--;
13007            }
13008        }
13009    }
13010
13011    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13012            new Comparator<ResolveInfo>() {
13013        public int compare(ResolveInfo r1, ResolveInfo r2) {
13014            int v1 = r1.priority;
13015            int v2 = r2.priority;
13016            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13017            if (v1 != v2) {
13018                return (v1 > v2) ? -1 : 1;
13019            }
13020            v1 = r1.preferredOrder;
13021            v2 = r2.preferredOrder;
13022            if (v1 != v2) {
13023                return (v1 > v2) ? -1 : 1;
13024            }
13025            if (r1.isDefault != r2.isDefault) {
13026                return r1.isDefault ? -1 : 1;
13027            }
13028            v1 = r1.match;
13029            v2 = r2.match;
13030            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13031            if (v1 != v2) {
13032                return (v1 > v2) ? -1 : 1;
13033            }
13034            if (r1.system != r2.system) {
13035                return r1.system ? -1 : 1;
13036            }
13037            if (r1.activityInfo != null) {
13038                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13039            }
13040            if (r1.serviceInfo != null) {
13041                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13042            }
13043            if (r1.providerInfo != null) {
13044                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13045            }
13046            return 0;
13047        }
13048    };
13049
13050    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13051            new Comparator<ProviderInfo>() {
13052        public int compare(ProviderInfo p1, ProviderInfo p2) {
13053            final int v1 = p1.initOrder;
13054            final int v2 = p2.initOrder;
13055            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13056        }
13057    };
13058
13059    @Override
13060    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13061            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13062            final int[] userIds, int[] instantUserIds) {
13063        mHandler.post(new Runnable() {
13064            @Override
13065            public void run() {
13066                try {
13067                    final IActivityManager am = ActivityManager.getService();
13068                    if (am == null) return;
13069                    final int[] resolvedUserIds;
13070                    if (userIds == null) {
13071                        resolvedUserIds = am.getRunningUserIds();
13072                    } else {
13073                        resolvedUserIds = userIds;
13074                    }
13075                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13076                            resolvedUserIds, false);
13077                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13078                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13079                                instantUserIds, true);
13080                    }
13081                } catch (RemoteException ex) {
13082                }
13083            }
13084        });
13085    }
13086
13087    @Override
13088    public void notifyPackageAdded(String packageName) {
13089        final PackageListObserver[] observers;
13090        synchronized (mPackages) {
13091            if (mPackageListObservers.size() == 0) {
13092                return;
13093            }
13094            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13095        }
13096        for (int i = observers.length - 1; i >= 0; --i) {
13097            observers[i].onPackageAdded(packageName);
13098        }
13099    }
13100
13101    @Override
13102    public void notifyPackageRemoved(String packageName) {
13103        final PackageListObserver[] observers;
13104        synchronized (mPackages) {
13105            if (mPackageListObservers.size() == 0) {
13106                return;
13107            }
13108            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13109        }
13110        for (int i = observers.length - 1; i >= 0; --i) {
13111            observers[i].onPackageRemoved(packageName);
13112        }
13113    }
13114
13115    /**
13116     * Sends a broadcast for the given action.
13117     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13118     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13119     * the system and applications allowed to see instant applications to receive package
13120     * lifecycle events for instant applications.
13121     */
13122    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13123            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13124            int[] userIds, boolean isInstantApp)
13125                    throws RemoteException {
13126        for (int id : userIds) {
13127            final Intent intent = new Intent(action,
13128                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13129            final String[] requiredPermissions =
13130                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13131            if (extras != null) {
13132                intent.putExtras(extras);
13133            }
13134            if (targetPkg != null) {
13135                intent.setPackage(targetPkg);
13136            }
13137            // Modify the UID when posting to other users
13138            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13139            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13140                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13141                intent.putExtra(Intent.EXTRA_UID, uid);
13142            }
13143            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13144            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13145            if (DEBUG_BROADCASTS) {
13146                RuntimeException here = new RuntimeException("here");
13147                here.fillInStackTrace();
13148                Slog.d(TAG, "Sending to user " + id + ": "
13149                        + intent.toShortString(false, true, false, false)
13150                        + " " + intent.getExtras(), here);
13151            }
13152            am.broadcastIntent(null, intent, null, finishedReceiver,
13153                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13154                    null, finishedReceiver != null, false, id);
13155        }
13156    }
13157
13158    /**
13159     * Check if the external storage media is available. This is true if there
13160     * is a mounted external storage medium or if the external storage is
13161     * emulated.
13162     */
13163    private boolean isExternalMediaAvailable() {
13164        return mMediaMounted || Environment.isExternalStorageEmulated();
13165    }
13166
13167    @Override
13168    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13169        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13170            return null;
13171        }
13172        if (!isExternalMediaAvailable()) {
13173                // If the external storage is no longer mounted at this point,
13174                // the caller may not have been able to delete all of this
13175                // packages files and can not delete any more.  Bail.
13176            return null;
13177        }
13178        synchronized (mPackages) {
13179            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13180            if (lastPackage != null) {
13181                pkgs.remove(lastPackage);
13182            }
13183            if (pkgs.size() > 0) {
13184                return pkgs.get(0);
13185            }
13186        }
13187        return null;
13188    }
13189
13190    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13191        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13192                userId, andCode ? 1 : 0, packageName);
13193        if (mSystemReady) {
13194            msg.sendToTarget();
13195        } else {
13196            if (mPostSystemReadyMessages == null) {
13197                mPostSystemReadyMessages = new ArrayList<>();
13198            }
13199            mPostSystemReadyMessages.add(msg);
13200        }
13201    }
13202
13203    void startCleaningPackages() {
13204        // reader
13205        if (!isExternalMediaAvailable()) {
13206            return;
13207        }
13208        synchronized (mPackages) {
13209            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13210                return;
13211            }
13212        }
13213        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13214        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13215        IActivityManager am = ActivityManager.getService();
13216        if (am != null) {
13217            int dcsUid = -1;
13218            synchronized (mPackages) {
13219                if (!mDefaultContainerWhitelisted) {
13220                    mDefaultContainerWhitelisted = true;
13221                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13222                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13223                }
13224            }
13225            try {
13226                if (dcsUid > 0) {
13227                    am.backgroundWhitelistUid(dcsUid);
13228                }
13229                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13230                        UserHandle.USER_SYSTEM);
13231            } catch (RemoteException e) {
13232            }
13233        }
13234    }
13235
13236    /**
13237     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13238     * it is acting on behalf on an enterprise or the user).
13239     *
13240     * Note that the ordering of the conditionals in this method is important. The checks we perform
13241     * are as follows, in this order:
13242     *
13243     * 1) If the install is being performed by a system app, we can trust the app to have set the
13244     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13245     *    what it is.
13246     * 2) If the install is being performed by a device or profile owner app, the install reason
13247     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13248     *    set the install reason correctly. If the app targets an older SDK version where install
13249     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13250     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13251     * 3) In all other cases, the install is being performed by a regular app that is neither part
13252     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13253     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13254     *    set to enterprise policy and if so, change it to unknown instead.
13255     */
13256    private int fixUpInstallReason(String installerPackageName, int installerUid,
13257            int installReason) {
13258        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13259                == PERMISSION_GRANTED) {
13260            // If the install is being performed by a system app, we trust that app to have set the
13261            // install reason correctly.
13262            return installReason;
13263        }
13264
13265        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13266            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13267        if (dpm != null) {
13268            ComponentName owner = null;
13269            try {
13270                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13271                if (owner == null) {
13272                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13273                }
13274            } catch (RemoteException e) {
13275            }
13276            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13277                // If the install is being performed by a device or profile owner, the install
13278                // reason should be enterprise policy.
13279                return PackageManager.INSTALL_REASON_POLICY;
13280            }
13281        }
13282
13283        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13284            // If the install is being performed by a regular app (i.e. neither system app nor
13285            // device or profile owner), we have no reason to believe that the app is acting on
13286            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13287            // change it to unknown instead.
13288            return PackageManager.INSTALL_REASON_UNKNOWN;
13289        }
13290
13291        // If the install is being performed by a regular app and the install reason was set to any
13292        // value but enterprise policy, leave the install reason unchanged.
13293        return installReason;
13294    }
13295
13296    void installStage(String packageName, File stagedDir,
13297            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13298            String installerPackageName, int installerUid, UserHandle user,
13299            PackageParser.SigningDetails signingDetails) {
13300        if (DEBUG_EPHEMERAL) {
13301            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13302                Slog.d(TAG, "Ephemeral install of " + packageName);
13303            }
13304        }
13305        final VerificationInfo verificationInfo = new VerificationInfo(
13306                sessionParams.originatingUri, sessionParams.referrerUri,
13307                sessionParams.originatingUid, installerUid);
13308
13309        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13310
13311        final Message msg = mHandler.obtainMessage(INIT_COPY);
13312        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13313                sessionParams.installReason);
13314        final InstallParams params = new InstallParams(origin, null, observer,
13315                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13316                verificationInfo, user, sessionParams.abiOverride,
13317                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13318        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13319        msg.obj = params;
13320
13321        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13322                System.identityHashCode(msg.obj));
13323        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13324                System.identityHashCode(msg.obj));
13325
13326        mHandler.sendMessage(msg);
13327    }
13328
13329    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13330            int userId) {
13331        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13332        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13333        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13334        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13335        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13336                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13337
13338        // Send a session commit broadcast
13339        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13340        info.installReason = pkgSetting.getInstallReason(userId);
13341        info.appPackageName = packageName;
13342        sendSessionCommitBroadcast(info, userId);
13343    }
13344
13345    @Override
13346    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13347            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13348        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13349            return;
13350        }
13351        Bundle extras = new Bundle(1);
13352        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13353        final int uid = UserHandle.getUid(
13354                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13355        extras.putInt(Intent.EXTRA_UID, uid);
13356
13357        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13358                packageName, extras, 0, null, null, userIds, instantUserIds);
13359        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13360            mHandler.post(() -> {
13361                        for (int userId : userIds) {
13362                            sendBootCompletedBroadcastToSystemApp(
13363                                    packageName, includeStopped, userId);
13364                        }
13365                    }
13366            );
13367        }
13368    }
13369
13370    /**
13371     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13372     * automatically without needing an explicit launch.
13373     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13374     */
13375    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13376            int userId) {
13377        // If user is not running, the app didn't miss any broadcast
13378        if (!mUserManagerInternal.isUserRunning(userId)) {
13379            return;
13380        }
13381        final IActivityManager am = ActivityManager.getService();
13382        try {
13383            // Deliver LOCKED_BOOT_COMPLETED first
13384            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13385                    .setPackage(packageName);
13386            if (includeStopped) {
13387                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13388            }
13389            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13390            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13391                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13392
13393            // Deliver BOOT_COMPLETED only if user is unlocked
13394            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13395                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13396                if (includeStopped) {
13397                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13398                }
13399                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13400                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13401            }
13402        } catch (RemoteException e) {
13403            throw e.rethrowFromSystemServer();
13404        }
13405    }
13406
13407    @Override
13408    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13409            int userId) {
13410        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13411        PackageSetting pkgSetting;
13412        final int callingUid = Binder.getCallingUid();
13413        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13414                true /* requireFullPermission */, true /* checkShell */,
13415                "setApplicationHiddenSetting for user " + userId);
13416
13417        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13418            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13419            return false;
13420        }
13421
13422        long callingId = Binder.clearCallingIdentity();
13423        try {
13424            boolean sendAdded = false;
13425            boolean sendRemoved = false;
13426            // writer
13427            synchronized (mPackages) {
13428                pkgSetting = mSettings.mPackages.get(packageName);
13429                if (pkgSetting == null) {
13430                    return false;
13431                }
13432                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13433                    return false;
13434                }
13435                // Do not allow "android" is being disabled
13436                if ("android".equals(packageName)) {
13437                    Slog.w(TAG, "Cannot hide package: android");
13438                    return false;
13439                }
13440                // Cannot hide static shared libs as they are considered
13441                // a part of the using app (emulating static linking). Also
13442                // static libs are installed always on internal storage.
13443                PackageParser.Package pkg = mPackages.get(packageName);
13444                if (pkg != null && pkg.staticSharedLibName != null) {
13445                    Slog.w(TAG, "Cannot hide package: " + packageName
13446                            + " providing static shared library: "
13447                            + pkg.staticSharedLibName);
13448                    return false;
13449                }
13450                // Only allow protected packages to hide themselves.
13451                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13452                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13453                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13454                    return false;
13455                }
13456
13457                if (pkgSetting.getHidden(userId) != hidden) {
13458                    pkgSetting.setHidden(hidden, userId);
13459                    mSettings.writePackageRestrictionsLPr(userId);
13460                    if (hidden) {
13461                        sendRemoved = true;
13462                    } else {
13463                        sendAdded = true;
13464                    }
13465                }
13466            }
13467            if (sendAdded) {
13468                sendPackageAddedForUser(packageName, pkgSetting, userId);
13469                return true;
13470            }
13471            if (sendRemoved) {
13472                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13473                        "hiding pkg");
13474                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13475                return true;
13476            }
13477        } finally {
13478            Binder.restoreCallingIdentity(callingId);
13479        }
13480        return false;
13481    }
13482
13483    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13484            int userId) {
13485        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13486        info.removedPackage = packageName;
13487        info.installerPackageName = pkgSetting.installerPackageName;
13488        info.removedUsers = new int[] {userId};
13489        info.broadcastUsers = new int[] {userId};
13490        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13491        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13492    }
13493
13494    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13495        if (pkgList.length > 0) {
13496            Bundle extras = new Bundle(1);
13497            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13498
13499            sendPackageBroadcast(
13500                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13501                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13502                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13503                    new int[] {userId}, null);
13504        }
13505    }
13506
13507    /**
13508     * Returns true if application is not found or there was an error. Otherwise it returns
13509     * the hidden state of the package for the given user.
13510     */
13511    @Override
13512    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13513        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13514        final int callingUid = Binder.getCallingUid();
13515        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13516                true /* requireFullPermission */, false /* checkShell */,
13517                "getApplicationHidden for user " + userId);
13518        PackageSetting ps;
13519        long callingId = Binder.clearCallingIdentity();
13520        try {
13521            // writer
13522            synchronized (mPackages) {
13523                ps = mSettings.mPackages.get(packageName);
13524                if (ps == null) {
13525                    return true;
13526                }
13527                if (filterAppAccessLPr(ps, callingUid, userId)) {
13528                    return true;
13529                }
13530                return ps.getHidden(userId);
13531            }
13532        } finally {
13533            Binder.restoreCallingIdentity(callingId);
13534        }
13535    }
13536
13537    /**
13538     * @hide
13539     */
13540    @Override
13541    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13542            int installReason) {
13543        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13544                null);
13545        PackageSetting pkgSetting;
13546        final int callingUid = Binder.getCallingUid();
13547        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13548                true /* requireFullPermission */, true /* checkShell */,
13549                "installExistingPackage for user " + userId);
13550        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13551            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13552        }
13553
13554        long callingId = Binder.clearCallingIdentity();
13555        try {
13556            boolean installed = false;
13557            final boolean instantApp =
13558                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13559            final boolean fullApp =
13560                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13561
13562            // writer
13563            synchronized (mPackages) {
13564                pkgSetting = mSettings.mPackages.get(packageName);
13565                if (pkgSetting == null) {
13566                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13567                }
13568                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13569                    // only allow the existing package to be used if it's installed as a full
13570                    // application for at least one user
13571                    boolean installAllowed = false;
13572                    for (int checkUserId : sUserManager.getUserIds()) {
13573                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13574                        if (installAllowed) {
13575                            break;
13576                        }
13577                    }
13578                    if (!installAllowed) {
13579                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13580                    }
13581                }
13582                if (!pkgSetting.getInstalled(userId)) {
13583                    pkgSetting.setInstalled(true, userId);
13584                    pkgSetting.setHidden(false, userId);
13585                    pkgSetting.setInstallReason(installReason, userId);
13586                    mSettings.writePackageRestrictionsLPr(userId);
13587                    mSettings.writeKernelMappingLPr(pkgSetting);
13588                    installed = true;
13589                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13590                    // upgrade app from instant to full; we don't allow app downgrade
13591                    installed = true;
13592                }
13593                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13594            }
13595
13596            if (installed) {
13597                if (pkgSetting.pkg != null) {
13598                    synchronized (mInstallLock) {
13599                        // We don't need to freeze for a brand new install
13600                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13601                    }
13602                }
13603                sendPackageAddedForUser(packageName, pkgSetting, userId);
13604                synchronized (mPackages) {
13605                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13606                }
13607            }
13608        } finally {
13609            Binder.restoreCallingIdentity(callingId);
13610        }
13611
13612        return PackageManager.INSTALL_SUCCEEDED;
13613    }
13614
13615    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13616            boolean instantApp, boolean fullApp) {
13617        // no state specified; do nothing
13618        if (!instantApp && !fullApp) {
13619            return;
13620        }
13621        if (userId != UserHandle.USER_ALL) {
13622            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13623                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13624            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13625                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13626            }
13627        } else {
13628            for (int currentUserId : sUserManager.getUserIds()) {
13629                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13630                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13631                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13632                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13633                }
13634            }
13635        }
13636    }
13637
13638    boolean isUserRestricted(int userId, String restrictionKey) {
13639        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13640        if (restrictions.getBoolean(restrictionKey, false)) {
13641            Log.w(TAG, "User is restricted: " + restrictionKey);
13642            return true;
13643        }
13644        return false;
13645    }
13646
13647    @Override
13648    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13649            int userId) {
13650        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13651        final int callingUid = Binder.getCallingUid();
13652        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13653                true /* requireFullPermission */, true /* checkShell */,
13654                "setPackagesSuspended for user " + userId);
13655
13656        if (ArrayUtils.isEmpty(packageNames)) {
13657            return packageNames;
13658        }
13659
13660        // List of package names for whom the suspended state has changed.
13661        List<String> changedPackages = new ArrayList<>(packageNames.length);
13662        // List of package names for whom the suspended state is not set as requested in this
13663        // method.
13664        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13665        long callingId = Binder.clearCallingIdentity();
13666        try {
13667            for (int i = 0; i < packageNames.length; i++) {
13668                String packageName = packageNames[i];
13669                boolean changed = false;
13670                final int appId;
13671                synchronized (mPackages) {
13672                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13673                    if (pkgSetting == null
13674                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13675                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13676                                + "\". Skipping suspending/un-suspending.");
13677                        unactionedPackages.add(packageName);
13678                        continue;
13679                    }
13680                    appId = pkgSetting.appId;
13681                    if (pkgSetting.getSuspended(userId) != suspended) {
13682                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13683                            unactionedPackages.add(packageName);
13684                            continue;
13685                        }
13686                        pkgSetting.setSuspended(suspended, userId);
13687                        mSettings.writePackageRestrictionsLPr(userId);
13688                        changed = true;
13689                        changedPackages.add(packageName);
13690                    }
13691                }
13692
13693                if (changed && suspended) {
13694                    killApplication(packageName, UserHandle.getUid(userId, appId),
13695                            "suspending package");
13696                }
13697            }
13698        } finally {
13699            Binder.restoreCallingIdentity(callingId);
13700        }
13701
13702        if (!changedPackages.isEmpty()) {
13703            sendPackagesSuspendedForUser(changedPackages.toArray(
13704                    new String[changedPackages.size()]), userId, suspended);
13705        }
13706
13707        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13708    }
13709
13710    @Override
13711    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13712        final int callingUid = Binder.getCallingUid();
13713        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13714                true /* requireFullPermission */, false /* checkShell */,
13715                "isPackageSuspendedForUser for user " + userId);
13716        synchronized (mPackages) {
13717            final PackageSetting ps = mSettings.mPackages.get(packageName);
13718            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13719                throw new IllegalArgumentException("Unknown target package: " + packageName);
13720            }
13721            return ps.getSuspended(userId);
13722        }
13723    }
13724
13725    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13726        if (isPackageDeviceAdmin(packageName, userId)) {
13727            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13728                    + "\": has an active device admin");
13729            return false;
13730        }
13731
13732        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13733        if (packageName.equals(activeLauncherPackageName)) {
13734            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13735                    + "\": contains the active launcher");
13736            return false;
13737        }
13738
13739        if (packageName.equals(mRequiredInstallerPackage)) {
13740            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13741                    + "\": required for package installation");
13742            return false;
13743        }
13744
13745        if (packageName.equals(mRequiredUninstallerPackage)) {
13746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13747                    + "\": required for package uninstallation");
13748            return false;
13749        }
13750
13751        if (packageName.equals(mRequiredVerifierPackage)) {
13752            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13753                    + "\": required for package verification");
13754            return false;
13755        }
13756
13757        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13758            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13759                    + "\": is the default dialer");
13760            return false;
13761        }
13762
13763        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13764            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13765                    + "\": protected package");
13766            return false;
13767        }
13768
13769        // Cannot suspend static shared libs as they are considered
13770        // a part of the using app (emulating static linking). Also
13771        // static libs are installed always on internal storage.
13772        PackageParser.Package pkg = mPackages.get(packageName);
13773        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13774            Slog.w(TAG, "Cannot suspend package: " + packageName
13775                    + " providing static shared library: "
13776                    + pkg.staticSharedLibName);
13777            return false;
13778        }
13779
13780        return true;
13781    }
13782
13783    private String getActiveLauncherPackageName(int userId) {
13784        Intent intent = new Intent(Intent.ACTION_MAIN);
13785        intent.addCategory(Intent.CATEGORY_HOME);
13786        ResolveInfo resolveInfo = resolveIntent(
13787                intent,
13788                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13789                PackageManager.MATCH_DEFAULT_ONLY,
13790                userId);
13791
13792        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13793    }
13794
13795    private String getDefaultDialerPackageName(int userId) {
13796        synchronized (mPackages) {
13797            return mSettings.getDefaultDialerPackageNameLPw(userId);
13798        }
13799    }
13800
13801    @Override
13802    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13803        mContext.enforceCallingOrSelfPermission(
13804                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13805                "Only package verification agents can verify applications");
13806
13807        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13808        final PackageVerificationResponse response = new PackageVerificationResponse(
13809                verificationCode, Binder.getCallingUid());
13810        msg.arg1 = id;
13811        msg.obj = response;
13812        mHandler.sendMessage(msg);
13813    }
13814
13815    @Override
13816    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13817            long millisecondsToDelay) {
13818        mContext.enforceCallingOrSelfPermission(
13819                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13820                "Only package verification agents can extend verification timeouts");
13821
13822        final PackageVerificationState state = mPendingVerification.get(id);
13823        final PackageVerificationResponse response = new PackageVerificationResponse(
13824                verificationCodeAtTimeout, Binder.getCallingUid());
13825
13826        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13827            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13828        }
13829        if (millisecondsToDelay < 0) {
13830            millisecondsToDelay = 0;
13831        }
13832        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13833                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13834            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13835        }
13836
13837        if ((state != null) && !state.timeoutExtended()) {
13838            state.extendTimeout();
13839
13840            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13841            msg.arg1 = id;
13842            msg.obj = response;
13843            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13844        }
13845    }
13846
13847    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13848            int verificationCode, UserHandle user) {
13849        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13850        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13851        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13852        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13853        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13854
13855        mContext.sendBroadcastAsUser(intent, user,
13856                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13857    }
13858
13859    private ComponentName matchComponentForVerifier(String packageName,
13860            List<ResolveInfo> receivers) {
13861        ActivityInfo targetReceiver = null;
13862
13863        final int NR = receivers.size();
13864        for (int i = 0; i < NR; i++) {
13865            final ResolveInfo info = receivers.get(i);
13866            if (info.activityInfo == null) {
13867                continue;
13868            }
13869
13870            if (packageName.equals(info.activityInfo.packageName)) {
13871                targetReceiver = info.activityInfo;
13872                break;
13873            }
13874        }
13875
13876        if (targetReceiver == null) {
13877            return null;
13878        }
13879
13880        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13881    }
13882
13883    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13884            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13885        if (pkgInfo.verifiers.length == 0) {
13886            return null;
13887        }
13888
13889        final int N = pkgInfo.verifiers.length;
13890        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13891        for (int i = 0; i < N; i++) {
13892            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13893
13894            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13895                    receivers);
13896            if (comp == null) {
13897                continue;
13898            }
13899
13900            final int verifierUid = getUidForVerifier(verifierInfo);
13901            if (verifierUid == -1) {
13902                continue;
13903            }
13904
13905            if (DEBUG_VERIFY) {
13906                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13907                        + " with the correct signature");
13908            }
13909            sufficientVerifiers.add(comp);
13910            verificationState.addSufficientVerifier(verifierUid);
13911        }
13912
13913        return sufficientVerifiers;
13914    }
13915
13916    private int getUidForVerifier(VerifierInfo verifierInfo) {
13917        synchronized (mPackages) {
13918            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13919            if (pkg == null) {
13920                return -1;
13921            } else if (pkg.mSigningDetails.signatures.length != 1) {
13922                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13923                        + " has more than one signature; ignoring");
13924                return -1;
13925            }
13926
13927            /*
13928             * If the public key of the package's signature does not match
13929             * our expected public key, then this is a different package and
13930             * we should skip.
13931             */
13932
13933            final byte[] expectedPublicKey;
13934            try {
13935                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
13936                final PublicKey publicKey = verifierSig.getPublicKey();
13937                expectedPublicKey = publicKey.getEncoded();
13938            } catch (CertificateException e) {
13939                return -1;
13940            }
13941
13942            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13943
13944            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13945                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13946                        + " does not have the expected public key; ignoring");
13947                return -1;
13948            }
13949
13950            return pkg.applicationInfo.uid;
13951        }
13952    }
13953
13954    @Override
13955    public void finishPackageInstall(int token, boolean didLaunch) {
13956        enforceSystemOrRoot("Only the system is allowed to finish installs");
13957
13958        if (DEBUG_INSTALL) {
13959            Slog.v(TAG, "BM finishing package install for " + token);
13960        }
13961        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13962
13963        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13964        mHandler.sendMessage(msg);
13965    }
13966
13967    /**
13968     * Get the verification agent timeout.  Used for both the APK verifier and the
13969     * intent filter verifier.
13970     *
13971     * @return verification timeout in milliseconds
13972     */
13973    private long getVerificationTimeout() {
13974        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13975                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13976                DEFAULT_VERIFICATION_TIMEOUT);
13977    }
13978
13979    /**
13980     * Get the default verification agent response code.
13981     *
13982     * @return default verification response code
13983     */
13984    private int getDefaultVerificationResponse(UserHandle user) {
13985        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13986            return PackageManager.VERIFICATION_REJECT;
13987        }
13988        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13989                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13990                DEFAULT_VERIFICATION_RESPONSE);
13991    }
13992
13993    /**
13994     * Check whether or not package verification has been enabled.
13995     *
13996     * @return true if verification should be performed
13997     */
13998    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13999        if (!DEFAULT_VERIFY_ENABLE) {
14000            return false;
14001        }
14002
14003        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14004
14005        // Check if installing from ADB
14006        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14007            // Do not run verification in a test harness environment
14008            if (ActivityManager.isRunningInTestHarness()) {
14009                return false;
14010            }
14011            if (ensureVerifyAppsEnabled) {
14012                return true;
14013            }
14014            // Check if the developer does not want package verification for ADB installs
14015            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14016                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14017                return false;
14018            }
14019        } else {
14020            // only when not installed from ADB, skip verification for instant apps when
14021            // the installer and verifier are the same.
14022            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14023                if (mInstantAppInstallerActivity != null
14024                        && mInstantAppInstallerActivity.packageName.equals(
14025                                mRequiredVerifierPackage)) {
14026                    try {
14027                        mContext.getSystemService(AppOpsManager.class)
14028                                .checkPackage(installerUid, mRequiredVerifierPackage);
14029                        if (DEBUG_VERIFY) {
14030                            Slog.i(TAG, "disable verification for instant app");
14031                        }
14032                        return false;
14033                    } catch (SecurityException ignore) { }
14034                }
14035            }
14036        }
14037
14038        if (ensureVerifyAppsEnabled) {
14039            return true;
14040        }
14041
14042        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14043                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14044    }
14045
14046    @Override
14047    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14048            throws RemoteException {
14049        mContext.enforceCallingOrSelfPermission(
14050                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14051                "Only intentfilter verification agents can verify applications");
14052
14053        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14054        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14055                Binder.getCallingUid(), verificationCode, failedDomains);
14056        msg.arg1 = id;
14057        msg.obj = response;
14058        mHandler.sendMessage(msg);
14059    }
14060
14061    @Override
14062    public int getIntentVerificationStatus(String packageName, int userId) {
14063        final int callingUid = Binder.getCallingUid();
14064        if (UserHandle.getUserId(callingUid) != userId) {
14065            mContext.enforceCallingOrSelfPermission(
14066                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14067                    "getIntentVerificationStatus" + userId);
14068        }
14069        if (getInstantAppPackageName(callingUid) != null) {
14070            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14071        }
14072        synchronized (mPackages) {
14073            final PackageSetting ps = mSettings.mPackages.get(packageName);
14074            if (ps == null
14075                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14076                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14077            }
14078            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14079        }
14080    }
14081
14082    @Override
14083    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14084        mContext.enforceCallingOrSelfPermission(
14085                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14086
14087        boolean result = false;
14088        synchronized (mPackages) {
14089            final PackageSetting ps = mSettings.mPackages.get(packageName);
14090            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14091                return false;
14092            }
14093            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14094        }
14095        if (result) {
14096            scheduleWritePackageRestrictionsLocked(userId);
14097        }
14098        return result;
14099    }
14100
14101    @Override
14102    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14103            String packageName) {
14104        final int callingUid = Binder.getCallingUid();
14105        if (getInstantAppPackageName(callingUid) != null) {
14106            return ParceledListSlice.emptyList();
14107        }
14108        synchronized (mPackages) {
14109            final PackageSetting ps = mSettings.mPackages.get(packageName);
14110            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14111                return ParceledListSlice.emptyList();
14112            }
14113            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14114        }
14115    }
14116
14117    @Override
14118    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14119        if (TextUtils.isEmpty(packageName)) {
14120            return ParceledListSlice.emptyList();
14121        }
14122        final int callingUid = Binder.getCallingUid();
14123        final int callingUserId = UserHandle.getUserId(callingUid);
14124        synchronized (mPackages) {
14125            PackageParser.Package pkg = mPackages.get(packageName);
14126            if (pkg == null || pkg.activities == null) {
14127                return ParceledListSlice.emptyList();
14128            }
14129            if (pkg.mExtras == null) {
14130                return ParceledListSlice.emptyList();
14131            }
14132            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14133            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14134                return ParceledListSlice.emptyList();
14135            }
14136            final int count = pkg.activities.size();
14137            ArrayList<IntentFilter> result = new ArrayList<>();
14138            for (int n=0; n<count; n++) {
14139                PackageParser.Activity activity = pkg.activities.get(n);
14140                if (activity.intents != null && activity.intents.size() > 0) {
14141                    result.addAll(activity.intents);
14142                }
14143            }
14144            return new ParceledListSlice<>(result);
14145        }
14146    }
14147
14148    @Override
14149    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14150        mContext.enforceCallingOrSelfPermission(
14151                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14152        if (UserHandle.getCallingUserId() != userId) {
14153            mContext.enforceCallingOrSelfPermission(
14154                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14155        }
14156
14157        synchronized (mPackages) {
14158            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14159            if (packageName != null) {
14160                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14161                        packageName, userId);
14162            }
14163            return result;
14164        }
14165    }
14166
14167    @Override
14168    public String getDefaultBrowserPackageName(int userId) {
14169        if (UserHandle.getCallingUserId() != userId) {
14170            mContext.enforceCallingOrSelfPermission(
14171                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14172        }
14173        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14174            return null;
14175        }
14176        synchronized (mPackages) {
14177            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14178        }
14179    }
14180
14181    /**
14182     * Get the "allow unknown sources" setting.
14183     *
14184     * @return the current "allow unknown sources" setting
14185     */
14186    private int getUnknownSourcesSettings() {
14187        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14188                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14189                -1);
14190    }
14191
14192    @Override
14193    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14194        final int callingUid = Binder.getCallingUid();
14195        if (getInstantAppPackageName(callingUid) != null) {
14196            return;
14197        }
14198        // writer
14199        synchronized (mPackages) {
14200            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14201            if (targetPackageSetting == null
14202                    || filterAppAccessLPr(
14203                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14204                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14205            }
14206
14207            PackageSetting installerPackageSetting;
14208            if (installerPackageName != null) {
14209                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14210                if (installerPackageSetting == null) {
14211                    throw new IllegalArgumentException("Unknown installer package: "
14212                            + installerPackageName);
14213                }
14214            } else {
14215                installerPackageSetting = null;
14216            }
14217
14218            Signature[] callerSignature;
14219            Object obj = mSettings.getUserIdLPr(callingUid);
14220            if (obj != null) {
14221                if (obj instanceof SharedUserSetting) {
14222                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14223                } else if (obj instanceof PackageSetting) {
14224                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14225                } else {
14226                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14227                }
14228            } else {
14229                throw new SecurityException("Unknown calling UID: " + callingUid);
14230            }
14231
14232            // Verify: can't set installerPackageName to a package that is
14233            // not signed with the same cert as the caller.
14234            if (installerPackageSetting != null) {
14235                if (compareSignatures(callerSignature,
14236                        installerPackageSetting.signatures.mSignatures)
14237                        != PackageManager.SIGNATURE_MATCH) {
14238                    throw new SecurityException(
14239                            "Caller does not have same cert as new installer package "
14240                            + installerPackageName);
14241                }
14242            }
14243
14244            // Verify: if target already has an installer package, it must
14245            // be signed with the same cert as the caller.
14246            if (targetPackageSetting.installerPackageName != null) {
14247                PackageSetting setting = mSettings.mPackages.get(
14248                        targetPackageSetting.installerPackageName);
14249                // If the currently set package isn't valid, then it's always
14250                // okay to change it.
14251                if (setting != null) {
14252                    if (compareSignatures(callerSignature,
14253                            setting.signatures.mSignatures)
14254                            != PackageManager.SIGNATURE_MATCH) {
14255                        throw new SecurityException(
14256                                "Caller does not have same cert as old installer package "
14257                                + targetPackageSetting.installerPackageName);
14258                    }
14259                }
14260            }
14261
14262            // Okay!
14263            targetPackageSetting.installerPackageName = installerPackageName;
14264            if (installerPackageName != null) {
14265                mSettings.mInstallerPackages.add(installerPackageName);
14266            }
14267            scheduleWriteSettingsLocked();
14268        }
14269    }
14270
14271    @Override
14272    public void setApplicationCategoryHint(String packageName, int categoryHint,
14273            String callerPackageName) {
14274        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14275            throw new SecurityException("Instant applications don't have access to this method");
14276        }
14277        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14278                callerPackageName);
14279        synchronized (mPackages) {
14280            PackageSetting ps = mSettings.mPackages.get(packageName);
14281            if (ps == null) {
14282                throw new IllegalArgumentException("Unknown target package " + packageName);
14283            }
14284            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14285                throw new IllegalArgumentException("Unknown target package " + packageName);
14286            }
14287            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14288                throw new IllegalArgumentException("Calling package " + callerPackageName
14289                        + " is not installer for " + packageName);
14290            }
14291
14292            if (ps.categoryHint != categoryHint) {
14293                ps.categoryHint = categoryHint;
14294                scheduleWriteSettingsLocked();
14295            }
14296        }
14297    }
14298
14299    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14300        // Queue up an async operation since the package installation may take a little while.
14301        mHandler.post(new Runnable() {
14302            public void run() {
14303                mHandler.removeCallbacks(this);
14304                 // Result object to be returned
14305                PackageInstalledInfo res = new PackageInstalledInfo();
14306                res.setReturnCode(currentStatus);
14307                res.uid = -1;
14308                res.pkg = null;
14309                res.removedInfo = null;
14310                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14311                    args.doPreInstall(res.returnCode);
14312                    synchronized (mInstallLock) {
14313                        installPackageTracedLI(args, res);
14314                    }
14315                    args.doPostInstall(res.returnCode, res.uid);
14316                }
14317
14318                // A restore should be performed at this point if (a) the install
14319                // succeeded, (b) the operation is not an update, and (c) the new
14320                // package has not opted out of backup participation.
14321                final boolean update = res.removedInfo != null
14322                        && res.removedInfo.removedPackage != null;
14323                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14324                boolean doRestore = !update
14325                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14326
14327                // Set up the post-install work request bookkeeping.  This will be used
14328                // and cleaned up by the post-install event handling regardless of whether
14329                // there's a restore pass performed.  Token values are >= 1.
14330                int token;
14331                if (mNextInstallToken < 0) mNextInstallToken = 1;
14332                token = mNextInstallToken++;
14333
14334                PostInstallData data = new PostInstallData(args, res);
14335                mRunningInstalls.put(token, data);
14336                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14337
14338                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14339                    // Pass responsibility to the Backup Manager.  It will perform a
14340                    // restore if appropriate, then pass responsibility back to the
14341                    // Package Manager to run the post-install observer callbacks
14342                    // and broadcasts.
14343                    IBackupManager bm = IBackupManager.Stub.asInterface(
14344                            ServiceManager.getService(Context.BACKUP_SERVICE));
14345                    if (bm != null) {
14346                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14347                                + " to BM for possible restore");
14348                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14349                        try {
14350                            // TODO: http://b/22388012
14351                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14352                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14353                            } else {
14354                                doRestore = false;
14355                            }
14356                        } catch (RemoteException e) {
14357                            // can't happen; the backup manager is local
14358                        } catch (Exception e) {
14359                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14360                            doRestore = false;
14361                        }
14362                    } else {
14363                        Slog.e(TAG, "Backup Manager not found!");
14364                        doRestore = false;
14365                    }
14366                }
14367
14368                if (!doRestore) {
14369                    // No restore possible, or the Backup Manager was mysteriously not
14370                    // available -- just fire the post-install work request directly.
14371                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14372
14373                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14374
14375                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14376                    mHandler.sendMessage(msg);
14377                }
14378            }
14379        });
14380    }
14381
14382    /**
14383     * Callback from PackageSettings whenever an app is first transitioned out of the
14384     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14385     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14386     * here whether the app is the target of an ongoing install, and only send the
14387     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14388     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14389     * handling.
14390     */
14391    void notifyFirstLaunch(final String packageName, final String installerPackage,
14392            final int userId) {
14393        // Serialize this with the rest of the install-process message chain.  In the
14394        // restore-at-install case, this Runnable will necessarily run before the
14395        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14396        // are coherent.  In the non-restore case, the app has already completed install
14397        // and been launched through some other means, so it is not in a problematic
14398        // state for observers to see the FIRST_LAUNCH signal.
14399        mHandler.post(new Runnable() {
14400            @Override
14401            public void run() {
14402                for (int i = 0; i < mRunningInstalls.size(); i++) {
14403                    final PostInstallData data = mRunningInstalls.valueAt(i);
14404                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14405                        continue;
14406                    }
14407                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14408                        // right package; but is it for the right user?
14409                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14410                            if (userId == data.res.newUsers[uIndex]) {
14411                                if (DEBUG_BACKUP) {
14412                                    Slog.i(TAG, "Package " + packageName
14413                                            + " being restored so deferring FIRST_LAUNCH");
14414                                }
14415                                return;
14416                            }
14417                        }
14418                    }
14419                }
14420                // didn't find it, so not being restored
14421                if (DEBUG_BACKUP) {
14422                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14423                }
14424                final boolean isInstantApp = isInstantApp(packageName, userId);
14425                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14426                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14427                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14428            }
14429        });
14430    }
14431
14432    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14433            int[] userIds, int[] instantUserIds) {
14434        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14435                installerPkg, null, userIds, instantUserIds);
14436    }
14437
14438    private abstract class HandlerParams {
14439        private static final int MAX_RETRIES = 4;
14440
14441        /**
14442         * Number of times startCopy() has been attempted and had a non-fatal
14443         * error.
14444         */
14445        private int mRetries = 0;
14446
14447        /** User handle for the user requesting the information or installation. */
14448        private final UserHandle mUser;
14449        String traceMethod;
14450        int traceCookie;
14451
14452        HandlerParams(UserHandle user) {
14453            mUser = user;
14454        }
14455
14456        UserHandle getUser() {
14457            return mUser;
14458        }
14459
14460        HandlerParams setTraceMethod(String traceMethod) {
14461            this.traceMethod = traceMethod;
14462            return this;
14463        }
14464
14465        HandlerParams setTraceCookie(int traceCookie) {
14466            this.traceCookie = traceCookie;
14467            return this;
14468        }
14469
14470        final boolean startCopy() {
14471            boolean res;
14472            try {
14473                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14474
14475                if (++mRetries > MAX_RETRIES) {
14476                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14477                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14478                    handleServiceError();
14479                    return false;
14480                } else {
14481                    handleStartCopy();
14482                    res = true;
14483                }
14484            } catch (RemoteException e) {
14485                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14486                mHandler.sendEmptyMessage(MCS_RECONNECT);
14487                res = false;
14488            }
14489            handleReturnCode();
14490            return res;
14491        }
14492
14493        final void serviceError() {
14494            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14495            handleServiceError();
14496            handleReturnCode();
14497        }
14498
14499        abstract void handleStartCopy() throws RemoteException;
14500        abstract void handleServiceError();
14501        abstract void handleReturnCode();
14502    }
14503
14504    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14505        for (File path : paths) {
14506            try {
14507                mcs.clearDirectory(path.getAbsolutePath());
14508            } catch (RemoteException e) {
14509            }
14510        }
14511    }
14512
14513    static class OriginInfo {
14514        /**
14515         * Location where install is coming from, before it has been
14516         * copied/renamed into place. This could be a single monolithic APK
14517         * file, or a cluster directory. This location may be untrusted.
14518         */
14519        final File file;
14520
14521        /**
14522         * Flag indicating that {@link #file} or {@link #cid} has already been
14523         * staged, meaning downstream users don't need to defensively copy the
14524         * contents.
14525         */
14526        final boolean staged;
14527
14528        /**
14529         * Flag indicating that {@link #file} or {@link #cid} is an already
14530         * installed app that is being moved.
14531         */
14532        final boolean existing;
14533
14534        final String resolvedPath;
14535        final File resolvedFile;
14536
14537        static OriginInfo fromNothing() {
14538            return new OriginInfo(null, false, false);
14539        }
14540
14541        static OriginInfo fromUntrustedFile(File file) {
14542            return new OriginInfo(file, false, false);
14543        }
14544
14545        static OriginInfo fromExistingFile(File file) {
14546            return new OriginInfo(file, false, true);
14547        }
14548
14549        static OriginInfo fromStagedFile(File file) {
14550            return new OriginInfo(file, true, false);
14551        }
14552
14553        private OriginInfo(File file, boolean staged, boolean existing) {
14554            this.file = file;
14555            this.staged = staged;
14556            this.existing = existing;
14557
14558            if (file != null) {
14559                resolvedPath = file.getAbsolutePath();
14560                resolvedFile = file;
14561            } else {
14562                resolvedPath = null;
14563                resolvedFile = null;
14564            }
14565        }
14566    }
14567
14568    static class MoveInfo {
14569        final int moveId;
14570        final String fromUuid;
14571        final String toUuid;
14572        final String packageName;
14573        final String dataAppName;
14574        final int appId;
14575        final String seinfo;
14576        final int targetSdkVersion;
14577
14578        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14579                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14580            this.moveId = moveId;
14581            this.fromUuid = fromUuid;
14582            this.toUuid = toUuid;
14583            this.packageName = packageName;
14584            this.dataAppName = dataAppName;
14585            this.appId = appId;
14586            this.seinfo = seinfo;
14587            this.targetSdkVersion = targetSdkVersion;
14588        }
14589    }
14590
14591    static class VerificationInfo {
14592        /** A constant used to indicate that a uid value is not present. */
14593        public static final int NO_UID = -1;
14594
14595        /** URI referencing where the package was downloaded from. */
14596        final Uri originatingUri;
14597
14598        /** HTTP referrer URI associated with the originatingURI. */
14599        final Uri referrer;
14600
14601        /** UID of the application that the install request originated from. */
14602        final int originatingUid;
14603
14604        /** UID of application requesting the install */
14605        final int installerUid;
14606
14607        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14608            this.originatingUri = originatingUri;
14609            this.referrer = referrer;
14610            this.originatingUid = originatingUid;
14611            this.installerUid = installerUid;
14612        }
14613    }
14614
14615    class InstallParams extends HandlerParams {
14616        final OriginInfo origin;
14617        final MoveInfo move;
14618        final IPackageInstallObserver2 observer;
14619        int installFlags;
14620        final String installerPackageName;
14621        final String volumeUuid;
14622        private InstallArgs mArgs;
14623        private int mRet;
14624        final String packageAbiOverride;
14625        final String[] grantedRuntimePermissions;
14626        final VerificationInfo verificationInfo;
14627        final PackageParser.SigningDetails signingDetails;
14628        final int installReason;
14629
14630        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14631                int installFlags, String installerPackageName, String volumeUuid,
14632                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14633                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14634            super(user);
14635            this.origin = origin;
14636            this.move = move;
14637            this.observer = observer;
14638            this.installFlags = installFlags;
14639            this.installerPackageName = installerPackageName;
14640            this.volumeUuid = volumeUuid;
14641            this.verificationInfo = verificationInfo;
14642            this.packageAbiOverride = packageAbiOverride;
14643            this.grantedRuntimePermissions = grantedPermissions;
14644            this.signingDetails = signingDetails;
14645            this.installReason = installReason;
14646        }
14647
14648        @Override
14649        public String toString() {
14650            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14651                    + " file=" + origin.file + "}";
14652        }
14653
14654        private int installLocationPolicy(PackageInfoLite pkgLite) {
14655            String packageName = pkgLite.packageName;
14656            int installLocation = pkgLite.installLocation;
14657            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14658            // reader
14659            synchronized (mPackages) {
14660                // Currently installed package which the new package is attempting to replace or
14661                // null if no such package is installed.
14662                PackageParser.Package installedPkg = mPackages.get(packageName);
14663                // Package which currently owns the data which the new package will own if installed.
14664                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14665                // will be null whereas dataOwnerPkg will contain information about the package
14666                // which was uninstalled while keeping its data.
14667                PackageParser.Package dataOwnerPkg = installedPkg;
14668                if (dataOwnerPkg  == null) {
14669                    PackageSetting ps = mSettings.mPackages.get(packageName);
14670                    if (ps != null) {
14671                        dataOwnerPkg = ps.pkg;
14672                    }
14673                }
14674
14675                if (dataOwnerPkg != null) {
14676                    // If installed, the package will get access to data left on the device by its
14677                    // predecessor. As a security measure, this is permited only if this is not a
14678                    // version downgrade or if the predecessor package is marked as debuggable and
14679                    // a downgrade is explicitly requested.
14680                    //
14681                    // On debuggable platform builds, downgrades are permitted even for
14682                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14683                    // not offer security guarantees and thus it's OK to disable some security
14684                    // mechanisms to make debugging/testing easier on those builds. However, even on
14685                    // debuggable builds downgrades of packages are permitted only if requested via
14686                    // installFlags. This is because we aim to keep the behavior of debuggable
14687                    // platform builds as close as possible to the behavior of non-debuggable
14688                    // platform builds.
14689                    final boolean downgradeRequested =
14690                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14691                    final boolean packageDebuggable =
14692                                (dataOwnerPkg.applicationInfo.flags
14693                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14694                    final boolean downgradePermitted =
14695                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14696                    if (!downgradePermitted) {
14697                        try {
14698                            checkDowngrade(dataOwnerPkg, pkgLite);
14699                        } catch (PackageManagerException e) {
14700                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14701                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14702                        }
14703                    }
14704                }
14705
14706                if (installedPkg != null) {
14707                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14708                        // Check for updated system application.
14709                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14710                            if (onSd) {
14711                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14712                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14713                            }
14714                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14715                        } else {
14716                            if (onSd) {
14717                                // Install flag overrides everything.
14718                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14719                            }
14720                            // If current upgrade specifies particular preference
14721                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14722                                // Application explicitly specified internal.
14723                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14724                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14725                                // App explictly prefers external. Let policy decide
14726                            } else {
14727                                // Prefer previous location
14728                                if (isExternal(installedPkg)) {
14729                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14730                                }
14731                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14732                            }
14733                        }
14734                    } else {
14735                        // Invalid install. Return error code
14736                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14737                    }
14738                }
14739            }
14740            // All the special cases have been taken care of.
14741            // Return result based on recommended install location.
14742            if (onSd) {
14743                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14744            }
14745            return pkgLite.recommendedInstallLocation;
14746        }
14747
14748        /*
14749         * Invoke remote method to get package information and install
14750         * location values. Override install location based on default
14751         * policy if needed and then create install arguments based
14752         * on the install location.
14753         */
14754        public void handleStartCopy() throws RemoteException {
14755            int ret = PackageManager.INSTALL_SUCCEEDED;
14756
14757            // If we're already staged, we've firmly committed to an install location
14758            if (origin.staged) {
14759                if (origin.file != null) {
14760                    installFlags |= PackageManager.INSTALL_INTERNAL;
14761                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14762                } else {
14763                    throw new IllegalStateException("Invalid stage location");
14764                }
14765            }
14766
14767            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14768            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14769            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14770            PackageInfoLite pkgLite = null;
14771
14772            if (onInt && onSd) {
14773                // Check if both bits are set.
14774                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14775                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14776            } else if (onSd && ephemeral) {
14777                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14778                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14779            } else {
14780                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14781                        packageAbiOverride);
14782
14783                if (DEBUG_EPHEMERAL && ephemeral) {
14784                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14785                }
14786
14787                /*
14788                 * If we have too little free space, try to free cache
14789                 * before giving up.
14790                 */
14791                if (!origin.staged && pkgLite.recommendedInstallLocation
14792                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14793                    // TODO: focus freeing disk space on the target device
14794                    final StorageManager storage = StorageManager.from(mContext);
14795                    final long lowThreshold = storage.getStorageLowBytes(
14796                            Environment.getDataDirectory());
14797
14798                    final long sizeBytes = mContainerService.calculateInstalledSize(
14799                            origin.resolvedPath, packageAbiOverride);
14800
14801                    try {
14802                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14803                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14804                                installFlags, packageAbiOverride);
14805                    } catch (InstallerException e) {
14806                        Slog.w(TAG, "Failed to free cache", e);
14807                    }
14808
14809                    /*
14810                     * The cache free must have deleted the file we
14811                     * downloaded to install.
14812                     *
14813                     * TODO: fix the "freeCache" call to not delete
14814                     *       the file we care about.
14815                     */
14816                    if (pkgLite.recommendedInstallLocation
14817                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14818                        pkgLite.recommendedInstallLocation
14819                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14820                    }
14821                }
14822            }
14823
14824            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14825                int loc = pkgLite.recommendedInstallLocation;
14826                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14827                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14828                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14829                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14830                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14831                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14832                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14833                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14834                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14835                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14836                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14837                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14838                } else {
14839                    // Override with defaults if needed.
14840                    loc = installLocationPolicy(pkgLite);
14841                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14842                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14843                    } else if (!onSd && !onInt) {
14844                        // Override install location with flags
14845                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14846                            // Set the flag to install on external media.
14847                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14848                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14849                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14850                            if (DEBUG_EPHEMERAL) {
14851                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14852                            }
14853                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14854                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14855                                    |PackageManager.INSTALL_INTERNAL);
14856                        } else {
14857                            // Make sure the flag for installing on external
14858                            // media is unset
14859                            installFlags |= PackageManager.INSTALL_INTERNAL;
14860                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14861                        }
14862                    }
14863                }
14864            }
14865
14866            final InstallArgs args = createInstallArgs(this);
14867            mArgs = args;
14868
14869            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14870                // TODO: http://b/22976637
14871                // Apps installed for "all" users use the device owner to verify the app
14872                UserHandle verifierUser = getUser();
14873                if (verifierUser == UserHandle.ALL) {
14874                    verifierUser = UserHandle.SYSTEM;
14875                }
14876
14877                /*
14878                 * Determine if we have any installed package verifiers. If we
14879                 * do, then we'll defer to them to verify the packages.
14880                 */
14881                final int requiredUid = mRequiredVerifierPackage == null ? -1
14882                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14883                                verifierUser.getIdentifier());
14884                final int installerUid =
14885                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14886                if (!origin.existing && requiredUid != -1
14887                        && isVerificationEnabled(
14888                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14889                    final Intent verification = new Intent(
14890                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14891                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14892                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14893                            PACKAGE_MIME_TYPE);
14894                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14895
14896                    // Query all live verifiers based on current user state
14897                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14898                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14899                            false /*allowDynamicSplits*/);
14900
14901                    if (DEBUG_VERIFY) {
14902                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14903                                + verification.toString() + " with " + pkgLite.verifiers.length
14904                                + " optional verifiers");
14905                    }
14906
14907                    final int verificationId = mPendingVerificationToken++;
14908
14909                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14910
14911                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14912                            installerPackageName);
14913
14914                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14915                            installFlags);
14916
14917                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14918                            pkgLite.packageName);
14919
14920                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14921                            pkgLite.versionCode);
14922
14923                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
14924                            pkgLite.getLongVersionCode());
14925
14926                    if (verificationInfo != null) {
14927                        if (verificationInfo.originatingUri != null) {
14928                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14929                                    verificationInfo.originatingUri);
14930                        }
14931                        if (verificationInfo.referrer != null) {
14932                            verification.putExtra(Intent.EXTRA_REFERRER,
14933                                    verificationInfo.referrer);
14934                        }
14935                        if (verificationInfo.originatingUid >= 0) {
14936                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14937                                    verificationInfo.originatingUid);
14938                        }
14939                        if (verificationInfo.installerUid >= 0) {
14940                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14941                                    verificationInfo.installerUid);
14942                        }
14943                    }
14944
14945                    final PackageVerificationState verificationState = new PackageVerificationState(
14946                            requiredUid, args);
14947
14948                    mPendingVerification.append(verificationId, verificationState);
14949
14950                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14951                            receivers, verificationState);
14952
14953                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14954                    final long idleDuration = getVerificationTimeout();
14955
14956                    /*
14957                     * If any sufficient verifiers were listed in the package
14958                     * manifest, attempt to ask them.
14959                     */
14960                    if (sufficientVerifiers != null) {
14961                        final int N = sufficientVerifiers.size();
14962                        if (N == 0) {
14963                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14964                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14965                        } else {
14966                            for (int i = 0; i < N; i++) {
14967                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14968                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14969                                        verifierComponent.getPackageName(), idleDuration,
14970                                        verifierUser.getIdentifier(), false, "package verifier");
14971
14972                                final Intent sufficientIntent = new Intent(verification);
14973                                sufficientIntent.setComponent(verifierComponent);
14974                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14975                            }
14976                        }
14977                    }
14978
14979                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14980                            mRequiredVerifierPackage, receivers);
14981                    if (ret == PackageManager.INSTALL_SUCCEEDED
14982                            && mRequiredVerifierPackage != null) {
14983                        Trace.asyncTraceBegin(
14984                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14985                        /*
14986                         * Send the intent to the required verification agent,
14987                         * but only start the verification timeout after the
14988                         * target BroadcastReceivers have run.
14989                         */
14990                        verification.setComponent(requiredVerifierComponent);
14991                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14992                                mRequiredVerifierPackage, idleDuration,
14993                                verifierUser.getIdentifier(), false, "package verifier");
14994                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14995                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14996                                new BroadcastReceiver() {
14997                                    @Override
14998                                    public void onReceive(Context context, Intent intent) {
14999                                        final Message msg = mHandler
15000                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15001                                        msg.arg1 = verificationId;
15002                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15003                                    }
15004                                }, null, 0, null, null);
15005
15006                        /*
15007                         * We don't want the copy to proceed until verification
15008                         * succeeds, so null out this field.
15009                         */
15010                        mArgs = null;
15011                    }
15012                } else {
15013                    /*
15014                     * No package verification is enabled, so immediately start
15015                     * the remote call to initiate copy using temporary file.
15016                     */
15017                    ret = args.copyApk(mContainerService, true);
15018                }
15019            }
15020
15021            mRet = ret;
15022        }
15023
15024        @Override
15025        void handleReturnCode() {
15026            // If mArgs is null, then MCS couldn't be reached. When it
15027            // reconnects, it will try again to install. At that point, this
15028            // will succeed.
15029            if (mArgs != null) {
15030                processPendingInstall(mArgs, mRet);
15031            }
15032        }
15033
15034        @Override
15035        void handleServiceError() {
15036            mArgs = createInstallArgs(this);
15037            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15038        }
15039    }
15040
15041    private InstallArgs createInstallArgs(InstallParams params) {
15042        if (params.move != null) {
15043            return new MoveInstallArgs(params);
15044        } else {
15045            return new FileInstallArgs(params);
15046        }
15047    }
15048
15049    /**
15050     * Create args that describe an existing installed package. Typically used
15051     * when cleaning up old installs, or used as a move source.
15052     */
15053    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15054            String resourcePath, String[] instructionSets) {
15055        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15056    }
15057
15058    static abstract class InstallArgs {
15059        /** @see InstallParams#origin */
15060        final OriginInfo origin;
15061        /** @see InstallParams#move */
15062        final MoveInfo move;
15063
15064        final IPackageInstallObserver2 observer;
15065        // Always refers to PackageManager flags only
15066        final int installFlags;
15067        final String installerPackageName;
15068        final String volumeUuid;
15069        final UserHandle user;
15070        final String abiOverride;
15071        final String[] installGrantPermissions;
15072        /** If non-null, drop an async trace when the install completes */
15073        final String traceMethod;
15074        final int traceCookie;
15075        final PackageParser.SigningDetails signingDetails;
15076        final int installReason;
15077
15078        // The list of instruction sets supported by this app. This is currently
15079        // only used during the rmdex() phase to clean up resources. We can get rid of this
15080        // if we move dex files under the common app path.
15081        /* nullable */ String[] instructionSets;
15082
15083        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15084                int installFlags, String installerPackageName, String volumeUuid,
15085                UserHandle user, String[] instructionSets,
15086                String abiOverride, String[] installGrantPermissions,
15087                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15088                int installReason) {
15089            this.origin = origin;
15090            this.move = move;
15091            this.installFlags = installFlags;
15092            this.observer = observer;
15093            this.installerPackageName = installerPackageName;
15094            this.volumeUuid = volumeUuid;
15095            this.user = user;
15096            this.instructionSets = instructionSets;
15097            this.abiOverride = abiOverride;
15098            this.installGrantPermissions = installGrantPermissions;
15099            this.traceMethod = traceMethod;
15100            this.traceCookie = traceCookie;
15101            this.signingDetails = signingDetails;
15102            this.installReason = installReason;
15103        }
15104
15105        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15106        abstract int doPreInstall(int status);
15107
15108        /**
15109         * Rename package into final resting place. All paths on the given
15110         * scanned package should be updated to reflect the rename.
15111         */
15112        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15113        abstract int doPostInstall(int status, int uid);
15114
15115        /** @see PackageSettingBase#codePathString */
15116        abstract String getCodePath();
15117        /** @see PackageSettingBase#resourcePathString */
15118        abstract String getResourcePath();
15119
15120        // Need installer lock especially for dex file removal.
15121        abstract void cleanUpResourcesLI();
15122        abstract boolean doPostDeleteLI(boolean delete);
15123
15124        /**
15125         * Called before the source arguments are copied. This is used mostly
15126         * for MoveParams when it needs to read the source file to put it in the
15127         * destination.
15128         */
15129        int doPreCopy() {
15130            return PackageManager.INSTALL_SUCCEEDED;
15131        }
15132
15133        /**
15134         * Called after the source arguments are copied. This is used mostly for
15135         * MoveParams when it needs to read the source file to put it in the
15136         * destination.
15137         */
15138        int doPostCopy(int uid) {
15139            return PackageManager.INSTALL_SUCCEEDED;
15140        }
15141
15142        protected boolean isFwdLocked() {
15143            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15144        }
15145
15146        protected boolean isExternalAsec() {
15147            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15148        }
15149
15150        protected boolean isEphemeral() {
15151            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15152        }
15153
15154        UserHandle getUser() {
15155            return user;
15156        }
15157    }
15158
15159    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15160        if (!allCodePaths.isEmpty()) {
15161            if (instructionSets == null) {
15162                throw new IllegalStateException("instructionSet == null");
15163            }
15164            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15165            for (String codePath : allCodePaths) {
15166                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15167                    try {
15168                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15169                    } catch (InstallerException ignored) {
15170                    }
15171                }
15172            }
15173        }
15174    }
15175
15176    /**
15177     * Logic to handle installation of non-ASEC applications, including copying
15178     * and renaming logic.
15179     */
15180    class FileInstallArgs extends InstallArgs {
15181        private File codeFile;
15182        private File resourceFile;
15183
15184        // Example topology:
15185        // /data/app/com.example/base.apk
15186        // /data/app/com.example/split_foo.apk
15187        // /data/app/com.example/lib/arm/libfoo.so
15188        // /data/app/com.example/lib/arm64/libfoo.so
15189        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15190
15191        /** New install */
15192        FileInstallArgs(InstallParams params) {
15193            super(params.origin, params.move, params.observer, params.installFlags,
15194                    params.installerPackageName, params.volumeUuid,
15195                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15196                    params.grantedRuntimePermissions,
15197                    params.traceMethod, params.traceCookie, params.signingDetails,
15198                    params.installReason);
15199            if (isFwdLocked()) {
15200                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15201            }
15202        }
15203
15204        /** Existing install */
15205        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15206            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15207                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15208                    PackageManager.INSTALL_REASON_UNKNOWN);
15209            this.codeFile = (codePath != null) ? new File(codePath) : null;
15210            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15211        }
15212
15213        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15214            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15215            try {
15216                return doCopyApk(imcs, temp);
15217            } finally {
15218                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15219            }
15220        }
15221
15222        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15223            if (origin.staged) {
15224                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15225                codeFile = origin.file;
15226                resourceFile = origin.file;
15227                return PackageManager.INSTALL_SUCCEEDED;
15228            }
15229
15230            try {
15231                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15232                final File tempDir =
15233                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15234                codeFile = tempDir;
15235                resourceFile = tempDir;
15236            } catch (IOException e) {
15237                Slog.w(TAG, "Failed to create copy file: " + e);
15238                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15239            }
15240
15241            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15242                @Override
15243                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15244                    if (!FileUtils.isValidExtFilename(name)) {
15245                        throw new IllegalArgumentException("Invalid filename: " + name);
15246                    }
15247                    try {
15248                        final File file = new File(codeFile, name);
15249                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15250                                O_RDWR | O_CREAT, 0644);
15251                        Os.chmod(file.getAbsolutePath(), 0644);
15252                        return new ParcelFileDescriptor(fd);
15253                    } catch (ErrnoException e) {
15254                        throw new RemoteException("Failed to open: " + e.getMessage());
15255                    }
15256                }
15257            };
15258
15259            int ret = PackageManager.INSTALL_SUCCEEDED;
15260            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15261            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15262                Slog.e(TAG, "Failed to copy package");
15263                return ret;
15264            }
15265
15266            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15267            NativeLibraryHelper.Handle handle = null;
15268            try {
15269                handle = NativeLibraryHelper.Handle.create(codeFile);
15270                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15271                        abiOverride);
15272            } catch (IOException e) {
15273                Slog.e(TAG, "Copying native libraries failed", e);
15274                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15275            } finally {
15276                IoUtils.closeQuietly(handle);
15277            }
15278
15279            return ret;
15280        }
15281
15282        int doPreInstall(int status) {
15283            if (status != PackageManager.INSTALL_SUCCEEDED) {
15284                cleanUp();
15285            }
15286            return status;
15287        }
15288
15289        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15290            if (status != PackageManager.INSTALL_SUCCEEDED) {
15291                cleanUp();
15292                return false;
15293            }
15294
15295            final File targetDir = codeFile.getParentFile();
15296            final File beforeCodeFile = codeFile;
15297            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15298
15299            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15300            try {
15301                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15302            } catch (ErrnoException e) {
15303                Slog.w(TAG, "Failed to rename", e);
15304                return false;
15305            }
15306
15307            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15308                Slog.w(TAG, "Failed to restorecon");
15309                return false;
15310            }
15311
15312            // Reflect the rename internally
15313            codeFile = afterCodeFile;
15314            resourceFile = afterCodeFile;
15315
15316            // Reflect the rename in scanned details
15317            try {
15318                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15319            } catch (IOException e) {
15320                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15321                return false;
15322            }
15323            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15324                    afterCodeFile, pkg.baseCodePath));
15325            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15326                    afterCodeFile, pkg.splitCodePaths));
15327
15328            // Reflect the rename in app info
15329            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15330            pkg.setApplicationInfoCodePath(pkg.codePath);
15331            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15332            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15333            pkg.setApplicationInfoResourcePath(pkg.codePath);
15334            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15335            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15336
15337            return true;
15338        }
15339
15340        int doPostInstall(int status, int uid) {
15341            if (status != PackageManager.INSTALL_SUCCEEDED) {
15342                cleanUp();
15343            }
15344            return status;
15345        }
15346
15347        @Override
15348        String getCodePath() {
15349            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15350        }
15351
15352        @Override
15353        String getResourcePath() {
15354            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15355        }
15356
15357        private boolean cleanUp() {
15358            if (codeFile == null || !codeFile.exists()) {
15359                return false;
15360            }
15361
15362            removeCodePathLI(codeFile);
15363
15364            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15365                resourceFile.delete();
15366            }
15367
15368            return true;
15369        }
15370
15371        void cleanUpResourcesLI() {
15372            // Try enumerating all code paths before deleting
15373            List<String> allCodePaths = Collections.EMPTY_LIST;
15374            if (codeFile != null && codeFile.exists()) {
15375                try {
15376                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15377                    allCodePaths = pkg.getAllCodePaths();
15378                } catch (PackageParserException e) {
15379                    // Ignored; we tried our best
15380                }
15381            }
15382
15383            cleanUp();
15384            removeDexFiles(allCodePaths, instructionSets);
15385        }
15386
15387        boolean doPostDeleteLI(boolean delete) {
15388            // XXX err, shouldn't we respect the delete flag?
15389            cleanUpResourcesLI();
15390            return true;
15391        }
15392    }
15393
15394    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15395            PackageManagerException {
15396        if (copyRet < 0) {
15397            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15398                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15399                throw new PackageManagerException(copyRet, message);
15400            }
15401        }
15402    }
15403
15404    /**
15405     * Extract the StorageManagerService "container ID" from the full code path of an
15406     * .apk.
15407     */
15408    static String cidFromCodePath(String fullCodePath) {
15409        int eidx = fullCodePath.lastIndexOf("/");
15410        String subStr1 = fullCodePath.substring(0, eidx);
15411        int sidx = subStr1.lastIndexOf("/");
15412        return subStr1.substring(sidx+1, eidx);
15413    }
15414
15415    /**
15416     * Logic to handle movement of existing installed applications.
15417     */
15418    class MoveInstallArgs extends InstallArgs {
15419        private File codeFile;
15420        private File resourceFile;
15421
15422        /** New install */
15423        MoveInstallArgs(InstallParams params) {
15424            super(params.origin, params.move, params.observer, params.installFlags,
15425                    params.installerPackageName, params.volumeUuid,
15426                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15427                    params.grantedRuntimePermissions,
15428                    params.traceMethod, params.traceCookie, params.signingDetails,
15429                    params.installReason);
15430        }
15431
15432        int copyApk(IMediaContainerService imcs, boolean temp) {
15433            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15434                    + move.fromUuid + " to " + move.toUuid);
15435            synchronized (mInstaller) {
15436                try {
15437                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15438                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15439                } catch (InstallerException e) {
15440                    Slog.w(TAG, "Failed to move app", e);
15441                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15442                }
15443            }
15444
15445            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15446            resourceFile = codeFile;
15447            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15448
15449            return PackageManager.INSTALL_SUCCEEDED;
15450        }
15451
15452        int doPreInstall(int status) {
15453            if (status != PackageManager.INSTALL_SUCCEEDED) {
15454                cleanUp(move.toUuid);
15455            }
15456            return status;
15457        }
15458
15459        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15460            if (status != PackageManager.INSTALL_SUCCEEDED) {
15461                cleanUp(move.toUuid);
15462                return false;
15463            }
15464
15465            // Reflect the move in app info
15466            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15467            pkg.setApplicationInfoCodePath(pkg.codePath);
15468            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15469            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15470            pkg.setApplicationInfoResourcePath(pkg.codePath);
15471            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15472            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15473
15474            return true;
15475        }
15476
15477        int doPostInstall(int status, int uid) {
15478            if (status == PackageManager.INSTALL_SUCCEEDED) {
15479                cleanUp(move.fromUuid);
15480            } else {
15481                cleanUp(move.toUuid);
15482            }
15483            return status;
15484        }
15485
15486        @Override
15487        String getCodePath() {
15488            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15489        }
15490
15491        @Override
15492        String getResourcePath() {
15493            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15494        }
15495
15496        private boolean cleanUp(String volumeUuid) {
15497            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15498                    move.dataAppName);
15499            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15500            final int[] userIds = sUserManager.getUserIds();
15501            synchronized (mInstallLock) {
15502                // Clean up both app data and code
15503                // All package moves are frozen until finished
15504                for (int userId : userIds) {
15505                    try {
15506                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15507                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15508                    } catch (InstallerException e) {
15509                        Slog.w(TAG, String.valueOf(e));
15510                    }
15511                }
15512                removeCodePathLI(codeFile);
15513            }
15514            return true;
15515        }
15516
15517        void cleanUpResourcesLI() {
15518            throw new UnsupportedOperationException();
15519        }
15520
15521        boolean doPostDeleteLI(boolean delete) {
15522            throw new UnsupportedOperationException();
15523        }
15524    }
15525
15526    static String getAsecPackageName(String packageCid) {
15527        int idx = packageCid.lastIndexOf("-");
15528        if (idx == -1) {
15529            return packageCid;
15530        }
15531        return packageCid.substring(0, idx);
15532    }
15533
15534    // Utility method used to create code paths based on package name and available index.
15535    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15536        String idxStr = "";
15537        int idx = 1;
15538        // Fall back to default value of idx=1 if prefix is not
15539        // part of oldCodePath
15540        if (oldCodePath != null) {
15541            String subStr = oldCodePath;
15542            // Drop the suffix right away
15543            if (suffix != null && subStr.endsWith(suffix)) {
15544                subStr = subStr.substring(0, subStr.length() - suffix.length());
15545            }
15546            // If oldCodePath already contains prefix find out the
15547            // ending index to either increment or decrement.
15548            int sidx = subStr.lastIndexOf(prefix);
15549            if (sidx != -1) {
15550                subStr = subStr.substring(sidx + prefix.length());
15551                if (subStr != null) {
15552                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15553                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15554                    }
15555                    try {
15556                        idx = Integer.parseInt(subStr);
15557                        if (idx <= 1) {
15558                            idx++;
15559                        } else {
15560                            idx--;
15561                        }
15562                    } catch(NumberFormatException e) {
15563                    }
15564                }
15565            }
15566        }
15567        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15568        return prefix + idxStr;
15569    }
15570
15571    private File getNextCodePath(File targetDir, String packageName) {
15572        File result;
15573        SecureRandom random = new SecureRandom();
15574        byte[] bytes = new byte[16];
15575        do {
15576            random.nextBytes(bytes);
15577            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15578            result = new File(targetDir, packageName + "-" + suffix);
15579        } while (result.exists());
15580        return result;
15581    }
15582
15583    // Utility method that returns the relative package path with respect
15584    // to the installation directory. Like say for /data/data/com.test-1.apk
15585    // string com.test-1 is returned.
15586    static String deriveCodePathName(String codePath) {
15587        if (codePath == null) {
15588            return null;
15589        }
15590        final File codeFile = new File(codePath);
15591        final String name = codeFile.getName();
15592        if (codeFile.isDirectory()) {
15593            return name;
15594        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15595            final int lastDot = name.lastIndexOf('.');
15596            return name.substring(0, lastDot);
15597        } else {
15598            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15599            return null;
15600        }
15601    }
15602
15603    static class PackageInstalledInfo {
15604        String name;
15605        int uid;
15606        // The set of users that originally had this package installed.
15607        int[] origUsers;
15608        // The set of users that now have this package installed.
15609        int[] newUsers;
15610        PackageParser.Package pkg;
15611        int returnCode;
15612        String returnMsg;
15613        String installerPackageName;
15614        PackageRemovedInfo removedInfo;
15615        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15616
15617        public void setError(int code, String msg) {
15618            setReturnCode(code);
15619            setReturnMessage(msg);
15620            Slog.w(TAG, msg);
15621        }
15622
15623        public void setError(String msg, PackageParserException e) {
15624            setReturnCode(e.error);
15625            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15626            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15627            for (int i = 0; i < childCount; i++) {
15628                addedChildPackages.valueAt(i).setError(msg, e);
15629            }
15630            Slog.w(TAG, msg, e);
15631        }
15632
15633        public void setError(String msg, PackageManagerException e) {
15634            returnCode = e.error;
15635            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15636            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15637            for (int i = 0; i < childCount; i++) {
15638                addedChildPackages.valueAt(i).setError(msg, e);
15639            }
15640            Slog.w(TAG, msg, e);
15641        }
15642
15643        public void setReturnCode(int returnCode) {
15644            this.returnCode = returnCode;
15645            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15646            for (int i = 0; i < childCount; i++) {
15647                addedChildPackages.valueAt(i).returnCode = returnCode;
15648            }
15649        }
15650
15651        private void setReturnMessage(String returnMsg) {
15652            this.returnMsg = returnMsg;
15653            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15654            for (int i = 0; i < childCount; i++) {
15655                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15656            }
15657        }
15658
15659        // In some error cases we want to convey more info back to the observer
15660        String origPackage;
15661        String origPermission;
15662    }
15663
15664    /*
15665     * Install a non-existing package.
15666     */
15667    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15668            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15669            String volumeUuid, PackageInstalledInfo res, int installReason) {
15670        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15671
15672        // Remember this for later, in case we need to rollback this install
15673        String pkgName = pkg.packageName;
15674
15675        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15676
15677        synchronized(mPackages) {
15678            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15679            if (renamedPackage != null) {
15680                // A package with the same name is already installed, though
15681                // it has been renamed to an older name.  The package we
15682                // are trying to install should be installed as an update to
15683                // the existing one, but that has not been requested, so bail.
15684                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15685                        + " without first uninstalling package running as "
15686                        + renamedPackage);
15687                return;
15688            }
15689            if (mPackages.containsKey(pkgName)) {
15690                // Don't allow installation over an existing package with the same name.
15691                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15692                        + " without first uninstalling.");
15693                return;
15694            }
15695        }
15696
15697        try {
15698            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15699                    System.currentTimeMillis(), user);
15700
15701            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15702
15703            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15704                prepareAppDataAfterInstallLIF(newPackage);
15705
15706            } else {
15707                // Remove package from internal structures, but keep around any
15708                // data that might have already existed
15709                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15710                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15711            }
15712        } catch (PackageManagerException e) {
15713            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15714        }
15715
15716        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15717    }
15718
15719    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15720        try (DigestInputStream digestStream =
15721                new DigestInputStream(new FileInputStream(file), digest)) {
15722            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15723        }
15724    }
15725
15726    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15727            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15728            PackageInstalledInfo res, int installReason) {
15729        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15730
15731        final PackageParser.Package oldPackage;
15732        final PackageSetting ps;
15733        final String pkgName = pkg.packageName;
15734        final int[] allUsers;
15735        final int[] installedUsers;
15736
15737        synchronized(mPackages) {
15738            oldPackage = mPackages.get(pkgName);
15739            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15740
15741            // don't allow upgrade to target a release SDK from a pre-release SDK
15742            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15743                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15744            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15745                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15746            if (oldTargetsPreRelease
15747                    && !newTargetsPreRelease
15748                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15749                Slog.w(TAG, "Can't install package targeting released sdk");
15750                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15751                return;
15752            }
15753
15754            ps = mSettings.mPackages.get(pkgName);
15755
15756            // verify signatures are valid
15757            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15758            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15759                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15760                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15761                            "New package not signed by keys specified by upgrade-keysets: "
15762                                    + pkgName);
15763                    return;
15764                }
15765            } else {
15766                // default to original signature matching
15767                if (compareSignatures(oldPackage.mSigningDetails.signatures,
15768                        pkg.mSigningDetails.signatures)
15769                        != PackageManager.SIGNATURE_MATCH) {
15770                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15771                            "New package has a different signature: " + pkgName);
15772                    return;
15773                }
15774            }
15775
15776            // don't allow a system upgrade unless the upgrade hash matches
15777            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15778                byte[] digestBytes = null;
15779                try {
15780                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15781                    updateDigest(digest, new File(pkg.baseCodePath));
15782                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15783                        for (String path : pkg.splitCodePaths) {
15784                            updateDigest(digest, new File(path));
15785                        }
15786                    }
15787                    digestBytes = digest.digest();
15788                } catch (NoSuchAlgorithmException | IOException e) {
15789                    res.setError(INSTALL_FAILED_INVALID_APK,
15790                            "Could not compute hash: " + pkgName);
15791                    return;
15792                }
15793                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15794                    res.setError(INSTALL_FAILED_INVALID_APK,
15795                            "New package fails restrict-update check: " + pkgName);
15796                    return;
15797                }
15798                // retain upgrade restriction
15799                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15800            }
15801
15802            // Check for shared user id changes
15803            String invalidPackageName =
15804                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15805            if (invalidPackageName != null) {
15806                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15807                        "Package " + invalidPackageName + " tried to change user "
15808                                + oldPackage.mSharedUserId);
15809                return;
15810            }
15811
15812            // check if the new package supports all of the abis which the old package supports
15813            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
15814            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
15815            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
15816                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15817                        "Update to package " + pkgName + " doesn't support multi arch");
15818                return;
15819            }
15820
15821            // In case of rollback, remember per-user/profile install state
15822            allUsers = sUserManager.getUserIds();
15823            installedUsers = ps.queryInstalledUsers(allUsers, true);
15824
15825            // don't allow an upgrade from full to ephemeral
15826            if (isInstantApp) {
15827                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15828                    for (int currentUser : allUsers) {
15829                        if (!ps.getInstantApp(currentUser)) {
15830                            // can't downgrade from full to instant
15831                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15832                                    + " for user: " + currentUser);
15833                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15834                            return;
15835                        }
15836                    }
15837                } else if (!ps.getInstantApp(user.getIdentifier())) {
15838                    // can't downgrade from full to instant
15839                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15840                            + " for user: " + user.getIdentifier());
15841                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15842                    return;
15843                }
15844            }
15845        }
15846
15847        // Update what is removed
15848        res.removedInfo = new PackageRemovedInfo(this);
15849        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15850        res.removedInfo.removedPackage = oldPackage.packageName;
15851        res.removedInfo.installerPackageName = ps.installerPackageName;
15852        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15853        res.removedInfo.isUpdate = true;
15854        res.removedInfo.origUsers = installedUsers;
15855        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15856        for (int i = 0; i < installedUsers.length; i++) {
15857            final int userId = installedUsers[i];
15858            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15859        }
15860
15861        final int childCount = (oldPackage.childPackages != null)
15862                ? oldPackage.childPackages.size() : 0;
15863        for (int i = 0; i < childCount; i++) {
15864            boolean childPackageUpdated = false;
15865            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15866            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15867            if (res.addedChildPackages != null) {
15868                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15869                if (childRes != null) {
15870                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15871                    childRes.removedInfo.removedPackage = childPkg.packageName;
15872                    if (childPs != null) {
15873                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15874                    }
15875                    childRes.removedInfo.isUpdate = true;
15876                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15877                    childPackageUpdated = true;
15878                }
15879            }
15880            if (!childPackageUpdated) {
15881                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15882                childRemovedRes.removedPackage = childPkg.packageName;
15883                if (childPs != null) {
15884                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15885                }
15886                childRemovedRes.isUpdate = false;
15887                childRemovedRes.dataRemoved = true;
15888                synchronized (mPackages) {
15889                    if (childPs != null) {
15890                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15891                    }
15892                }
15893                if (res.removedInfo.removedChildPackages == null) {
15894                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15895                }
15896                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15897            }
15898        }
15899
15900        boolean sysPkg = (isSystemApp(oldPackage));
15901        if (sysPkg) {
15902            // Set the system/privileged/oem/vendor flags as needed
15903            final boolean privileged =
15904                    (oldPackage.applicationInfo.privateFlags
15905                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15906            final boolean oem =
15907                    (oldPackage.applicationInfo.privateFlags
15908                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15909            final boolean vendor =
15910                    (oldPackage.applicationInfo.privateFlags
15911                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
15912            final @ParseFlags int systemParseFlags = parseFlags;
15913            final @ScanFlags int systemScanFlags = scanFlags
15914                    | SCAN_AS_SYSTEM
15915                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15916                    | (oem ? SCAN_AS_OEM : 0)
15917                    | (vendor ? SCAN_AS_VENDOR : 0);
15918
15919            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15920                    user, allUsers, installerPackageName, res, installReason);
15921        } else {
15922            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15923                    user, allUsers, installerPackageName, res, installReason);
15924        }
15925    }
15926
15927    @Override
15928    public List<String> getPreviousCodePaths(String packageName) {
15929        final int callingUid = Binder.getCallingUid();
15930        final List<String> result = new ArrayList<>();
15931        if (getInstantAppPackageName(callingUid) != null) {
15932            return result;
15933        }
15934        final PackageSetting ps = mSettings.mPackages.get(packageName);
15935        if (ps != null
15936                && ps.oldCodePaths != null
15937                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15938            result.addAll(ps.oldCodePaths);
15939        }
15940        return result;
15941    }
15942
15943    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15944            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15945            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15946            String installerPackageName, PackageInstalledInfo res, int installReason) {
15947        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15948                + deletedPackage);
15949
15950        String pkgName = deletedPackage.packageName;
15951        boolean deletedPkg = true;
15952        boolean addedPkg = false;
15953        boolean updatedSettings = false;
15954        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15955        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15956                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15957
15958        final long origUpdateTime = (pkg.mExtras != null)
15959                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15960
15961        // First delete the existing package while retaining the data directory
15962        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15963                res.removedInfo, true, pkg)) {
15964            // If the existing package wasn't successfully deleted
15965            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15966            deletedPkg = false;
15967        } else {
15968            // Successfully deleted the old package; proceed with replace.
15969
15970            // If deleted package lived in a container, give users a chance to
15971            // relinquish resources before killing.
15972            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15973                if (DEBUG_INSTALL) {
15974                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15975                }
15976                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15977                final ArrayList<String> pkgList = new ArrayList<String>(1);
15978                pkgList.add(deletedPackage.applicationInfo.packageName);
15979                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15980            }
15981
15982            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15983                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15984            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15985
15986            try {
15987                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15988                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15989                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15990                        installReason);
15991
15992                // Update the in-memory copy of the previous code paths.
15993                PackageSetting ps = mSettings.mPackages.get(pkgName);
15994                if (!killApp) {
15995                    if (ps.oldCodePaths == null) {
15996                        ps.oldCodePaths = new ArraySet<>();
15997                    }
15998                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15999                    if (deletedPackage.splitCodePaths != null) {
16000                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16001                    }
16002                } else {
16003                    ps.oldCodePaths = null;
16004                }
16005                if (ps.childPackageNames != null) {
16006                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16007                        final String childPkgName = ps.childPackageNames.get(i);
16008                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16009                        childPs.oldCodePaths = ps.oldCodePaths;
16010                    }
16011                }
16012                // set instant app status, but, only if it's explicitly specified
16013                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16014                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16015                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16016                prepareAppDataAfterInstallLIF(newPackage);
16017                addedPkg = true;
16018                mDexManager.notifyPackageUpdated(newPackage.packageName,
16019                        newPackage.baseCodePath, newPackage.splitCodePaths);
16020            } catch (PackageManagerException e) {
16021                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16022            }
16023        }
16024
16025        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16026            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16027
16028            // Revert all internal state mutations and added folders for the failed install
16029            if (addedPkg) {
16030                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16031                        res.removedInfo, true, null);
16032            }
16033
16034            // Restore the old package
16035            if (deletedPkg) {
16036                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16037                File restoreFile = new File(deletedPackage.codePath);
16038                // Parse old package
16039                boolean oldExternal = isExternal(deletedPackage);
16040                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16041                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16042                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16043                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16044                try {
16045                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16046                            null);
16047                } catch (PackageManagerException e) {
16048                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16049                            + e.getMessage());
16050                    return;
16051                }
16052
16053                synchronized (mPackages) {
16054                    // Ensure the installer package name up to date
16055                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16056
16057                    // Update permissions for restored package
16058                    mPermissionManager.updatePermissions(
16059                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16060                            mPermissionCallback);
16061
16062                    mSettings.writeLPr();
16063                }
16064
16065                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16066            }
16067        } else {
16068            synchronized (mPackages) {
16069                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16070                if (ps != null) {
16071                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16072                    if (res.removedInfo.removedChildPackages != null) {
16073                        final int childCount = res.removedInfo.removedChildPackages.size();
16074                        // Iterate in reverse as we may modify the collection
16075                        for (int i = childCount - 1; i >= 0; i--) {
16076                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16077                            if (res.addedChildPackages.containsKey(childPackageName)) {
16078                                res.removedInfo.removedChildPackages.removeAt(i);
16079                            } else {
16080                                PackageRemovedInfo childInfo = res.removedInfo
16081                                        .removedChildPackages.valueAt(i);
16082                                childInfo.removedForAllUsers = mPackages.get(
16083                                        childInfo.removedPackage) == null;
16084                            }
16085                        }
16086                    }
16087                }
16088            }
16089        }
16090    }
16091
16092    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16093            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16094            final @ScanFlags int scanFlags, UserHandle user,
16095            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16096            int installReason) {
16097        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16098                + ", old=" + deletedPackage);
16099
16100        final boolean disabledSystem;
16101
16102        // Remove existing system package
16103        removePackageLI(deletedPackage, true);
16104
16105        synchronized (mPackages) {
16106            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16107        }
16108        if (!disabledSystem) {
16109            // We didn't need to disable the .apk as a current system package,
16110            // which means we are replacing another update that is already
16111            // installed.  We need to make sure to delete the older one's .apk.
16112            res.removedInfo.args = createInstallArgsForExisting(0,
16113                    deletedPackage.applicationInfo.getCodePath(),
16114                    deletedPackage.applicationInfo.getResourcePath(),
16115                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16116        } else {
16117            res.removedInfo.args = null;
16118        }
16119
16120        // Successfully disabled the old package. Now proceed with re-installation
16121        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16122                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16123        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16124
16125        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16126        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16127                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16128
16129        PackageParser.Package newPackage = null;
16130        try {
16131            // Add the package to the internal data structures
16132            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16133
16134            // Set the update and install times
16135            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16136            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16137                    System.currentTimeMillis());
16138
16139            // Update the package dynamic state if succeeded
16140            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16141                // Now that the install succeeded make sure we remove data
16142                // directories for any child package the update removed.
16143                final int deletedChildCount = (deletedPackage.childPackages != null)
16144                        ? deletedPackage.childPackages.size() : 0;
16145                final int newChildCount = (newPackage.childPackages != null)
16146                        ? newPackage.childPackages.size() : 0;
16147                for (int i = 0; i < deletedChildCount; i++) {
16148                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16149                    boolean childPackageDeleted = true;
16150                    for (int j = 0; j < newChildCount; j++) {
16151                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16152                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16153                            childPackageDeleted = false;
16154                            break;
16155                        }
16156                    }
16157                    if (childPackageDeleted) {
16158                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16159                                deletedChildPkg.packageName);
16160                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16161                            PackageRemovedInfo removedChildRes = res.removedInfo
16162                                    .removedChildPackages.get(deletedChildPkg.packageName);
16163                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16164                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16165                        }
16166                    }
16167                }
16168
16169                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16170                        installReason);
16171                prepareAppDataAfterInstallLIF(newPackage);
16172
16173                mDexManager.notifyPackageUpdated(newPackage.packageName,
16174                            newPackage.baseCodePath, newPackage.splitCodePaths);
16175            }
16176        } catch (PackageManagerException e) {
16177            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16178            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16179        }
16180
16181        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16182            // Re installation failed. Restore old information
16183            // Remove new pkg information
16184            if (newPackage != null) {
16185                removeInstalledPackageLI(newPackage, true);
16186            }
16187            // Add back the old system package
16188            try {
16189                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16190            } catch (PackageManagerException e) {
16191                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16192            }
16193
16194            synchronized (mPackages) {
16195                if (disabledSystem) {
16196                    enableSystemPackageLPw(deletedPackage);
16197                }
16198
16199                // Ensure the installer package name up to date
16200                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16201
16202                // Update permissions for restored package
16203                mPermissionManager.updatePermissions(
16204                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16205                        mPermissionCallback);
16206
16207                mSettings.writeLPr();
16208            }
16209
16210            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16211                    + " after failed upgrade");
16212        }
16213    }
16214
16215    /**
16216     * Checks whether the parent or any of the child packages have a change shared
16217     * user. For a package to be a valid update the shred users of the parent and
16218     * the children should match. We may later support changing child shared users.
16219     * @param oldPkg The updated package.
16220     * @param newPkg The update package.
16221     * @return The shared user that change between the versions.
16222     */
16223    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16224            PackageParser.Package newPkg) {
16225        // Check parent shared user
16226        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16227            return newPkg.packageName;
16228        }
16229        // Check child shared users
16230        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16231        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16232        for (int i = 0; i < newChildCount; i++) {
16233            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16234            // If this child was present, did it have the same shared user?
16235            for (int j = 0; j < oldChildCount; j++) {
16236                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16237                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16238                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16239                    return newChildPkg.packageName;
16240                }
16241            }
16242        }
16243        return null;
16244    }
16245
16246    private void removeNativeBinariesLI(PackageSetting ps) {
16247        // Remove the lib path for the parent package
16248        if (ps != null) {
16249            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16250            // Remove the lib path for the child packages
16251            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16252            for (int i = 0; i < childCount; i++) {
16253                PackageSetting childPs = null;
16254                synchronized (mPackages) {
16255                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16256                }
16257                if (childPs != null) {
16258                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16259                            .legacyNativeLibraryPathString);
16260                }
16261            }
16262        }
16263    }
16264
16265    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16266        // Enable the parent package
16267        mSettings.enableSystemPackageLPw(pkg.packageName);
16268        // Enable the child packages
16269        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16270        for (int i = 0; i < childCount; i++) {
16271            PackageParser.Package childPkg = pkg.childPackages.get(i);
16272            mSettings.enableSystemPackageLPw(childPkg.packageName);
16273        }
16274    }
16275
16276    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16277            PackageParser.Package newPkg) {
16278        // Disable the parent package (parent always replaced)
16279        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16280        // Disable the child packages
16281        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16282        for (int i = 0; i < childCount; i++) {
16283            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16284            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16285            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16286        }
16287        return disabled;
16288    }
16289
16290    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16291            String installerPackageName) {
16292        // Enable the parent package
16293        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16294        // Enable the child packages
16295        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16296        for (int i = 0; i < childCount; i++) {
16297            PackageParser.Package childPkg = pkg.childPackages.get(i);
16298            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16299        }
16300    }
16301
16302    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16303            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16304        // Update the parent package setting
16305        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16306                res, user, installReason);
16307        // Update the child packages setting
16308        final int childCount = (newPackage.childPackages != null)
16309                ? newPackage.childPackages.size() : 0;
16310        for (int i = 0; i < childCount; i++) {
16311            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16312            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16313            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16314                    childRes.origUsers, childRes, user, installReason);
16315        }
16316    }
16317
16318    private void updateSettingsInternalLI(PackageParser.Package pkg,
16319            String installerPackageName, int[] allUsers, int[] installedForUsers,
16320            PackageInstalledInfo res, UserHandle user, int installReason) {
16321        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16322
16323        String pkgName = pkg.packageName;
16324        synchronized (mPackages) {
16325            //write settings. the installStatus will be incomplete at this stage.
16326            //note that the new package setting would have already been
16327            //added to mPackages. It hasn't been persisted yet.
16328            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16329            // TODO: Remove this write? It's also written at the end of this method
16330            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16331            mSettings.writeLPr();
16332            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16333        }
16334
16335        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16336        synchronized (mPackages) {
16337// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16338            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16339                    mPermissionCallback);
16340            // For system-bundled packages, we assume that installing an upgraded version
16341            // of the package implies that the user actually wants to run that new code,
16342            // so we enable the package.
16343            PackageSetting ps = mSettings.mPackages.get(pkgName);
16344            final int userId = user.getIdentifier();
16345            if (ps != null) {
16346                if (isSystemApp(pkg)) {
16347                    if (DEBUG_INSTALL) {
16348                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16349                    }
16350                    // Enable system package for requested users
16351                    if (res.origUsers != null) {
16352                        for (int origUserId : res.origUsers) {
16353                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16354                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16355                                        origUserId, installerPackageName);
16356                            }
16357                        }
16358                    }
16359                    // Also convey the prior install/uninstall state
16360                    if (allUsers != null && installedForUsers != null) {
16361                        for (int currentUserId : allUsers) {
16362                            final boolean installed = ArrayUtils.contains(
16363                                    installedForUsers, currentUserId);
16364                            if (DEBUG_INSTALL) {
16365                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16366                            }
16367                            ps.setInstalled(installed, currentUserId);
16368                        }
16369                        // these install state changes will be persisted in the
16370                        // upcoming call to mSettings.writeLPr().
16371                    }
16372                }
16373                // It's implied that when a user requests installation, they want the app to be
16374                // installed and enabled.
16375                if (userId != UserHandle.USER_ALL) {
16376                    ps.setInstalled(true, userId);
16377                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16378                }
16379
16380                // When replacing an existing package, preserve the original install reason for all
16381                // users that had the package installed before.
16382                final Set<Integer> previousUserIds = new ArraySet<>();
16383                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16384                    final int installReasonCount = res.removedInfo.installReasons.size();
16385                    for (int i = 0; i < installReasonCount; i++) {
16386                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16387                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16388                        ps.setInstallReason(previousInstallReason, previousUserId);
16389                        previousUserIds.add(previousUserId);
16390                    }
16391                }
16392
16393                // Set install reason for users that are having the package newly installed.
16394                if (userId == UserHandle.USER_ALL) {
16395                    for (int currentUserId : sUserManager.getUserIds()) {
16396                        if (!previousUserIds.contains(currentUserId)) {
16397                            ps.setInstallReason(installReason, currentUserId);
16398                        }
16399                    }
16400                } else if (!previousUserIds.contains(userId)) {
16401                    ps.setInstallReason(installReason, userId);
16402                }
16403                mSettings.writeKernelMappingLPr(ps);
16404            }
16405            res.name = pkgName;
16406            res.uid = pkg.applicationInfo.uid;
16407            res.pkg = pkg;
16408            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16409            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16410            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16411            //to update install status
16412            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16413            mSettings.writeLPr();
16414            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16415        }
16416
16417        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16418    }
16419
16420    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16421        try {
16422            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16423            installPackageLI(args, res);
16424        } finally {
16425            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16426        }
16427    }
16428
16429    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16430        final int installFlags = args.installFlags;
16431        final String installerPackageName = args.installerPackageName;
16432        final String volumeUuid = args.volumeUuid;
16433        final File tmpPackageFile = new File(args.getCodePath());
16434        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16435        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16436                || (args.volumeUuid != null));
16437        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16438        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16439        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16440        final boolean virtualPreload =
16441                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16442        boolean replace = false;
16443        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16444        if (args.move != null) {
16445            // moving a complete application; perform an initial scan on the new install location
16446            scanFlags |= SCAN_INITIAL;
16447        }
16448        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16449            scanFlags |= SCAN_DONT_KILL_APP;
16450        }
16451        if (instantApp) {
16452            scanFlags |= SCAN_AS_INSTANT_APP;
16453        }
16454        if (fullApp) {
16455            scanFlags |= SCAN_AS_FULL_APP;
16456        }
16457        if (virtualPreload) {
16458            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16459        }
16460
16461        // Result object to be returned
16462        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16463        res.installerPackageName = installerPackageName;
16464
16465        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16466
16467        // Sanity check
16468        if (instantApp && (forwardLocked || onExternal)) {
16469            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16470                    + " external=" + onExternal);
16471            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16472            return;
16473        }
16474
16475        // Retrieve PackageSettings and parse package
16476        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16477                | PackageParser.PARSE_ENFORCE_CODE
16478                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16479                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16480                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16481        PackageParser pp = new PackageParser();
16482        pp.setSeparateProcesses(mSeparateProcesses);
16483        pp.setDisplayMetrics(mMetrics);
16484        pp.setCallback(mPackageParserCallback);
16485
16486        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16487        final PackageParser.Package pkg;
16488        try {
16489            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16490            DexMetadataHelper.validatePackageDexMetadata(pkg);
16491        } catch (PackageParserException e) {
16492            res.setError("Failed parse during installPackageLI", e);
16493            return;
16494        } finally {
16495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16496        }
16497
16498        // App targetSdkVersion is below min supported version
16499        if (!forceSdk && pkg.applicationInfo.isTargetingDeprecatedSdkVersion()) {
16500            Slog.w(TAG, "App " + pkg.packageName + " targets deprecated sdk");
16501
16502            res.setError(INSTALL_FAILED_NEWER_SDK,
16503                    "App is targeting deprecated sdk (targetSdkVersion should be at least "
16504                    + Build.VERSION.MIN_SUPPORTED_TARGET_SDK_INT + ").");
16505            return;
16506        }
16507
16508        // Instant apps have several additional install-time checks.
16509        if (instantApp) {
16510            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16511                Slog.w(TAG,
16512                        "Instant app package " + pkg.packageName + " does not target at least O");
16513                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16514                        "Instant app package must target at least O");
16515                return;
16516            }
16517            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16518                Slog.w(TAG, "Instant app package " + pkg.packageName
16519                        + " does not target targetSandboxVersion 2");
16520                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16521                        "Instant app package must use targetSandboxVersion 2");
16522                return;
16523            }
16524            if (pkg.mSharedUserId != null) {
16525                Slog.w(TAG, "Instant app package " + pkg.packageName
16526                        + " may not declare sharedUserId.");
16527                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16528                        "Instant app package may not declare a sharedUserId");
16529                return;
16530            }
16531        }
16532
16533        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16534            // Static shared libraries have synthetic package names
16535            renameStaticSharedLibraryPackage(pkg);
16536
16537            // No static shared libs on external storage
16538            if (onExternal) {
16539                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16540                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16541                        "Packages declaring static-shared libs cannot be updated");
16542                return;
16543            }
16544        }
16545
16546        // If we are installing a clustered package add results for the children
16547        if (pkg.childPackages != null) {
16548            synchronized (mPackages) {
16549                final int childCount = pkg.childPackages.size();
16550                for (int i = 0; i < childCount; i++) {
16551                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16552                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16553                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16554                    childRes.pkg = childPkg;
16555                    childRes.name = childPkg.packageName;
16556                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16557                    if (childPs != null) {
16558                        childRes.origUsers = childPs.queryInstalledUsers(
16559                                sUserManager.getUserIds(), true);
16560                    }
16561                    if ((mPackages.containsKey(childPkg.packageName))) {
16562                        childRes.removedInfo = new PackageRemovedInfo(this);
16563                        childRes.removedInfo.removedPackage = childPkg.packageName;
16564                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16565                    }
16566                    if (res.addedChildPackages == null) {
16567                        res.addedChildPackages = new ArrayMap<>();
16568                    }
16569                    res.addedChildPackages.put(childPkg.packageName, childRes);
16570                }
16571            }
16572        }
16573
16574        // If package doesn't declare API override, mark that we have an install
16575        // time CPU ABI override.
16576        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16577            pkg.cpuAbiOverride = args.abiOverride;
16578        }
16579
16580        String pkgName = res.name = pkg.packageName;
16581        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16582            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16583                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16584                return;
16585            }
16586        }
16587
16588        try {
16589            // either use what we've been given or parse directly from the APK
16590            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16591                pkg.setSigningDetails(args.signingDetails);
16592            } else {
16593                PackageParser.collectCertificates(pkg, parseFlags);
16594            }
16595        } catch (PackageParserException e) {
16596            res.setError("Failed collect during installPackageLI", e);
16597            return;
16598        }
16599
16600        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16601                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16602            Slog.w(TAG, "Instant app package " + pkg.packageName
16603                    + " is not signed with at least APK Signature Scheme v2");
16604            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16605                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16606            return;
16607        }
16608
16609        // Get rid of all references to package scan path via parser.
16610        pp = null;
16611        String oldCodePath = null;
16612        boolean systemApp = false;
16613        synchronized (mPackages) {
16614            // Check if installing already existing package
16615            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16616                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16617                if (pkg.mOriginalPackages != null
16618                        && pkg.mOriginalPackages.contains(oldName)
16619                        && mPackages.containsKey(oldName)) {
16620                    // This package is derived from an original package,
16621                    // and this device has been updating from that original
16622                    // name.  We must continue using the original name, so
16623                    // rename the new package here.
16624                    pkg.setPackageName(oldName);
16625                    pkgName = pkg.packageName;
16626                    replace = true;
16627                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16628                            + oldName + " pkgName=" + pkgName);
16629                } else if (mPackages.containsKey(pkgName)) {
16630                    // This package, under its official name, already exists
16631                    // on the device; we should replace it.
16632                    replace = true;
16633                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16634                }
16635
16636                // Child packages are installed through the parent package
16637                if (pkg.parentPackage != null) {
16638                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16639                            "Package " + pkg.packageName + " is child of package "
16640                                    + pkg.parentPackage.parentPackage + ". Child packages "
16641                                    + "can be updated only through the parent package.");
16642                    return;
16643                }
16644
16645                if (replace) {
16646                    // Prevent apps opting out from runtime permissions
16647                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16648                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16649                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16650                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16651                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16652                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16653                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16654                                        + " doesn't support runtime permissions but the old"
16655                                        + " target SDK " + oldTargetSdk + " does.");
16656                        return;
16657                    }
16658                    // Prevent persistent apps from being updated
16659                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16660                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16661                                "Package " + oldPackage.packageName + " is a persistent app. "
16662                                        + "Persistent apps are not updateable.");
16663                        return;
16664                    }
16665                    // Prevent apps from downgrading their targetSandbox.
16666                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16667                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16668                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16669                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16670                                "Package " + pkg.packageName + " new target sandbox "
16671                                + newTargetSandbox + " is incompatible with the previous value of"
16672                                + oldTargetSandbox + ".");
16673                        return;
16674                    }
16675
16676                    // Prevent installing of child packages
16677                    if (oldPackage.parentPackage != null) {
16678                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16679                                "Package " + pkg.packageName + " is child of package "
16680                                        + oldPackage.parentPackage + ". Child packages "
16681                                        + "can be updated only through the parent package.");
16682                        return;
16683                    }
16684                }
16685            }
16686
16687            PackageSetting ps = mSettings.mPackages.get(pkgName);
16688            if (ps != null) {
16689                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16690
16691                // Static shared libs have same package with different versions where
16692                // we internally use a synthetic package name to allow multiple versions
16693                // of the same package, therefore we need to compare signatures against
16694                // the package setting for the latest library version.
16695                PackageSetting signatureCheckPs = ps;
16696                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16697                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16698                    if (libraryEntry != null) {
16699                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16700                    }
16701                }
16702
16703                // Quick sanity check that we're signed correctly if updating;
16704                // we'll check this again later when scanning, but we want to
16705                // bail early here before tripping over redefined permissions.
16706                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16707                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16708                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16709                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16710                                + pkg.packageName + " upgrade keys do not match the "
16711                                + "previously installed version");
16712                        return;
16713                    }
16714                } else {
16715                    try {
16716                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16717                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16718                        // We don't care about disabledPkgSetting on install for now.
16719                        final boolean compatMatch = verifySignatures(
16720                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16721                                compareRecover);
16722                        // The new KeySets will be re-added later in the scanning process.
16723                        if (compatMatch) {
16724                            synchronized (mPackages) {
16725                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16726                            }
16727                        }
16728                    } catch (PackageManagerException e) {
16729                        res.setError(e.error, e.getMessage());
16730                        return;
16731                    }
16732                }
16733
16734                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16735                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16736                    systemApp = (ps.pkg.applicationInfo.flags &
16737                            ApplicationInfo.FLAG_SYSTEM) != 0;
16738                }
16739                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16740            }
16741
16742            int N = pkg.permissions.size();
16743            for (int i = N-1; i >= 0; i--) {
16744                final PackageParser.Permission perm = pkg.permissions.get(i);
16745                final BasePermission bp =
16746                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16747
16748                // Don't allow anyone but the system to define ephemeral permissions.
16749                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16750                        && !systemApp) {
16751                    Slog.w(TAG, "Non-System package " + pkg.packageName
16752                            + " attempting to delcare ephemeral permission "
16753                            + perm.info.name + "; Removing ephemeral.");
16754                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16755                }
16756
16757                // Check whether the newly-scanned package wants to define an already-defined perm
16758                if (bp != null) {
16759                    // If the defining package is signed with our cert, it's okay.  This
16760                    // also includes the "updating the same package" case, of course.
16761                    // "updating same package" could also involve key-rotation.
16762                    final boolean sigsOk;
16763                    final String sourcePackageName = bp.getSourcePackageName();
16764                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16765                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16766                    if (sourcePackageName.equals(pkg.packageName)
16767                            && (ksms.shouldCheckUpgradeKeySetLocked(
16768                                    sourcePackageSetting, scanFlags))) {
16769                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16770                    } else {
16771                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16772                                pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH;
16773                    }
16774                    if (!sigsOk) {
16775                        // If the owning package is the system itself, we log but allow
16776                        // install to proceed; we fail the install on all other permission
16777                        // redefinitions.
16778                        if (!sourcePackageName.equals("android")) {
16779                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16780                                    + pkg.packageName + " attempting to redeclare permission "
16781                                    + perm.info.name + " already owned by " + sourcePackageName);
16782                            res.origPermission = perm.info.name;
16783                            res.origPackage = sourcePackageName;
16784                            return;
16785                        } else {
16786                            Slog.w(TAG, "Package " + pkg.packageName
16787                                    + " attempting to redeclare system permission "
16788                                    + perm.info.name + "; ignoring new declaration");
16789                            pkg.permissions.remove(i);
16790                        }
16791                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16792                        // Prevent apps to change protection level to dangerous from any other
16793                        // type as this would allow a privilege escalation where an app adds a
16794                        // normal/signature permission in other app's group and later redefines
16795                        // it as dangerous leading to the group auto-grant.
16796                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16797                                == PermissionInfo.PROTECTION_DANGEROUS) {
16798                            if (bp != null && !bp.isRuntime()) {
16799                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16800                                        + "non-runtime permission " + perm.info.name
16801                                        + " to runtime; keeping old protection level");
16802                                perm.info.protectionLevel = bp.getProtectionLevel();
16803                            }
16804                        }
16805                    }
16806                }
16807            }
16808        }
16809
16810        if (systemApp) {
16811            if (onExternal) {
16812                // Abort update; system app can't be replaced with app on sdcard
16813                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16814                        "Cannot install updates to system apps on sdcard");
16815                return;
16816            } else if (instantApp) {
16817                // Abort update; system app can't be replaced with an instant app
16818                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16819                        "Cannot update a system app with an instant app");
16820                return;
16821            }
16822        }
16823
16824        if (args.move != null) {
16825            // We did an in-place move, so dex is ready to roll
16826            scanFlags |= SCAN_NO_DEX;
16827            scanFlags |= SCAN_MOVE;
16828
16829            synchronized (mPackages) {
16830                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16831                if (ps == null) {
16832                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16833                            "Missing settings for moved package " + pkgName);
16834                }
16835
16836                // We moved the entire application as-is, so bring over the
16837                // previously derived ABI information.
16838                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16839                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16840            }
16841
16842        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16843            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16844            scanFlags |= SCAN_NO_DEX;
16845
16846            try {
16847                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16848                    args.abiOverride : pkg.cpuAbiOverride);
16849                final boolean extractNativeLibs = !pkg.isLibrary();
16850                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
16851            } catch (PackageManagerException pme) {
16852                Slog.e(TAG, "Error deriving application ABI", pme);
16853                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16854                return;
16855            }
16856
16857            // Shared libraries for the package need to be updated.
16858            synchronized (mPackages) {
16859                try {
16860                    updateSharedLibrariesLPr(pkg, null);
16861                } catch (PackageManagerException e) {
16862                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16863                }
16864            }
16865        }
16866
16867        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16868            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16869            return;
16870        }
16871
16872        if (!instantApp) {
16873            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16874        } else {
16875            if (DEBUG_DOMAIN_VERIFICATION) {
16876                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16877            }
16878        }
16879
16880        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16881                "installPackageLI")) {
16882            if (replace) {
16883                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16884                    // Static libs have a synthetic package name containing the version
16885                    // and cannot be updated as an update would get a new package name,
16886                    // unless this is the exact same version code which is useful for
16887                    // development.
16888                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16889                    if (existingPkg != null &&
16890                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
16891                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16892                                + "static-shared libs cannot be updated");
16893                        return;
16894                    }
16895                }
16896                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16897                        installerPackageName, res, args.installReason);
16898            } else {
16899                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16900                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16901            }
16902        }
16903
16904        // Prepare the application profiles for the new code paths.
16905        // This needs to be done before invoking dexopt so that any install-time profile
16906        // can be used for optimizations.
16907        mArtManagerService.prepareAppProfiles(pkg, args.user.getIdentifier());
16908
16909        // Check whether we need to dexopt the app.
16910        //
16911        // NOTE: it is IMPORTANT to call dexopt:
16912        //   - after doRename which will sync the package data from PackageParser.Package and its
16913        //     corresponding ApplicationInfo.
16914        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
16915        //     uid of the application (pkg.applicationInfo.uid).
16916        //     This update happens in place!
16917        //
16918        // We only need to dexopt if the package meets ALL of the following conditions:
16919        //   1) it is not forward locked.
16920        //   2) it is not on on an external ASEC container.
16921        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16922        //
16923        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16924        // complete, so we skip this step during installation. Instead, we'll take extra time
16925        // the first time the instant app starts. It's preferred to do it this way to provide
16926        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16927        // middle of running an instant app. The default behaviour can be overridden
16928        // via gservices.
16929        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
16930                && !forwardLocked
16931                && !pkg.applicationInfo.isExternalAsec()
16932                && (!instantApp || Global.getInt(mContext.getContentResolver(),
16933                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16934
16935        if (performDexopt) {
16936            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16937            // Do not run PackageDexOptimizer through the local performDexOpt
16938            // method because `pkg` may not be in `mPackages` yet.
16939            //
16940            // Also, don't fail application installs if the dexopt step fails.
16941            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16942                    REASON_INSTALL,
16943                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
16944            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16945                    null /* instructionSets */,
16946                    getOrCreateCompilerPackageStats(pkg),
16947                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16948                    dexoptOptions);
16949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16950        }
16951
16952        // Notify BackgroundDexOptService that the package has been changed.
16953        // If this is an update of a package which used to fail to compile,
16954        // BackgroundDexOptService will remove it from its blacklist.
16955        // TODO: Layering violation
16956        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16957
16958        synchronized (mPackages) {
16959            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16960            if (ps != null) {
16961                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16962                ps.setUpdateAvailable(false /*updateAvailable*/);
16963            }
16964
16965            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16966            for (int i = 0; i < childCount; i++) {
16967                PackageParser.Package childPkg = pkg.childPackages.get(i);
16968                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16969                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16970                if (childPs != null) {
16971                    childRes.newUsers = childPs.queryInstalledUsers(
16972                            sUserManager.getUserIds(), true);
16973                }
16974            }
16975
16976            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16977                updateSequenceNumberLP(ps, res.newUsers);
16978                updateInstantAppInstallerLocked(pkgName);
16979            }
16980        }
16981    }
16982
16983    private void startIntentFilterVerifications(int userId, boolean replacing,
16984            PackageParser.Package pkg) {
16985        if (mIntentFilterVerifierComponent == null) {
16986            Slog.w(TAG, "No IntentFilter verification will not be done as "
16987                    + "there is no IntentFilterVerifier available!");
16988            return;
16989        }
16990
16991        final int verifierUid = getPackageUid(
16992                mIntentFilterVerifierComponent.getPackageName(),
16993                MATCH_DEBUG_TRIAGED_MISSING,
16994                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16995
16996        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16997        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16998        mHandler.sendMessage(msg);
16999
17000        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17001        for (int i = 0; i < childCount; i++) {
17002            PackageParser.Package childPkg = pkg.childPackages.get(i);
17003            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17004            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17005            mHandler.sendMessage(msg);
17006        }
17007    }
17008
17009    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17010            PackageParser.Package pkg) {
17011        int size = pkg.activities.size();
17012        if (size == 0) {
17013            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17014                    "No activity, so no need to verify any IntentFilter!");
17015            return;
17016        }
17017
17018        final boolean hasDomainURLs = hasDomainURLs(pkg);
17019        if (!hasDomainURLs) {
17020            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17021                    "No domain URLs, so no need to verify any IntentFilter!");
17022            return;
17023        }
17024
17025        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17026                + " if any IntentFilter from the " + size
17027                + " Activities needs verification ...");
17028
17029        int count = 0;
17030        final String packageName = pkg.packageName;
17031
17032        synchronized (mPackages) {
17033            // If this is a new install and we see that we've already run verification for this
17034            // package, we have nothing to do: it means the state was restored from backup.
17035            if (!replacing) {
17036                IntentFilterVerificationInfo ivi =
17037                        mSettings.getIntentFilterVerificationLPr(packageName);
17038                if (ivi != null) {
17039                    if (DEBUG_DOMAIN_VERIFICATION) {
17040                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17041                                + ivi.getStatusString());
17042                    }
17043                    return;
17044                }
17045            }
17046
17047            // If any filters need to be verified, then all need to be.
17048            boolean needToVerify = false;
17049            for (PackageParser.Activity a : pkg.activities) {
17050                for (ActivityIntentInfo filter : a.intents) {
17051                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17052                        if (DEBUG_DOMAIN_VERIFICATION) {
17053                            Slog.d(TAG,
17054                                    "Intent filter needs verification, so processing all filters");
17055                        }
17056                        needToVerify = true;
17057                        break;
17058                    }
17059                }
17060            }
17061
17062            if (needToVerify) {
17063                final int verificationId = mIntentFilterVerificationToken++;
17064                for (PackageParser.Activity a : pkg.activities) {
17065                    for (ActivityIntentInfo filter : a.intents) {
17066                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17067                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17068                                    "Verification needed for IntentFilter:" + filter.toString());
17069                            mIntentFilterVerifier.addOneIntentFilterVerification(
17070                                    verifierUid, userId, verificationId, filter, packageName);
17071                            count++;
17072                        }
17073                    }
17074                }
17075            }
17076        }
17077
17078        if (count > 0) {
17079            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17080                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17081                    +  " for userId:" + userId);
17082            mIntentFilterVerifier.startVerifications(userId);
17083        } else {
17084            if (DEBUG_DOMAIN_VERIFICATION) {
17085                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17086            }
17087        }
17088    }
17089
17090    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17091        final ComponentName cn  = filter.activity.getComponentName();
17092        final String packageName = cn.getPackageName();
17093
17094        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17095                packageName);
17096        if (ivi == null) {
17097            return true;
17098        }
17099        int status = ivi.getStatus();
17100        switch (status) {
17101            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17102            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17103                return true;
17104
17105            default:
17106                // Nothing to do
17107                return false;
17108        }
17109    }
17110
17111    private static boolean isMultiArch(ApplicationInfo info) {
17112        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17113    }
17114
17115    private static boolean isExternal(PackageParser.Package pkg) {
17116        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17117    }
17118
17119    private static boolean isExternal(PackageSetting ps) {
17120        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17121    }
17122
17123    private static boolean isSystemApp(PackageParser.Package pkg) {
17124        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17125    }
17126
17127    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17128        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17129    }
17130
17131    private static boolean isOemApp(PackageParser.Package pkg) {
17132        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17133    }
17134
17135    private static boolean isVendorApp(PackageParser.Package pkg) {
17136        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17137    }
17138
17139    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17140        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17141    }
17142
17143    private static boolean isSystemApp(PackageSetting ps) {
17144        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17145    }
17146
17147    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17148        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17149    }
17150
17151    private int packageFlagsToInstallFlags(PackageSetting ps) {
17152        int installFlags = 0;
17153        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17154            // This existing package was an external ASEC install when we have
17155            // the external flag without a UUID
17156            installFlags |= PackageManager.INSTALL_EXTERNAL;
17157        }
17158        if (ps.isForwardLocked()) {
17159            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17160        }
17161        return installFlags;
17162    }
17163
17164    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17165        if (isExternal(pkg)) {
17166            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17167                return mSettings.getExternalVersion();
17168            } else {
17169                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17170            }
17171        } else {
17172            return mSettings.getInternalVersion();
17173        }
17174    }
17175
17176    private void deleteTempPackageFiles() {
17177        final FilenameFilter filter = new FilenameFilter() {
17178            public boolean accept(File dir, String name) {
17179                return name.startsWith("vmdl") && name.endsWith(".tmp");
17180            }
17181        };
17182        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17183            file.delete();
17184        }
17185    }
17186
17187    @Override
17188    public void deletePackageAsUser(String packageName, int versionCode,
17189            IPackageDeleteObserver observer, int userId, int flags) {
17190        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17191                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17192    }
17193
17194    @Override
17195    public void deletePackageVersioned(VersionedPackage versionedPackage,
17196            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17197        final int callingUid = Binder.getCallingUid();
17198        mContext.enforceCallingOrSelfPermission(
17199                android.Manifest.permission.DELETE_PACKAGES, null);
17200        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17201        Preconditions.checkNotNull(versionedPackage);
17202        Preconditions.checkNotNull(observer);
17203        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17204                PackageManager.VERSION_CODE_HIGHEST,
17205                Long.MAX_VALUE, "versionCode must be >= -1");
17206
17207        final String packageName = versionedPackage.getPackageName();
17208        final long versionCode = versionedPackage.getLongVersionCode();
17209        final String internalPackageName;
17210        synchronized (mPackages) {
17211            // Normalize package name to handle renamed packages and static libs
17212            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17213        }
17214
17215        final int uid = Binder.getCallingUid();
17216        if (!isOrphaned(internalPackageName)
17217                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17218            try {
17219                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17220                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17221                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17222                observer.onUserActionRequired(intent);
17223            } catch (RemoteException re) {
17224            }
17225            return;
17226        }
17227        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17228        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17229        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17230            mContext.enforceCallingOrSelfPermission(
17231                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17232                    "deletePackage for user " + userId);
17233        }
17234
17235        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17236            try {
17237                observer.onPackageDeleted(packageName,
17238                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17239            } catch (RemoteException re) {
17240            }
17241            return;
17242        }
17243
17244        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17245            try {
17246                observer.onPackageDeleted(packageName,
17247                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17248            } catch (RemoteException re) {
17249            }
17250            return;
17251        }
17252
17253        if (DEBUG_REMOVE) {
17254            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17255                    + " deleteAllUsers: " + deleteAllUsers + " version="
17256                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17257                    ? "VERSION_CODE_HIGHEST" : versionCode));
17258        }
17259        // Queue up an async operation since the package deletion may take a little while.
17260        mHandler.post(new Runnable() {
17261            public void run() {
17262                mHandler.removeCallbacks(this);
17263                int returnCode;
17264                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17265                boolean doDeletePackage = true;
17266                if (ps != null) {
17267                    final boolean targetIsInstantApp =
17268                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17269                    doDeletePackage = !targetIsInstantApp
17270                            || canViewInstantApps;
17271                }
17272                if (doDeletePackage) {
17273                    if (!deleteAllUsers) {
17274                        returnCode = deletePackageX(internalPackageName, versionCode,
17275                                userId, deleteFlags);
17276                    } else {
17277                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17278                                internalPackageName, users);
17279                        // If nobody is blocking uninstall, proceed with delete for all users
17280                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17281                            returnCode = deletePackageX(internalPackageName, versionCode,
17282                                    userId, deleteFlags);
17283                        } else {
17284                            // Otherwise uninstall individually for users with blockUninstalls=false
17285                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17286                            for (int userId : users) {
17287                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17288                                    returnCode = deletePackageX(internalPackageName, versionCode,
17289                                            userId, userFlags);
17290                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17291                                        Slog.w(TAG, "Package delete failed for user " + userId
17292                                                + ", returnCode " + returnCode);
17293                                    }
17294                                }
17295                            }
17296                            // The app has only been marked uninstalled for certain users.
17297                            // We still need to report that delete was blocked
17298                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17299                        }
17300                    }
17301                } else {
17302                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17303                }
17304                try {
17305                    observer.onPackageDeleted(packageName, returnCode, null);
17306                } catch (RemoteException e) {
17307                    Log.i(TAG, "Observer no longer exists.");
17308                } //end catch
17309            } //end run
17310        });
17311    }
17312
17313    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17314        if (pkg.staticSharedLibName != null) {
17315            return pkg.manifestPackageName;
17316        }
17317        return pkg.packageName;
17318    }
17319
17320    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17321        // Handle renamed packages
17322        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17323        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17324
17325        // Is this a static library?
17326        LongSparseArray<SharedLibraryEntry> versionedLib =
17327                mStaticLibsByDeclaringPackage.get(packageName);
17328        if (versionedLib == null || versionedLib.size() <= 0) {
17329            return packageName;
17330        }
17331
17332        // Figure out which lib versions the caller can see
17333        LongSparseLongArray versionsCallerCanSee = null;
17334        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17335        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17336                && callingAppId != Process.ROOT_UID) {
17337            versionsCallerCanSee = new LongSparseLongArray();
17338            String libName = versionedLib.valueAt(0).info.getName();
17339            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17340            if (uidPackages != null) {
17341                for (String uidPackage : uidPackages) {
17342                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17343                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17344                    if (libIdx >= 0) {
17345                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17346                        versionsCallerCanSee.append(libVersion, libVersion);
17347                    }
17348                }
17349            }
17350        }
17351
17352        // Caller can see nothing - done
17353        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17354            return packageName;
17355        }
17356
17357        // Find the version the caller can see and the app version code
17358        SharedLibraryEntry highestVersion = null;
17359        final int versionCount = versionedLib.size();
17360        for (int i = 0; i < versionCount; i++) {
17361            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17362            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17363                    libEntry.info.getLongVersion()) < 0) {
17364                continue;
17365            }
17366            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17367            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17368                if (libVersionCode == versionCode) {
17369                    return libEntry.apk;
17370                }
17371            } else if (highestVersion == null) {
17372                highestVersion = libEntry;
17373            } else if (libVersionCode  > highestVersion.info
17374                    .getDeclaringPackage().getLongVersionCode()) {
17375                highestVersion = libEntry;
17376            }
17377        }
17378
17379        if (highestVersion != null) {
17380            return highestVersion.apk;
17381        }
17382
17383        return packageName;
17384    }
17385
17386    boolean isCallerVerifier(int callingUid) {
17387        final int callingUserId = UserHandle.getUserId(callingUid);
17388        return mRequiredVerifierPackage != null &&
17389                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17390    }
17391
17392    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17393        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17394              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17395            return true;
17396        }
17397        final int callingUserId = UserHandle.getUserId(callingUid);
17398        // If the caller installed the pkgName, then allow it to silently uninstall.
17399        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17400            return true;
17401        }
17402
17403        // Allow package verifier to silently uninstall.
17404        if (mRequiredVerifierPackage != null &&
17405                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17406            return true;
17407        }
17408
17409        // Allow package uninstaller to silently uninstall.
17410        if (mRequiredUninstallerPackage != null &&
17411                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17412            return true;
17413        }
17414
17415        // Allow storage manager to silently uninstall.
17416        if (mStorageManagerPackage != null &&
17417                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17418            return true;
17419        }
17420
17421        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17422        // uninstall for device owner provisioning.
17423        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17424                == PERMISSION_GRANTED) {
17425            return true;
17426        }
17427
17428        return false;
17429    }
17430
17431    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17432        int[] result = EMPTY_INT_ARRAY;
17433        for (int userId : userIds) {
17434            if (getBlockUninstallForUser(packageName, userId)) {
17435                result = ArrayUtils.appendInt(result, userId);
17436            }
17437        }
17438        return result;
17439    }
17440
17441    @Override
17442    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17443        final int callingUid = Binder.getCallingUid();
17444        if (getInstantAppPackageName(callingUid) != null
17445                && !isCallerSameApp(packageName, callingUid)) {
17446            return false;
17447        }
17448        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17449    }
17450
17451    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17452        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17453                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17454        try {
17455            if (dpm != null) {
17456                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17457                        /* callingUserOnly =*/ false);
17458                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17459                        : deviceOwnerComponentName.getPackageName();
17460                // Does the package contains the device owner?
17461                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17462                // this check is probably not needed, since DO should be registered as a device
17463                // admin on some user too. (Original bug for this: b/17657954)
17464                if (packageName.equals(deviceOwnerPackageName)) {
17465                    return true;
17466                }
17467                // Does it contain a device admin for any user?
17468                int[] users;
17469                if (userId == UserHandle.USER_ALL) {
17470                    users = sUserManager.getUserIds();
17471                } else {
17472                    users = new int[]{userId};
17473                }
17474                for (int i = 0; i < users.length; ++i) {
17475                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17476                        return true;
17477                    }
17478                }
17479            }
17480        } catch (RemoteException e) {
17481        }
17482        return false;
17483    }
17484
17485    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17486        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17487    }
17488
17489    /**
17490     *  This method is an internal method that could be get invoked either
17491     *  to delete an installed package or to clean up a failed installation.
17492     *  After deleting an installed package, a broadcast is sent to notify any
17493     *  listeners that the package has been removed. For cleaning up a failed
17494     *  installation, the broadcast is not necessary since the package's
17495     *  installation wouldn't have sent the initial broadcast either
17496     *  The key steps in deleting a package are
17497     *  deleting the package information in internal structures like mPackages,
17498     *  deleting the packages base directories through installd
17499     *  updating mSettings to reflect current status
17500     *  persisting settings for later use
17501     *  sending a broadcast if necessary
17502     */
17503    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17504        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17505        final boolean res;
17506
17507        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17508                ? UserHandle.USER_ALL : userId;
17509
17510        if (isPackageDeviceAdmin(packageName, removeUser)) {
17511            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17512            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17513        }
17514
17515        PackageSetting uninstalledPs = null;
17516        PackageParser.Package pkg = null;
17517
17518        // for the uninstall-updates case and restricted profiles, remember the per-
17519        // user handle installed state
17520        int[] allUsers;
17521        synchronized (mPackages) {
17522            uninstalledPs = mSettings.mPackages.get(packageName);
17523            if (uninstalledPs == null) {
17524                Slog.w(TAG, "Not removing non-existent package " + packageName);
17525                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17526            }
17527
17528            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17529                    && uninstalledPs.versionCode != versionCode) {
17530                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17531                        + uninstalledPs.versionCode + " != " + versionCode);
17532                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17533            }
17534
17535            // Static shared libs can be declared by any package, so let us not
17536            // allow removing a package if it provides a lib others depend on.
17537            pkg = mPackages.get(packageName);
17538
17539            allUsers = sUserManager.getUserIds();
17540
17541            if (pkg != null && pkg.staticSharedLibName != null) {
17542                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17543                        pkg.staticSharedLibVersion);
17544                if (libEntry != null) {
17545                    for (int currUserId : allUsers) {
17546                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17547                            continue;
17548                        }
17549                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17550                                libEntry.info, 0, currUserId);
17551                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17552                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17553                                    + " hosting lib " + libEntry.info.getName() + " version "
17554                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17555                                    + " for user " + currUserId);
17556                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17557                        }
17558                    }
17559                }
17560            }
17561
17562            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17563        }
17564
17565        final int freezeUser;
17566        if (isUpdatedSystemApp(uninstalledPs)
17567                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17568            // We're downgrading a system app, which will apply to all users, so
17569            // freeze them all during the downgrade
17570            freezeUser = UserHandle.USER_ALL;
17571        } else {
17572            freezeUser = removeUser;
17573        }
17574
17575        synchronized (mInstallLock) {
17576            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17577            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17578                    deleteFlags, "deletePackageX")) {
17579                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17580                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17581            }
17582            synchronized (mPackages) {
17583                if (res) {
17584                    if (pkg != null) {
17585                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17586                    }
17587                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17588                    updateInstantAppInstallerLocked(packageName);
17589                }
17590            }
17591        }
17592
17593        if (res) {
17594            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17595            info.sendPackageRemovedBroadcasts(killApp);
17596            info.sendSystemPackageUpdatedBroadcasts();
17597            info.sendSystemPackageAppearedBroadcasts();
17598        }
17599        // Force a gc here.
17600        Runtime.getRuntime().gc();
17601        // Delete the resources here after sending the broadcast to let
17602        // other processes clean up before deleting resources.
17603        if (info.args != null) {
17604            synchronized (mInstallLock) {
17605                info.args.doPostDeleteLI(true);
17606            }
17607        }
17608
17609        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17610    }
17611
17612    static class PackageRemovedInfo {
17613        final PackageSender packageSender;
17614        String removedPackage;
17615        String installerPackageName;
17616        int uid = -1;
17617        int removedAppId = -1;
17618        int[] origUsers;
17619        int[] removedUsers = null;
17620        int[] broadcastUsers = null;
17621        int[] instantUserIds = null;
17622        SparseArray<Integer> installReasons;
17623        boolean isRemovedPackageSystemUpdate = false;
17624        boolean isUpdate;
17625        boolean dataRemoved;
17626        boolean removedForAllUsers;
17627        boolean isStaticSharedLib;
17628        // Clean up resources deleted packages.
17629        InstallArgs args = null;
17630        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17631        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17632
17633        PackageRemovedInfo(PackageSender packageSender) {
17634            this.packageSender = packageSender;
17635        }
17636
17637        void sendPackageRemovedBroadcasts(boolean killApp) {
17638            sendPackageRemovedBroadcastInternal(killApp);
17639            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17640            for (int i = 0; i < childCount; i++) {
17641                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17642                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17643            }
17644        }
17645
17646        void sendSystemPackageUpdatedBroadcasts() {
17647            if (isRemovedPackageSystemUpdate) {
17648                sendSystemPackageUpdatedBroadcastsInternal();
17649                final int childCount = (removedChildPackages != null)
17650                        ? removedChildPackages.size() : 0;
17651                for (int i = 0; i < childCount; i++) {
17652                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17653                    if (childInfo.isRemovedPackageSystemUpdate) {
17654                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17655                    }
17656                }
17657            }
17658        }
17659
17660        void sendSystemPackageAppearedBroadcasts() {
17661            final int packageCount = (appearedChildPackages != null)
17662                    ? appearedChildPackages.size() : 0;
17663            for (int i = 0; i < packageCount; i++) {
17664                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17665                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17666                    true /*sendBootCompleted*/, false /*startReceiver*/,
17667                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17668            }
17669        }
17670
17671        private void sendSystemPackageUpdatedBroadcastsInternal() {
17672            Bundle extras = new Bundle(2);
17673            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17674            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17675            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17676                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17677            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17678                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17679            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17680                null, null, 0, removedPackage, null, null, null);
17681            if (installerPackageName != null) {
17682                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17683                        removedPackage, extras, 0 /*flags*/,
17684                        installerPackageName, null, null, null);
17685                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17686                        removedPackage, extras, 0 /*flags*/,
17687                        installerPackageName, null, null, null);
17688            }
17689        }
17690
17691        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17692            // Don't send static shared library removal broadcasts as these
17693            // libs are visible only the the apps that depend on them an one
17694            // cannot remove the library if it has a dependency.
17695            if (isStaticSharedLib) {
17696                return;
17697            }
17698            Bundle extras = new Bundle(2);
17699            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17700            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17701            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17702            if (isUpdate || isRemovedPackageSystemUpdate) {
17703                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17704            }
17705            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17706            if (removedPackage != null) {
17707                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17708                    removedPackage, extras, 0, null /*targetPackage*/, null,
17709                    broadcastUsers, instantUserIds);
17710                if (installerPackageName != null) {
17711                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17712                            removedPackage, extras, 0 /*flags*/,
17713                            installerPackageName, null, broadcastUsers, instantUserIds);
17714                }
17715                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17716                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17717                        removedPackage, extras,
17718                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17719                        null, null, broadcastUsers, instantUserIds);
17720                    packageSender.notifyPackageRemoved(removedPackage);
17721                }
17722            }
17723            if (removedAppId >= 0) {
17724                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17725                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17726                    null, null, broadcastUsers, instantUserIds);
17727            }
17728        }
17729
17730        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17731            removedUsers = userIds;
17732            if (removedUsers == null) {
17733                broadcastUsers = null;
17734                return;
17735            }
17736
17737            broadcastUsers = EMPTY_INT_ARRAY;
17738            instantUserIds = EMPTY_INT_ARRAY;
17739            for (int i = userIds.length - 1; i >= 0; --i) {
17740                final int userId = userIds[i];
17741                if (deletedPackageSetting.getInstantApp(userId)) {
17742                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
17743                } else {
17744                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17745                }
17746            }
17747        }
17748    }
17749
17750    /*
17751     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17752     * flag is not set, the data directory is removed as well.
17753     * make sure this flag is set for partially installed apps. If not its meaningless to
17754     * delete a partially installed application.
17755     */
17756    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17757            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17758        String packageName = ps.name;
17759        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17760        // Retrieve object to delete permissions for shared user later on
17761        final PackageParser.Package deletedPkg;
17762        final PackageSetting deletedPs;
17763        // reader
17764        synchronized (mPackages) {
17765            deletedPkg = mPackages.get(packageName);
17766            deletedPs = mSettings.mPackages.get(packageName);
17767            if (outInfo != null) {
17768                outInfo.removedPackage = packageName;
17769                outInfo.installerPackageName = ps.installerPackageName;
17770                outInfo.isStaticSharedLib = deletedPkg != null
17771                        && deletedPkg.staticSharedLibName != null;
17772                outInfo.populateUsers(deletedPs == null ? null
17773                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17774            }
17775        }
17776
17777        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17778
17779        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17780            final PackageParser.Package resolvedPkg;
17781            if (deletedPkg != null) {
17782                resolvedPkg = deletedPkg;
17783            } else {
17784                // We don't have a parsed package when it lives on an ejected
17785                // adopted storage device, so fake something together
17786                resolvedPkg = new PackageParser.Package(ps.name);
17787                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17788            }
17789            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17790                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17791            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17792            if (outInfo != null) {
17793                outInfo.dataRemoved = true;
17794            }
17795            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17796        }
17797
17798        int removedAppId = -1;
17799
17800        // writer
17801        synchronized (mPackages) {
17802            boolean installedStateChanged = false;
17803            if (deletedPs != null) {
17804                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17805                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17806                    clearDefaultBrowserIfNeeded(packageName);
17807                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17808                    removedAppId = mSettings.removePackageLPw(packageName);
17809                    if (outInfo != null) {
17810                        outInfo.removedAppId = removedAppId;
17811                    }
17812                    mPermissionManager.updatePermissions(
17813                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17814                    if (deletedPs.sharedUser != null) {
17815                        // Remove permissions associated with package. Since runtime
17816                        // permissions are per user we have to kill the removed package
17817                        // or packages running under the shared user of the removed
17818                        // package if revoking the permissions requested only by the removed
17819                        // package is successful and this causes a change in gids.
17820                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17821                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17822                                    userId);
17823                            if (userIdToKill == UserHandle.USER_ALL
17824                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17825                                // If gids changed for this user, kill all affected packages.
17826                                mHandler.post(new Runnable() {
17827                                    @Override
17828                                    public void run() {
17829                                        // This has to happen with no lock held.
17830                                        killApplication(deletedPs.name, deletedPs.appId,
17831                                                KILL_APP_REASON_GIDS_CHANGED);
17832                                    }
17833                                });
17834                                break;
17835                            }
17836                        }
17837                    }
17838                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17839                }
17840                // make sure to preserve per-user disabled state if this removal was just
17841                // a downgrade of a system app to the factory package
17842                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17843                    if (DEBUG_REMOVE) {
17844                        Slog.d(TAG, "Propagating install state across downgrade");
17845                    }
17846                    for (int userId : allUserHandles) {
17847                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17848                        if (DEBUG_REMOVE) {
17849                            Slog.d(TAG, "    user " + userId + " => " + installed);
17850                        }
17851                        if (installed != ps.getInstalled(userId)) {
17852                            installedStateChanged = true;
17853                        }
17854                        ps.setInstalled(installed, userId);
17855                    }
17856                }
17857            }
17858            // can downgrade to reader
17859            if (writeSettings) {
17860                // Save settings now
17861                mSettings.writeLPr();
17862            }
17863            if (installedStateChanged) {
17864                mSettings.writeKernelMappingLPr(ps);
17865            }
17866        }
17867        if (removedAppId != -1) {
17868            // A user ID was deleted here. Go through all users and remove it
17869            // from KeyStore.
17870            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17871        }
17872    }
17873
17874    static boolean locationIsPrivileged(String path) {
17875        try {
17876            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17877            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
17878            return path.startsWith(privilegedAppDir.getCanonicalPath())
17879                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath());
17880        } catch (IOException e) {
17881            Slog.e(TAG, "Unable to access code path " + path);
17882        }
17883        return false;
17884    }
17885
17886    static boolean locationIsOem(String path) {
17887        try {
17888            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
17889        } catch (IOException e) {
17890            Slog.e(TAG, "Unable to access code path " + path);
17891        }
17892        return false;
17893    }
17894
17895    static boolean locationIsVendor(String path) {
17896        try {
17897            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
17898        } catch (IOException e) {
17899            Slog.e(TAG, "Unable to access code path " + path);
17900        }
17901        return false;
17902    }
17903
17904    /*
17905     * Tries to delete system package.
17906     */
17907    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17908            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17909            boolean writeSettings) {
17910        if (deletedPs.parentPackageName != null) {
17911            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17912            return false;
17913        }
17914
17915        final boolean applyUserRestrictions
17916                = (allUserHandles != null) && (outInfo.origUsers != null);
17917        final PackageSetting disabledPs;
17918        // Confirm if the system package has been updated
17919        // An updated system app can be deleted. This will also have to restore
17920        // the system pkg from system partition
17921        // reader
17922        synchronized (mPackages) {
17923            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17924        }
17925
17926        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17927                + " disabledPs=" + disabledPs);
17928
17929        if (disabledPs == null) {
17930            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17931            return false;
17932        } else if (DEBUG_REMOVE) {
17933            Slog.d(TAG, "Deleting system pkg from data partition");
17934        }
17935
17936        if (DEBUG_REMOVE) {
17937            if (applyUserRestrictions) {
17938                Slog.d(TAG, "Remembering install states:");
17939                for (int userId : allUserHandles) {
17940                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17941                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17942                }
17943            }
17944        }
17945
17946        // Delete the updated package
17947        outInfo.isRemovedPackageSystemUpdate = true;
17948        if (outInfo.removedChildPackages != null) {
17949            final int childCount = (deletedPs.childPackageNames != null)
17950                    ? deletedPs.childPackageNames.size() : 0;
17951            for (int i = 0; i < childCount; i++) {
17952                String childPackageName = deletedPs.childPackageNames.get(i);
17953                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17954                        .contains(childPackageName)) {
17955                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17956                            childPackageName);
17957                    if (childInfo != null) {
17958                        childInfo.isRemovedPackageSystemUpdate = true;
17959                    }
17960                }
17961            }
17962        }
17963
17964        if (disabledPs.versionCode < deletedPs.versionCode) {
17965            // Delete data for downgrades
17966            flags &= ~PackageManager.DELETE_KEEP_DATA;
17967        } else {
17968            // Preserve data by setting flag
17969            flags |= PackageManager.DELETE_KEEP_DATA;
17970        }
17971
17972        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17973                outInfo, writeSettings, disabledPs.pkg);
17974        if (!ret) {
17975            return false;
17976        }
17977
17978        // writer
17979        synchronized (mPackages) {
17980            // NOTE: The system package always needs to be enabled; even if it's for
17981            // a compressed stub. If we don't, installing the system package fails
17982            // during scan [scanning checks the disabled packages]. We will reverse
17983            // this later, after we've "installed" the stub.
17984            // Reinstate the old system package
17985            enableSystemPackageLPw(disabledPs.pkg);
17986            // Remove any native libraries from the upgraded package.
17987            removeNativeBinariesLI(deletedPs);
17988        }
17989
17990        // Install the system package
17991        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17992        try {
17993            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
17994                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17995        } catch (PackageManagerException e) {
17996            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17997                    + e.getMessage());
17998            return false;
17999        } finally {
18000            if (disabledPs.pkg.isStub) {
18001                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18002            }
18003        }
18004        return true;
18005    }
18006
18007    /**
18008     * Installs a package that's already on the system partition.
18009     */
18010    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18011            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18012            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18013                    throws PackageManagerException {
18014        @ParseFlags int parseFlags =
18015                mDefParseFlags
18016                | PackageParser.PARSE_MUST_BE_APK
18017                | PackageParser.PARSE_IS_SYSTEM_DIR;
18018        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18019        if (isPrivileged || locationIsPrivileged(codePathString)) {
18020            scanFlags |= SCAN_AS_PRIVILEGED;
18021        }
18022        if (locationIsOem(codePathString)) {
18023            scanFlags |= SCAN_AS_OEM;
18024        }
18025        if (locationIsVendor(codePathString)) {
18026            scanFlags |= SCAN_AS_VENDOR;
18027        }
18028
18029        final File codePath = new File(codePathString);
18030        final PackageParser.Package pkg =
18031                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18032
18033        try {
18034            // update shared libraries for the newly re-installed system package
18035            updateSharedLibrariesLPr(pkg, null);
18036        } catch (PackageManagerException e) {
18037            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18038        }
18039
18040        prepareAppDataAfterInstallLIF(pkg);
18041
18042        // writer
18043        synchronized (mPackages) {
18044            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18045
18046            // Propagate the permissions state as we do not want to drop on the floor
18047            // runtime permissions. The update permissions method below will take
18048            // care of removing obsolete permissions and grant install permissions.
18049            if (origPermissionState != null) {
18050                ps.getPermissionsState().copyFrom(origPermissionState);
18051            }
18052            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18053                    mPermissionCallback);
18054
18055            final boolean applyUserRestrictions
18056                    = (allUserHandles != null) && (origUserHandles != null);
18057            if (applyUserRestrictions) {
18058                boolean installedStateChanged = false;
18059                if (DEBUG_REMOVE) {
18060                    Slog.d(TAG, "Propagating install state across reinstall");
18061                }
18062                for (int userId : allUserHandles) {
18063                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18064                    if (DEBUG_REMOVE) {
18065                        Slog.d(TAG, "    user " + userId + " => " + installed);
18066                    }
18067                    if (installed != ps.getInstalled(userId)) {
18068                        installedStateChanged = true;
18069                    }
18070                    ps.setInstalled(installed, userId);
18071
18072                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18073                }
18074                // Regardless of writeSettings we need to ensure that this restriction
18075                // state propagation is persisted
18076                mSettings.writeAllUsersPackageRestrictionsLPr();
18077                if (installedStateChanged) {
18078                    mSettings.writeKernelMappingLPr(ps);
18079                }
18080            }
18081            // can downgrade to reader here
18082            if (writeSettings) {
18083                mSettings.writeLPr();
18084            }
18085        }
18086        return pkg;
18087    }
18088
18089    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18090            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18091            PackageRemovedInfo outInfo, boolean writeSettings,
18092            PackageParser.Package replacingPackage) {
18093        synchronized (mPackages) {
18094            if (outInfo != null) {
18095                outInfo.uid = ps.appId;
18096            }
18097
18098            if (outInfo != null && outInfo.removedChildPackages != null) {
18099                final int childCount = (ps.childPackageNames != null)
18100                        ? ps.childPackageNames.size() : 0;
18101                for (int i = 0; i < childCount; i++) {
18102                    String childPackageName = ps.childPackageNames.get(i);
18103                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18104                    if (childPs == null) {
18105                        return false;
18106                    }
18107                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18108                            childPackageName);
18109                    if (childInfo != null) {
18110                        childInfo.uid = childPs.appId;
18111                    }
18112                }
18113            }
18114        }
18115
18116        // Delete package data from internal structures and also remove data if flag is set
18117        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18118
18119        // Delete the child packages data
18120        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18121        for (int i = 0; i < childCount; i++) {
18122            PackageSetting childPs;
18123            synchronized (mPackages) {
18124                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18125            }
18126            if (childPs != null) {
18127                PackageRemovedInfo childOutInfo = (outInfo != null
18128                        && outInfo.removedChildPackages != null)
18129                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18130                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18131                        && (replacingPackage != null
18132                        && !replacingPackage.hasChildPackage(childPs.name))
18133                        ? flags & ~DELETE_KEEP_DATA : flags;
18134                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18135                        deleteFlags, writeSettings);
18136            }
18137        }
18138
18139        // Delete application code and resources only for parent packages
18140        if (ps.parentPackageName == null) {
18141            if (deleteCodeAndResources && (outInfo != null)) {
18142                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18143                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18144                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18145            }
18146        }
18147
18148        return true;
18149    }
18150
18151    @Override
18152    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18153            int userId) {
18154        mContext.enforceCallingOrSelfPermission(
18155                android.Manifest.permission.DELETE_PACKAGES, null);
18156        synchronized (mPackages) {
18157            // Cannot block uninstall of static shared libs as they are
18158            // considered a part of the using app (emulating static linking).
18159            // Also static libs are installed always on internal storage.
18160            PackageParser.Package pkg = mPackages.get(packageName);
18161            if (pkg != null && pkg.staticSharedLibName != null) {
18162                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18163                        + " providing static shared library: " + pkg.staticSharedLibName);
18164                return false;
18165            }
18166            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18167            mSettings.writePackageRestrictionsLPr(userId);
18168        }
18169        return true;
18170    }
18171
18172    @Override
18173    public boolean getBlockUninstallForUser(String packageName, int userId) {
18174        synchronized (mPackages) {
18175            final PackageSetting ps = mSettings.mPackages.get(packageName);
18176            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18177                return false;
18178            }
18179            return mSettings.getBlockUninstallLPr(userId, packageName);
18180        }
18181    }
18182
18183    @Override
18184    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18185        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18186        synchronized (mPackages) {
18187            PackageSetting ps = mSettings.mPackages.get(packageName);
18188            if (ps == null) {
18189                Log.w(TAG, "Package doesn't exist: " + packageName);
18190                return false;
18191            }
18192            if (systemUserApp) {
18193                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18194            } else {
18195                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18196            }
18197            mSettings.writeLPr();
18198        }
18199        return true;
18200    }
18201
18202    /*
18203     * This method handles package deletion in general
18204     */
18205    private boolean deletePackageLIF(String packageName, UserHandle user,
18206            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18207            PackageRemovedInfo outInfo, boolean writeSettings,
18208            PackageParser.Package replacingPackage) {
18209        if (packageName == null) {
18210            Slog.w(TAG, "Attempt to delete null packageName.");
18211            return false;
18212        }
18213
18214        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18215
18216        PackageSetting ps;
18217        synchronized (mPackages) {
18218            ps = mSettings.mPackages.get(packageName);
18219            if (ps == null) {
18220                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18221                return false;
18222            }
18223
18224            if (ps.parentPackageName != null && (!isSystemApp(ps)
18225                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18226                if (DEBUG_REMOVE) {
18227                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18228                            + ((user == null) ? UserHandle.USER_ALL : user));
18229                }
18230                final int removedUserId = (user != null) ? user.getIdentifier()
18231                        : UserHandle.USER_ALL;
18232                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18233                    return false;
18234                }
18235                markPackageUninstalledForUserLPw(ps, user);
18236                scheduleWritePackageRestrictionsLocked(user);
18237                return true;
18238            }
18239        }
18240
18241        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18242                && user.getIdentifier() != UserHandle.USER_ALL)) {
18243            // The caller is asking that the package only be deleted for a single
18244            // user.  To do this, we just mark its uninstalled state and delete
18245            // its data. If this is a system app, we only allow this to happen if
18246            // they have set the special DELETE_SYSTEM_APP which requests different
18247            // semantics than normal for uninstalling system apps.
18248            markPackageUninstalledForUserLPw(ps, user);
18249
18250            if (!isSystemApp(ps)) {
18251                // Do not uninstall the APK if an app should be cached
18252                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18253                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18254                    // Other user still have this package installed, so all
18255                    // we need to do is clear this user's data and save that
18256                    // it is uninstalled.
18257                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18258                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18259                        return false;
18260                    }
18261                    scheduleWritePackageRestrictionsLocked(user);
18262                    return true;
18263                } else {
18264                    // We need to set it back to 'installed' so the uninstall
18265                    // broadcasts will be sent correctly.
18266                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18267                    ps.setInstalled(true, user.getIdentifier());
18268                    mSettings.writeKernelMappingLPr(ps);
18269                }
18270            } else {
18271                // This is a system app, so we assume that the
18272                // other users still have this package installed, so all
18273                // we need to do is clear this user's data and save that
18274                // it is uninstalled.
18275                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18276                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18277                    return false;
18278                }
18279                scheduleWritePackageRestrictionsLocked(user);
18280                return true;
18281            }
18282        }
18283
18284        // If we are deleting a composite package for all users, keep track
18285        // of result for each child.
18286        if (ps.childPackageNames != null && outInfo != null) {
18287            synchronized (mPackages) {
18288                final int childCount = ps.childPackageNames.size();
18289                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18290                for (int i = 0; i < childCount; i++) {
18291                    String childPackageName = ps.childPackageNames.get(i);
18292                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18293                    childInfo.removedPackage = childPackageName;
18294                    childInfo.installerPackageName = ps.installerPackageName;
18295                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18296                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18297                    if (childPs != null) {
18298                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18299                    }
18300                }
18301            }
18302        }
18303
18304        boolean ret = false;
18305        if (isSystemApp(ps)) {
18306            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18307            // When an updated system application is deleted we delete the existing resources
18308            // as well and fall back to existing code in system partition
18309            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18310        } else {
18311            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18312            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18313                    outInfo, writeSettings, replacingPackage);
18314        }
18315
18316        // Take a note whether we deleted the package for all users
18317        if (outInfo != null) {
18318            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18319            if (outInfo.removedChildPackages != null) {
18320                synchronized (mPackages) {
18321                    final int childCount = outInfo.removedChildPackages.size();
18322                    for (int i = 0; i < childCount; i++) {
18323                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18324                        if (childInfo != null) {
18325                            childInfo.removedForAllUsers = mPackages.get(
18326                                    childInfo.removedPackage) == null;
18327                        }
18328                    }
18329                }
18330            }
18331            // If we uninstalled an update to a system app there may be some
18332            // child packages that appeared as they are declared in the system
18333            // app but were not declared in the update.
18334            if (isSystemApp(ps)) {
18335                synchronized (mPackages) {
18336                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18337                    final int childCount = (updatedPs.childPackageNames != null)
18338                            ? updatedPs.childPackageNames.size() : 0;
18339                    for (int i = 0; i < childCount; i++) {
18340                        String childPackageName = updatedPs.childPackageNames.get(i);
18341                        if (outInfo.removedChildPackages == null
18342                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18343                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18344                            if (childPs == null) {
18345                                continue;
18346                            }
18347                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18348                            installRes.name = childPackageName;
18349                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18350                            installRes.pkg = mPackages.get(childPackageName);
18351                            installRes.uid = childPs.pkg.applicationInfo.uid;
18352                            if (outInfo.appearedChildPackages == null) {
18353                                outInfo.appearedChildPackages = new ArrayMap<>();
18354                            }
18355                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18356                        }
18357                    }
18358                }
18359            }
18360        }
18361
18362        return ret;
18363    }
18364
18365    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18366        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18367                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18368        for (int nextUserId : userIds) {
18369            if (DEBUG_REMOVE) {
18370                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18371            }
18372            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18373                    false /*installed*/,
18374                    true /*stopped*/,
18375                    true /*notLaunched*/,
18376                    false /*hidden*/,
18377                    false /*suspended*/,
18378                    false /*instantApp*/,
18379                    false /*virtualPreload*/,
18380                    null /*lastDisableAppCaller*/,
18381                    null /*enabledComponents*/,
18382                    null /*disabledComponents*/,
18383                    ps.readUserState(nextUserId).domainVerificationStatus,
18384                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18385                    null /*harmfulAppWarning*/);
18386        }
18387        mSettings.writeKernelMappingLPr(ps);
18388    }
18389
18390    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18391            PackageRemovedInfo outInfo) {
18392        final PackageParser.Package pkg;
18393        synchronized (mPackages) {
18394            pkg = mPackages.get(ps.name);
18395        }
18396
18397        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18398                : new int[] {userId};
18399        for (int nextUserId : userIds) {
18400            if (DEBUG_REMOVE) {
18401                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18402                        + nextUserId);
18403            }
18404
18405            destroyAppDataLIF(pkg, userId,
18406                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18407            destroyAppProfilesLIF(pkg, userId);
18408            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18409            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18410            schedulePackageCleaning(ps.name, nextUserId, false);
18411            synchronized (mPackages) {
18412                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18413                    scheduleWritePackageRestrictionsLocked(nextUserId);
18414                }
18415                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18416            }
18417        }
18418
18419        if (outInfo != null) {
18420            outInfo.removedPackage = ps.name;
18421            outInfo.installerPackageName = ps.installerPackageName;
18422            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18423            outInfo.removedAppId = ps.appId;
18424            outInfo.removedUsers = userIds;
18425            outInfo.broadcastUsers = userIds;
18426        }
18427
18428        return true;
18429    }
18430
18431    private final class ClearStorageConnection implements ServiceConnection {
18432        IMediaContainerService mContainerService;
18433
18434        @Override
18435        public void onServiceConnected(ComponentName name, IBinder service) {
18436            synchronized (this) {
18437                mContainerService = IMediaContainerService.Stub
18438                        .asInterface(Binder.allowBlocking(service));
18439                notifyAll();
18440            }
18441        }
18442
18443        @Override
18444        public void onServiceDisconnected(ComponentName name) {
18445        }
18446    }
18447
18448    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18449        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18450
18451        final boolean mounted;
18452        if (Environment.isExternalStorageEmulated()) {
18453            mounted = true;
18454        } else {
18455            final String status = Environment.getExternalStorageState();
18456
18457            mounted = status.equals(Environment.MEDIA_MOUNTED)
18458                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18459        }
18460
18461        if (!mounted) {
18462            return;
18463        }
18464
18465        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18466        int[] users;
18467        if (userId == UserHandle.USER_ALL) {
18468            users = sUserManager.getUserIds();
18469        } else {
18470            users = new int[] { userId };
18471        }
18472        final ClearStorageConnection conn = new ClearStorageConnection();
18473        if (mContext.bindServiceAsUser(
18474                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18475            try {
18476                for (int curUser : users) {
18477                    long timeout = SystemClock.uptimeMillis() + 5000;
18478                    synchronized (conn) {
18479                        long now;
18480                        while (conn.mContainerService == null &&
18481                                (now = SystemClock.uptimeMillis()) < timeout) {
18482                            try {
18483                                conn.wait(timeout - now);
18484                            } catch (InterruptedException e) {
18485                            }
18486                        }
18487                    }
18488                    if (conn.mContainerService == null) {
18489                        return;
18490                    }
18491
18492                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18493                    clearDirectory(conn.mContainerService,
18494                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18495                    if (allData) {
18496                        clearDirectory(conn.mContainerService,
18497                                userEnv.buildExternalStorageAppDataDirs(packageName));
18498                        clearDirectory(conn.mContainerService,
18499                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18500                    }
18501                }
18502            } finally {
18503                mContext.unbindService(conn);
18504            }
18505        }
18506    }
18507
18508    @Override
18509    public void clearApplicationProfileData(String packageName) {
18510        enforceSystemOrRoot("Only the system can clear all profile data");
18511
18512        final PackageParser.Package pkg;
18513        synchronized (mPackages) {
18514            pkg = mPackages.get(packageName);
18515        }
18516
18517        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18518            synchronized (mInstallLock) {
18519                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18520            }
18521        }
18522    }
18523
18524    @Override
18525    public void clearApplicationUserData(final String packageName,
18526            final IPackageDataObserver observer, final int userId) {
18527        mContext.enforceCallingOrSelfPermission(
18528                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18529
18530        final int callingUid = Binder.getCallingUid();
18531        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18532                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18533
18534        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18535        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18536        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18537            throw new SecurityException("Cannot clear data for a protected package: "
18538                    + packageName);
18539        }
18540        // Queue up an async operation since the package deletion may take a little while.
18541        mHandler.post(new Runnable() {
18542            public void run() {
18543                mHandler.removeCallbacks(this);
18544                final boolean succeeded;
18545                if (!filterApp) {
18546                    try (PackageFreezer freezer = freezePackage(packageName,
18547                            "clearApplicationUserData")) {
18548                        synchronized (mInstallLock) {
18549                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18550                        }
18551                        clearExternalStorageDataSync(packageName, userId, true);
18552                        synchronized (mPackages) {
18553                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18554                                    packageName, userId);
18555                        }
18556                    }
18557                    if (succeeded) {
18558                        // invoke DeviceStorageMonitor's update method to clear any notifications
18559                        DeviceStorageMonitorInternal dsm = LocalServices
18560                                .getService(DeviceStorageMonitorInternal.class);
18561                        if (dsm != null) {
18562                            dsm.checkMemory();
18563                        }
18564                    }
18565                } else {
18566                    succeeded = false;
18567                }
18568                if (observer != null) {
18569                    try {
18570                        observer.onRemoveCompleted(packageName, succeeded);
18571                    } catch (RemoteException e) {
18572                        Log.i(TAG, "Observer no longer exists.");
18573                    }
18574                } //end if observer
18575            } //end run
18576        });
18577    }
18578
18579    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18580        if (packageName == null) {
18581            Slog.w(TAG, "Attempt to delete null packageName.");
18582            return false;
18583        }
18584
18585        // Try finding details about the requested package
18586        PackageParser.Package pkg;
18587        synchronized (mPackages) {
18588            pkg = mPackages.get(packageName);
18589            if (pkg == null) {
18590                final PackageSetting ps = mSettings.mPackages.get(packageName);
18591                if (ps != null) {
18592                    pkg = ps.pkg;
18593                }
18594            }
18595
18596            if (pkg == null) {
18597                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18598                return false;
18599            }
18600
18601            PackageSetting ps = (PackageSetting) pkg.mExtras;
18602            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18603        }
18604
18605        clearAppDataLIF(pkg, userId,
18606                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18607
18608        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18609        removeKeystoreDataIfNeeded(userId, appId);
18610
18611        UserManagerInternal umInternal = getUserManagerInternal();
18612        final int flags;
18613        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18614            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18615        } else if (umInternal.isUserRunning(userId)) {
18616            flags = StorageManager.FLAG_STORAGE_DE;
18617        } else {
18618            flags = 0;
18619        }
18620        prepareAppDataContentsLIF(pkg, userId, flags);
18621
18622        return true;
18623    }
18624
18625    /**
18626     * Reverts user permission state changes (permissions and flags) in
18627     * all packages for a given user.
18628     *
18629     * @param userId The device user for which to do a reset.
18630     */
18631    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18632        final int packageCount = mPackages.size();
18633        for (int i = 0; i < packageCount; i++) {
18634            PackageParser.Package pkg = mPackages.valueAt(i);
18635            PackageSetting ps = (PackageSetting) pkg.mExtras;
18636            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18637        }
18638    }
18639
18640    private void resetNetworkPolicies(int userId) {
18641        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18642    }
18643
18644    /**
18645     * Reverts user permission state changes (permissions and flags).
18646     *
18647     * @param ps The package for which to reset.
18648     * @param userId The device user for which to do a reset.
18649     */
18650    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18651            final PackageSetting ps, final int userId) {
18652        if (ps.pkg == null) {
18653            return;
18654        }
18655
18656        // These are flags that can change base on user actions.
18657        final int userSettableMask = FLAG_PERMISSION_USER_SET
18658                | FLAG_PERMISSION_USER_FIXED
18659                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18660                | FLAG_PERMISSION_REVIEW_REQUIRED;
18661
18662        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18663                | FLAG_PERMISSION_POLICY_FIXED;
18664
18665        boolean writeInstallPermissions = false;
18666        boolean writeRuntimePermissions = false;
18667
18668        final int permissionCount = ps.pkg.requestedPermissions.size();
18669        for (int i = 0; i < permissionCount; i++) {
18670            final String permName = ps.pkg.requestedPermissions.get(i);
18671            final BasePermission bp =
18672                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18673            if (bp == null) {
18674                continue;
18675            }
18676
18677            // If shared user we just reset the state to which only this app contributed.
18678            if (ps.sharedUser != null) {
18679                boolean used = false;
18680                final int packageCount = ps.sharedUser.packages.size();
18681                for (int j = 0; j < packageCount; j++) {
18682                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18683                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18684                            && pkg.pkg.requestedPermissions.contains(permName)) {
18685                        used = true;
18686                        break;
18687                    }
18688                }
18689                if (used) {
18690                    continue;
18691                }
18692            }
18693
18694            final PermissionsState permissionsState = ps.getPermissionsState();
18695
18696            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18697
18698            // Always clear the user settable flags.
18699            final boolean hasInstallState =
18700                    permissionsState.getInstallPermissionState(permName) != null;
18701            // If permission review is enabled and this is a legacy app, mark the
18702            // permission as requiring a review as this is the initial state.
18703            int flags = 0;
18704            if (mSettings.mPermissions.mPermissionReviewRequired
18705                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18706                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18707            }
18708            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18709                if (hasInstallState) {
18710                    writeInstallPermissions = true;
18711                } else {
18712                    writeRuntimePermissions = true;
18713                }
18714            }
18715
18716            // Below is only runtime permission handling.
18717            if (!bp.isRuntime()) {
18718                continue;
18719            }
18720
18721            // Never clobber system or policy.
18722            if ((oldFlags & policyOrSystemFlags) != 0) {
18723                continue;
18724            }
18725
18726            // If this permission was granted by default, make sure it is.
18727            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18728                if (permissionsState.grantRuntimePermission(bp, userId)
18729                        != PERMISSION_OPERATION_FAILURE) {
18730                    writeRuntimePermissions = true;
18731                }
18732            // If permission review is enabled the permissions for a legacy apps
18733            // are represented as constantly granted runtime ones, so don't revoke.
18734            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18735                // Otherwise, reset the permission.
18736                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18737                switch (revokeResult) {
18738                    case PERMISSION_OPERATION_SUCCESS:
18739                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18740                        writeRuntimePermissions = true;
18741                        final int appId = ps.appId;
18742                        mHandler.post(new Runnable() {
18743                            @Override
18744                            public void run() {
18745                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18746                            }
18747                        });
18748                    } break;
18749                }
18750            }
18751        }
18752
18753        // Synchronously write as we are taking permissions away.
18754        if (writeRuntimePermissions) {
18755            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18756        }
18757
18758        // Synchronously write as we are taking permissions away.
18759        if (writeInstallPermissions) {
18760            mSettings.writeLPr();
18761        }
18762    }
18763
18764    /**
18765     * Remove entries from the keystore daemon. Will only remove it if the
18766     * {@code appId} is valid.
18767     */
18768    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18769        if (appId < 0) {
18770            return;
18771        }
18772
18773        final KeyStore keyStore = KeyStore.getInstance();
18774        if (keyStore != null) {
18775            if (userId == UserHandle.USER_ALL) {
18776                for (final int individual : sUserManager.getUserIds()) {
18777                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18778                }
18779            } else {
18780                keyStore.clearUid(UserHandle.getUid(userId, appId));
18781            }
18782        } else {
18783            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18784        }
18785    }
18786
18787    @Override
18788    public void deleteApplicationCacheFiles(final String packageName,
18789            final IPackageDataObserver observer) {
18790        final int userId = UserHandle.getCallingUserId();
18791        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18792    }
18793
18794    @Override
18795    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18796            final IPackageDataObserver observer) {
18797        final int callingUid = Binder.getCallingUid();
18798        mContext.enforceCallingOrSelfPermission(
18799                android.Manifest.permission.DELETE_CACHE_FILES, null);
18800        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18801                /* requireFullPermission= */ true, /* checkShell= */ false,
18802                "delete application cache files");
18803        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18804                android.Manifest.permission.ACCESS_INSTANT_APPS);
18805
18806        final PackageParser.Package pkg;
18807        synchronized (mPackages) {
18808            pkg = mPackages.get(packageName);
18809        }
18810
18811        // Queue up an async operation since the package deletion may take a little while.
18812        mHandler.post(new Runnable() {
18813            public void run() {
18814                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18815                boolean doClearData = true;
18816                if (ps != null) {
18817                    final boolean targetIsInstantApp =
18818                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18819                    doClearData = !targetIsInstantApp
18820                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18821                }
18822                if (doClearData) {
18823                    synchronized (mInstallLock) {
18824                        final int flags = StorageManager.FLAG_STORAGE_DE
18825                                | StorageManager.FLAG_STORAGE_CE;
18826                        // We're only clearing cache files, so we don't care if the
18827                        // app is unfrozen and still able to run
18828                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18829                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18830                    }
18831                    clearExternalStorageDataSync(packageName, userId, false);
18832                }
18833                if (observer != null) {
18834                    try {
18835                        observer.onRemoveCompleted(packageName, true);
18836                    } catch (RemoteException e) {
18837                        Log.i(TAG, "Observer no longer exists.");
18838                    }
18839                }
18840            }
18841        });
18842    }
18843
18844    @Override
18845    public void getPackageSizeInfo(final String packageName, int userHandle,
18846            final IPackageStatsObserver observer) {
18847        throw new UnsupportedOperationException(
18848                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18849    }
18850
18851    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18852        final PackageSetting ps;
18853        synchronized (mPackages) {
18854            ps = mSettings.mPackages.get(packageName);
18855            if (ps == null) {
18856                Slog.w(TAG, "Failed to find settings for " + packageName);
18857                return false;
18858            }
18859        }
18860
18861        final String[] packageNames = { packageName };
18862        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18863        final String[] codePaths = { ps.codePathString };
18864
18865        try {
18866            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18867                    ps.appId, ceDataInodes, codePaths, stats);
18868
18869            // For now, ignore code size of packages on system partition
18870            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18871                stats.codeSize = 0;
18872            }
18873
18874            // External clients expect these to be tracked separately
18875            stats.dataSize -= stats.cacheSize;
18876
18877        } catch (InstallerException e) {
18878            Slog.w(TAG, String.valueOf(e));
18879            return false;
18880        }
18881
18882        return true;
18883    }
18884
18885    private int getUidTargetSdkVersionLockedLPr(int uid) {
18886        Object obj = mSettings.getUserIdLPr(uid);
18887        if (obj instanceof SharedUserSetting) {
18888            final SharedUserSetting sus = (SharedUserSetting) obj;
18889            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18890            final Iterator<PackageSetting> it = sus.packages.iterator();
18891            while (it.hasNext()) {
18892                final PackageSetting ps = it.next();
18893                if (ps.pkg != null) {
18894                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18895                    if (v < vers) vers = v;
18896                }
18897            }
18898            return vers;
18899        } else if (obj instanceof PackageSetting) {
18900            final PackageSetting ps = (PackageSetting) obj;
18901            if (ps.pkg != null) {
18902                return ps.pkg.applicationInfo.targetSdkVersion;
18903            }
18904        }
18905        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18906    }
18907
18908    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
18909        final PackageParser.Package p = mPackages.get(packageName);
18910        if (p != null) {
18911            return p.applicationInfo.targetSdkVersion;
18912        }
18913        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18914    }
18915
18916    @Override
18917    public void addPreferredActivity(IntentFilter filter, int match,
18918            ComponentName[] set, ComponentName activity, int userId) {
18919        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18920                "Adding preferred");
18921    }
18922
18923    private void addPreferredActivityInternal(IntentFilter filter, int match,
18924            ComponentName[] set, ComponentName activity, boolean always, int userId,
18925            String opname) {
18926        // writer
18927        int callingUid = Binder.getCallingUid();
18928        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18929                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18930        if (filter.countActions() == 0) {
18931            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18932            return;
18933        }
18934        synchronized (mPackages) {
18935            if (mContext.checkCallingOrSelfPermission(
18936                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18937                    != PackageManager.PERMISSION_GRANTED) {
18938                if (getUidTargetSdkVersionLockedLPr(callingUid)
18939                        < Build.VERSION_CODES.FROYO) {
18940                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18941                            + callingUid);
18942                    return;
18943                }
18944                mContext.enforceCallingOrSelfPermission(
18945                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18946            }
18947
18948            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18949            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18950                    + userId + ":");
18951            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18952            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18953            scheduleWritePackageRestrictionsLocked(userId);
18954            postPreferredActivityChangedBroadcast(userId);
18955        }
18956    }
18957
18958    private void postPreferredActivityChangedBroadcast(int userId) {
18959        mHandler.post(() -> {
18960            final IActivityManager am = ActivityManager.getService();
18961            if (am == null) {
18962                return;
18963            }
18964
18965            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18966            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18967            try {
18968                am.broadcastIntent(null, intent, null, null,
18969                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18970                        null, false, false, userId);
18971            } catch (RemoteException e) {
18972            }
18973        });
18974    }
18975
18976    @Override
18977    public void replacePreferredActivity(IntentFilter filter, int match,
18978            ComponentName[] set, ComponentName activity, int userId) {
18979        if (filter.countActions() != 1) {
18980            throw new IllegalArgumentException(
18981                    "replacePreferredActivity expects filter to have only 1 action.");
18982        }
18983        if (filter.countDataAuthorities() != 0
18984                || filter.countDataPaths() != 0
18985                || filter.countDataSchemes() > 1
18986                || filter.countDataTypes() != 0) {
18987            throw new IllegalArgumentException(
18988                    "replacePreferredActivity expects filter to have no data authorities, " +
18989                    "paths, or types; and at most one scheme.");
18990        }
18991
18992        final int callingUid = Binder.getCallingUid();
18993        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18994                true /* requireFullPermission */, false /* checkShell */,
18995                "replace preferred activity");
18996        synchronized (mPackages) {
18997            if (mContext.checkCallingOrSelfPermission(
18998                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18999                    != PackageManager.PERMISSION_GRANTED) {
19000                if (getUidTargetSdkVersionLockedLPr(callingUid)
19001                        < Build.VERSION_CODES.FROYO) {
19002                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19003                            + Binder.getCallingUid());
19004                    return;
19005                }
19006                mContext.enforceCallingOrSelfPermission(
19007                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19008            }
19009
19010            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19011            if (pir != null) {
19012                // Get all of the existing entries that exactly match this filter.
19013                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19014                if (existing != null && existing.size() == 1) {
19015                    PreferredActivity cur = existing.get(0);
19016                    if (DEBUG_PREFERRED) {
19017                        Slog.i(TAG, "Checking replace of preferred:");
19018                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19019                        if (!cur.mPref.mAlways) {
19020                            Slog.i(TAG, "  -- CUR; not mAlways!");
19021                        } else {
19022                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19023                            Slog.i(TAG, "  -- CUR: mSet="
19024                                    + Arrays.toString(cur.mPref.mSetComponents));
19025                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19026                            Slog.i(TAG, "  -- NEW: mMatch="
19027                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19028                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19029                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19030                        }
19031                    }
19032                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19033                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19034                            && cur.mPref.sameSet(set)) {
19035                        // Setting the preferred activity to what it happens to be already
19036                        if (DEBUG_PREFERRED) {
19037                            Slog.i(TAG, "Replacing with same preferred activity "
19038                                    + cur.mPref.mShortComponent + " for user "
19039                                    + userId + ":");
19040                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19041                        }
19042                        return;
19043                    }
19044                }
19045
19046                if (existing != null) {
19047                    if (DEBUG_PREFERRED) {
19048                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19049                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19050                    }
19051                    for (int i = 0; i < existing.size(); i++) {
19052                        PreferredActivity pa = existing.get(i);
19053                        if (DEBUG_PREFERRED) {
19054                            Slog.i(TAG, "Removing existing preferred activity "
19055                                    + pa.mPref.mComponent + ":");
19056                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19057                        }
19058                        pir.removeFilter(pa);
19059                    }
19060                }
19061            }
19062            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19063                    "Replacing preferred");
19064        }
19065    }
19066
19067    @Override
19068    public void clearPackagePreferredActivities(String packageName) {
19069        final int callingUid = Binder.getCallingUid();
19070        if (getInstantAppPackageName(callingUid) != null) {
19071            return;
19072        }
19073        // writer
19074        synchronized (mPackages) {
19075            PackageParser.Package pkg = mPackages.get(packageName);
19076            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19077                if (mContext.checkCallingOrSelfPermission(
19078                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19079                        != PackageManager.PERMISSION_GRANTED) {
19080                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19081                            < Build.VERSION_CODES.FROYO) {
19082                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19083                                + callingUid);
19084                        return;
19085                    }
19086                    mContext.enforceCallingOrSelfPermission(
19087                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19088                }
19089            }
19090            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19091            if (ps != null
19092                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19093                return;
19094            }
19095            int user = UserHandle.getCallingUserId();
19096            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19097                scheduleWritePackageRestrictionsLocked(user);
19098            }
19099        }
19100    }
19101
19102    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19103    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19104        ArrayList<PreferredActivity> removed = null;
19105        boolean changed = false;
19106        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19107            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19108            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19109            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19110                continue;
19111            }
19112            Iterator<PreferredActivity> it = pir.filterIterator();
19113            while (it.hasNext()) {
19114                PreferredActivity pa = it.next();
19115                // Mark entry for removal only if it matches the package name
19116                // and the entry is of type "always".
19117                if (packageName == null ||
19118                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19119                                && pa.mPref.mAlways)) {
19120                    if (removed == null) {
19121                        removed = new ArrayList<PreferredActivity>();
19122                    }
19123                    removed.add(pa);
19124                }
19125            }
19126            if (removed != null) {
19127                for (int j=0; j<removed.size(); j++) {
19128                    PreferredActivity pa = removed.get(j);
19129                    pir.removeFilter(pa);
19130                }
19131                changed = true;
19132            }
19133        }
19134        if (changed) {
19135            postPreferredActivityChangedBroadcast(userId);
19136        }
19137        return changed;
19138    }
19139
19140    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19141    private void clearIntentFilterVerificationsLPw(int userId) {
19142        final int packageCount = mPackages.size();
19143        for (int i = 0; i < packageCount; i++) {
19144            PackageParser.Package pkg = mPackages.valueAt(i);
19145            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19146        }
19147    }
19148
19149    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19150    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19151        if (userId == UserHandle.USER_ALL) {
19152            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19153                    sUserManager.getUserIds())) {
19154                for (int oneUserId : sUserManager.getUserIds()) {
19155                    scheduleWritePackageRestrictionsLocked(oneUserId);
19156                }
19157            }
19158        } else {
19159            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19160                scheduleWritePackageRestrictionsLocked(userId);
19161            }
19162        }
19163    }
19164
19165    /** Clears state for all users, and touches intent filter verification policy */
19166    void clearDefaultBrowserIfNeeded(String packageName) {
19167        for (int oneUserId : sUserManager.getUserIds()) {
19168            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19169        }
19170    }
19171
19172    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19173        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19174        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19175            if (packageName.equals(defaultBrowserPackageName)) {
19176                setDefaultBrowserPackageName(null, userId);
19177            }
19178        }
19179    }
19180
19181    @Override
19182    public void resetApplicationPreferences(int userId) {
19183        mContext.enforceCallingOrSelfPermission(
19184                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19185        final long identity = Binder.clearCallingIdentity();
19186        // writer
19187        try {
19188            synchronized (mPackages) {
19189                clearPackagePreferredActivitiesLPw(null, userId);
19190                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19191                // TODO: We have to reset the default SMS and Phone. This requires
19192                // significant refactoring to keep all default apps in the package
19193                // manager (cleaner but more work) or have the services provide
19194                // callbacks to the package manager to request a default app reset.
19195                applyFactoryDefaultBrowserLPw(userId);
19196                clearIntentFilterVerificationsLPw(userId);
19197                primeDomainVerificationsLPw(userId);
19198                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19199                scheduleWritePackageRestrictionsLocked(userId);
19200            }
19201            resetNetworkPolicies(userId);
19202        } finally {
19203            Binder.restoreCallingIdentity(identity);
19204        }
19205    }
19206
19207    @Override
19208    public int getPreferredActivities(List<IntentFilter> outFilters,
19209            List<ComponentName> outActivities, String packageName) {
19210        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19211            return 0;
19212        }
19213        int num = 0;
19214        final int userId = UserHandle.getCallingUserId();
19215        // reader
19216        synchronized (mPackages) {
19217            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19218            if (pir != null) {
19219                final Iterator<PreferredActivity> it = pir.filterIterator();
19220                while (it.hasNext()) {
19221                    final PreferredActivity pa = it.next();
19222                    if (packageName == null
19223                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19224                                    && pa.mPref.mAlways)) {
19225                        if (outFilters != null) {
19226                            outFilters.add(new IntentFilter(pa));
19227                        }
19228                        if (outActivities != null) {
19229                            outActivities.add(pa.mPref.mComponent);
19230                        }
19231                    }
19232                }
19233            }
19234        }
19235
19236        return num;
19237    }
19238
19239    @Override
19240    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19241            int userId) {
19242        int callingUid = Binder.getCallingUid();
19243        if (callingUid != Process.SYSTEM_UID) {
19244            throw new SecurityException(
19245                    "addPersistentPreferredActivity can only be run by the system");
19246        }
19247        if (filter.countActions() == 0) {
19248            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19249            return;
19250        }
19251        synchronized (mPackages) {
19252            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19253                    ":");
19254            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19255            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19256                    new PersistentPreferredActivity(filter, activity));
19257            scheduleWritePackageRestrictionsLocked(userId);
19258            postPreferredActivityChangedBroadcast(userId);
19259        }
19260    }
19261
19262    @Override
19263    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19264        int callingUid = Binder.getCallingUid();
19265        if (callingUid != Process.SYSTEM_UID) {
19266            throw new SecurityException(
19267                    "clearPackagePersistentPreferredActivities can only be run by the system");
19268        }
19269        ArrayList<PersistentPreferredActivity> removed = null;
19270        boolean changed = false;
19271        synchronized (mPackages) {
19272            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19273                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19274                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19275                        .valueAt(i);
19276                if (userId != thisUserId) {
19277                    continue;
19278                }
19279                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19280                while (it.hasNext()) {
19281                    PersistentPreferredActivity ppa = it.next();
19282                    // Mark entry for removal only if it matches the package name.
19283                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19284                        if (removed == null) {
19285                            removed = new ArrayList<PersistentPreferredActivity>();
19286                        }
19287                        removed.add(ppa);
19288                    }
19289                }
19290                if (removed != null) {
19291                    for (int j=0; j<removed.size(); j++) {
19292                        PersistentPreferredActivity ppa = removed.get(j);
19293                        ppir.removeFilter(ppa);
19294                    }
19295                    changed = true;
19296                }
19297            }
19298
19299            if (changed) {
19300                scheduleWritePackageRestrictionsLocked(userId);
19301                postPreferredActivityChangedBroadcast(userId);
19302            }
19303        }
19304    }
19305
19306    /**
19307     * Common machinery for picking apart a restored XML blob and passing
19308     * it to a caller-supplied functor to be applied to the running system.
19309     */
19310    private void restoreFromXml(XmlPullParser parser, int userId,
19311            String expectedStartTag, BlobXmlRestorer functor)
19312            throws IOException, XmlPullParserException {
19313        int type;
19314        while ((type = parser.next()) != XmlPullParser.START_TAG
19315                && type != XmlPullParser.END_DOCUMENT) {
19316        }
19317        if (type != XmlPullParser.START_TAG) {
19318            // oops didn't find a start tag?!
19319            if (DEBUG_BACKUP) {
19320                Slog.e(TAG, "Didn't find start tag during restore");
19321            }
19322            return;
19323        }
19324Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19325        // this is supposed to be TAG_PREFERRED_BACKUP
19326        if (!expectedStartTag.equals(parser.getName())) {
19327            if (DEBUG_BACKUP) {
19328                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19329            }
19330            return;
19331        }
19332
19333        // skip interfering stuff, then we're aligned with the backing implementation
19334        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19335Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19336        functor.apply(parser, userId);
19337    }
19338
19339    private interface BlobXmlRestorer {
19340        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19341    }
19342
19343    /**
19344     * Non-Binder method, support for the backup/restore mechanism: write the
19345     * full set of preferred activities in its canonical XML format.  Returns the
19346     * XML output as a byte array, or null if there is none.
19347     */
19348    @Override
19349    public byte[] getPreferredActivityBackup(int userId) {
19350        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19351            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19352        }
19353
19354        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19355        try {
19356            final XmlSerializer serializer = new FastXmlSerializer();
19357            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19358            serializer.startDocument(null, true);
19359            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19360
19361            synchronized (mPackages) {
19362                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19363            }
19364
19365            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19366            serializer.endDocument();
19367            serializer.flush();
19368        } catch (Exception e) {
19369            if (DEBUG_BACKUP) {
19370                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19371            }
19372            return null;
19373        }
19374
19375        return dataStream.toByteArray();
19376    }
19377
19378    @Override
19379    public void restorePreferredActivities(byte[] backup, int userId) {
19380        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19381            throw new SecurityException("Only the system may call restorePreferredActivities()");
19382        }
19383
19384        try {
19385            final XmlPullParser parser = Xml.newPullParser();
19386            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19387            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19388                    new BlobXmlRestorer() {
19389                        @Override
19390                        public void apply(XmlPullParser parser, int userId)
19391                                throws XmlPullParserException, IOException {
19392                            synchronized (mPackages) {
19393                                mSettings.readPreferredActivitiesLPw(parser, userId);
19394                            }
19395                        }
19396                    } );
19397        } catch (Exception e) {
19398            if (DEBUG_BACKUP) {
19399                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19400            }
19401        }
19402    }
19403
19404    /**
19405     * Non-Binder method, support for the backup/restore mechanism: write the
19406     * default browser (etc) settings in its canonical XML format.  Returns the default
19407     * browser XML representation as a byte array, or null if there is none.
19408     */
19409    @Override
19410    public byte[] getDefaultAppsBackup(int userId) {
19411        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19412            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19413        }
19414
19415        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19416        try {
19417            final XmlSerializer serializer = new FastXmlSerializer();
19418            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19419            serializer.startDocument(null, true);
19420            serializer.startTag(null, TAG_DEFAULT_APPS);
19421
19422            synchronized (mPackages) {
19423                mSettings.writeDefaultAppsLPr(serializer, userId);
19424            }
19425
19426            serializer.endTag(null, TAG_DEFAULT_APPS);
19427            serializer.endDocument();
19428            serializer.flush();
19429        } catch (Exception e) {
19430            if (DEBUG_BACKUP) {
19431                Slog.e(TAG, "Unable to write default apps for backup", e);
19432            }
19433            return null;
19434        }
19435
19436        return dataStream.toByteArray();
19437    }
19438
19439    @Override
19440    public void restoreDefaultApps(byte[] backup, int userId) {
19441        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19442            throw new SecurityException("Only the system may call restoreDefaultApps()");
19443        }
19444
19445        try {
19446            final XmlPullParser parser = Xml.newPullParser();
19447            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19448            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19449                    new BlobXmlRestorer() {
19450                        @Override
19451                        public void apply(XmlPullParser parser, int userId)
19452                                throws XmlPullParserException, IOException {
19453                            synchronized (mPackages) {
19454                                mSettings.readDefaultAppsLPw(parser, userId);
19455                            }
19456                        }
19457                    } );
19458        } catch (Exception e) {
19459            if (DEBUG_BACKUP) {
19460                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19461            }
19462        }
19463    }
19464
19465    @Override
19466    public byte[] getIntentFilterVerificationBackup(int userId) {
19467        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19468            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19469        }
19470
19471        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19472        try {
19473            final XmlSerializer serializer = new FastXmlSerializer();
19474            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19475            serializer.startDocument(null, true);
19476            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19477
19478            synchronized (mPackages) {
19479                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19480            }
19481
19482            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19483            serializer.endDocument();
19484            serializer.flush();
19485        } catch (Exception e) {
19486            if (DEBUG_BACKUP) {
19487                Slog.e(TAG, "Unable to write default apps for backup", e);
19488            }
19489            return null;
19490        }
19491
19492        return dataStream.toByteArray();
19493    }
19494
19495    @Override
19496    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19497        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19498            throw new SecurityException("Only the system may call restorePreferredActivities()");
19499        }
19500
19501        try {
19502            final XmlPullParser parser = Xml.newPullParser();
19503            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19504            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19505                    new BlobXmlRestorer() {
19506                        @Override
19507                        public void apply(XmlPullParser parser, int userId)
19508                                throws XmlPullParserException, IOException {
19509                            synchronized (mPackages) {
19510                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19511                                mSettings.writeLPr();
19512                            }
19513                        }
19514                    } );
19515        } catch (Exception e) {
19516            if (DEBUG_BACKUP) {
19517                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19518            }
19519        }
19520    }
19521
19522    @Override
19523    public byte[] getPermissionGrantBackup(int userId) {
19524        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19525            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19526        }
19527
19528        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19529        try {
19530            final XmlSerializer serializer = new FastXmlSerializer();
19531            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19532            serializer.startDocument(null, true);
19533            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19534
19535            synchronized (mPackages) {
19536                serializeRuntimePermissionGrantsLPr(serializer, userId);
19537            }
19538
19539            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19540            serializer.endDocument();
19541            serializer.flush();
19542        } catch (Exception e) {
19543            if (DEBUG_BACKUP) {
19544                Slog.e(TAG, "Unable to write default apps for backup", e);
19545            }
19546            return null;
19547        }
19548
19549        return dataStream.toByteArray();
19550    }
19551
19552    @Override
19553    public void restorePermissionGrants(byte[] backup, int userId) {
19554        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19555            throw new SecurityException("Only the system may call restorePermissionGrants()");
19556        }
19557
19558        try {
19559            final XmlPullParser parser = Xml.newPullParser();
19560            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19561            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19562                    new BlobXmlRestorer() {
19563                        @Override
19564                        public void apply(XmlPullParser parser, int userId)
19565                                throws XmlPullParserException, IOException {
19566                            synchronized (mPackages) {
19567                                processRestoredPermissionGrantsLPr(parser, userId);
19568                            }
19569                        }
19570                    } );
19571        } catch (Exception e) {
19572            if (DEBUG_BACKUP) {
19573                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19574            }
19575        }
19576    }
19577
19578    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19579            throws IOException {
19580        serializer.startTag(null, TAG_ALL_GRANTS);
19581
19582        final int N = mSettings.mPackages.size();
19583        for (int i = 0; i < N; i++) {
19584            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19585            boolean pkgGrantsKnown = false;
19586
19587            PermissionsState packagePerms = ps.getPermissionsState();
19588
19589            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19590                final int grantFlags = state.getFlags();
19591                // only look at grants that are not system/policy fixed
19592                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19593                    final boolean isGranted = state.isGranted();
19594                    // And only back up the user-twiddled state bits
19595                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19596                        final String packageName = mSettings.mPackages.keyAt(i);
19597                        if (!pkgGrantsKnown) {
19598                            serializer.startTag(null, TAG_GRANT);
19599                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19600                            pkgGrantsKnown = true;
19601                        }
19602
19603                        final boolean userSet =
19604                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19605                        final boolean userFixed =
19606                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19607                        final boolean revoke =
19608                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19609
19610                        serializer.startTag(null, TAG_PERMISSION);
19611                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19612                        if (isGranted) {
19613                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19614                        }
19615                        if (userSet) {
19616                            serializer.attribute(null, ATTR_USER_SET, "true");
19617                        }
19618                        if (userFixed) {
19619                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19620                        }
19621                        if (revoke) {
19622                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19623                        }
19624                        serializer.endTag(null, TAG_PERMISSION);
19625                    }
19626                }
19627            }
19628
19629            if (pkgGrantsKnown) {
19630                serializer.endTag(null, TAG_GRANT);
19631            }
19632        }
19633
19634        serializer.endTag(null, TAG_ALL_GRANTS);
19635    }
19636
19637    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19638            throws XmlPullParserException, IOException {
19639        String pkgName = null;
19640        int outerDepth = parser.getDepth();
19641        int type;
19642        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19643                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19644            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19645                continue;
19646            }
19647
19648            final String tagName = parser.getName();
19649            if (tagName.equals(TAG_GRANT)) {
19650                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19651                if (DEBUG_BACKUP) {
19652                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19653                }
19654            } else if (tagName.equals(TAG_PERMISSION)) {
19655
19656                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19657                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19658
19659                int newFlagSet = 0;
19660                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19661                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19662                }
19663                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19664                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19665                }
19666                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19667                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19668                }
19669                if (DEBUG_BACKUP) {
19670                    Slog.v(TAG, "  + Restoring grant:"
19671                            + " pkg=" + pkgName
19672                            + " perm=" + permName
19673                            + " granted=" + isGranted
19674                            + " bits=0x" + Integer.toHexString(newFlagSet));
19675                }
19676                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19677                if (ps != null) {
19678                    // Already installed so we apply the grant immediately
19679                    if (DEBUG_BACKUP) {
19680                        Slog.v(TAG, "        + already installed; applying");
19681                    }
19682                    PermissionsState perms = ps.getPermissionsState();
19683                    BasePermission bp =
19684                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19685                    if (bp != null) {
19686                        if (isGranted) {
19687                            perms.grantRuntimePermission(bp, userId);
19688                        }
19689                        if (newFlagSet != 0) {
19690                            perms.updatePermissionFlags(
19691                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19692                        }
19693                    }
19694                } else {
19695                    // Need to wait for post-restore install to apply the grant
19696                    if (DEBUG_BACKUP) {
19697                        Slog.v(TAG, "        - not yet installed; saving for later");
19698                    }
19699                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19700                            isGranted, newFlagSet, userId);
19701                }
19702            } else {
19703                PackageManagerService.reportSettingsProblem(Log.WARN,
19704                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19705                XmlUtils.skipCurrentTag(parser);
19706            }
19707        }
19708
19709        scheduleWriteSettingsLocked();
19710        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19711    }
19712
19713    @Override
19714    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19715            int sourceUserId, int targetUserId, int flags) {
19716        mContext.enforceCallingOrSelfPermission(
19717                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19718        int callingUid = Binder.getCallingUid();
19719        enforceOwnerRights(ownerPackage, callingUid);
19720        PackageManagerServiceUtils.enforceShellRestriction(
19721                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19722        if (intentFilter.countActions() == 0) {
19723            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19724            return;
19725        }
19726        synchronized (mPackages) {
19727            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19728                    ownerPackage, targetUserId, flags);
19729            CrossProfileIntentResolver resolver =
19730                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19731            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19732            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19733            if (existing != null) {
19734                int size = existing.size();
19735                for (int i = 0; i < size; i++) {
19736                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19737                        return;
19738                    }
19739                }
19740            }
19741            resolver.addFilter(newFilter);
19742            scheduleWritePackageRestrictionsLocked(sourceUserId);
19743        }
19744    }
19745
19746    @Override
19747    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19748        mContext.enforceCallingOrSelfPermission(
19749                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19750        final int callingUid = Binder.getCallingUid();
19751        enforceOwnerRights(ownerPackage, callingUid);
19752        PackageManagerServiceUtils.enforceShellRestriction(
19753                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19754        synchronized (mPackages) {
19755            CrossProfileIntentResolver resolver =
19756                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19757            ArraySet<CrossProfileIntentFilter> set =
19758                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19759            for (CrossProfileIntentFilter filter : set) {
19760                if (filter.getOwnerPackage().equals(ownerPackage)) {
19761                    resolver.removeFilter(filter);
19762                }
19763            }
19764            scheduleWritePackageRestrictionsLocked(sourceUserId);
19765        }
19766    }
19767
19768    // Enforcing that callingUid is owning pkg on userId
19769    private void enforceOwnerRights(String pkg, int callingUid) {
19770        // The system owns everything.
19771        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19772            return;
19773        }
19774        final int callingUserId = UserHandle.getUserId(callingUid);
19775        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19776        if (pi == null) {
19777            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19778                    + callingUserId);
19779        }
19780        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19781            throw new SecurityException("Calling uid " + callingUid
19782                    + " does not own package " + pkg);
19783        }
19784    }
19785
19786    @Override
19787    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19788        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19789            return null;
19790        }
19791        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19792    }
19793
19794    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19795        UserManagerService ums = UserManagerService.getInstance();
19796        if (ums != null) {
19797            final UserInfo parent = ums.getProfileParent(userId);
19798            final int launcherUid = (parent != null) ? parent.id : userId;
19799            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19800            if (launcherComponent != null) {
19801                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19802                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19803                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19804                        .setPackage(launcherComponent.getPackageName());
19805                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19806            }
19807        }
19808    }
19809
19810    /**
19811     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19812     * then reports the most likely home activity or null if there are more than one.
19813     */
19814    private ComponentName getDefaultHomeActivity(int userId) {
19815        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19816        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19817        if (cn != null) {
19818            return cn;
19819        }
19820
19821        // Find the launcher with the highest priority and return that component if there are no
19822        // other home activity with the same priority.
19823        int lastPriority = Integer.MIN_VALUE;
19824        ComponentName lastComponent = null;
19825        final int size = allHomeCandidates.size();
19826        for (int i = 0; i < size; i++) {
19827            final ResolveInfo ri = allHomeCandidates.get(i);
19828            if (ri.priority > lastPriority) {
19829                lastComponent = ri.activityInfo.getComponentName();
19830                lastPriority = ri.priority;
19831            } else if (ri.priority == lastPriority) {
19832                // Two components found with same priority.
19833                lastComponent = null;
19834            }
19835        }
19836        return lastComponent;
19837    }
19838
19839    private Intent getHomeIntent() {
19840        Intent intent = new Intent(Intent.ACTION_MAIN);
19841        intent.addCategory(Intent.CATEGORY_HOME);
19842        intent.addCategory(Intent.CATEGORY_DEFAULT);
19843        return intent;
19844    }
19845
19846    private IntentFilter getHomeFilter() {
19847        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19848        filter.addCategory(Intent.CATEGORY_HOME);
19849        filter.addCategory(Intent.CATEGORY_DEFAULT);
19850        return filter;
19851    }
19852
19853    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19854            int userId) {
19855        Intent intent  = getHomeIntent();
19856        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19857                PackageManager.GET_META_DATA, userId);
19858        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19859                true, false, false, userId);
19860
19861        allHomeCandidates.clear();
19862        if (list != null) {
19863            for (ResolveInfo ri : list) {
19864                allHomeCandidates.add(ri);
19865            }
19866        }
19867        return (preferred == null || preferred.activityInfo == null)
19868                ? null
19869                : new ComponentName(preferred.activityInfo.packageName,
19870                        preferred.activityInfo.name);
19871    }
19872
19873    @Override
19874    public void setHomeActivity(ComponentName comp, int userId) {
19875        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19876            return;
19877        }
19878        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19879        getHomeActivitiesAsUser(homeActivities, userId);
19880
19881        boolean found = false;
19882
19883        final int size = homeActivities.size();
19884        final ComponentName[] set = new ComponentName[size];
19885        for (int i = 0; i < size; i++) {
19886            final ResolveInfo candidate = homeActivities.get(i);
19887            final ActivityInfo info = candidate.activityInfo;
19888            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19889            set[i] = activityName;
19890            if (!found && activityName.equals(comp)) {
19891                found = true;
19892            }
19893        }
19894        if (!found) {
19895            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19896                    + userId);
19897        }
19898        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19899                set, comp, userId);
19900    }
19901
19902    private @Nullable String getSetupWizardPackageName() {
19903        final Intent intent = new Intent(Intent.ACTION_MAIN);
19904        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19905
19906        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19907                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19908                        | MATCH_DISABLED_COMPONENTS,
19909                UserHandle.myUserId());
19910        if (matches.size() == 1) {
19911            return matches.get(0).getComponentInfo().packageName;
19912        } else {
19913            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19914                    + ": matches=" + matches);
19915            return null;
19916        }
19917    }
19918
19919    private @Nullable String getStorageManagerPackageName() {
19920        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19921
19922        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19923                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19924                        | MATCH_DISABLED_COMPONENTS,
19925                UserHandle.myUserId());
19926        if (matches.size() == 1) {
19927            return matches.get(0).getComponentInfo().packageName;
19928        } else {
19929            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19930                    + matches.size() + ": matches=" + matches);
19931            return null;
19932        }
19933    }
19934
19935    @Override
19936    public void setApplicationEnabledSetting(String appPackageName,
19937            int newState, int flags, int userId, String callingPackage) {
19938        if (!sUserManager.exists(userId)) return;
19939        if (callingPackage == null) {
19940            callingPackage = Integer.toString(Binder.getCallingUid());
19941        }
19942        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19943    }
19944
19945    @Override
19946    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19947        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19948        synchronized (mPackages) {
19949            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19950            if (pkgSetting != null) {
19951                pkgSetting.setUpdateAvailable(updateAvailable);
19952            }
19953        }
19954    }
19955
19956    @Override
19957    public void setComponentEnabledSetting(ComponentName componentName,
19958            int newState, int flags, int userId) {
19959        if (!sUserManager.exists(userId)) return;
19960        setEnabledSetting(componentName.getPackageName(),
19961                componentName.getClassName(), newState, flags, userId, null);
19962    }
19963
19964    private void setEnabledSetting(final String packageName, String className, int newState,
19965            final int flags, int userId, String callingPackage) {
19966        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19967              || newState == COMPONENT_ENABLED_STATE_ENABLED
19968              || newState == COMPONENT_ENABLED_STATE_DISABLED
19969              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19970              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19971            throw new IllegalArgumentException("Invalid new component state: "
19972                    + newState);
19973        }
19974        PackageSetting pkgSetting;
19975        final int callingUid = Binder.getCallingUid();
19976        final int permission;
19977        if (callingUid == Process.SYSTEM_UID) {
19978            permission = PackageManager.PERMISSION_GRANTED;
19979        } else {
19980            permission = mContext.checkCallingOrSelfPermission(
19981                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19982        }
19983        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19984                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19985        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19986        boolean sendNow = false;
19987        boolean isApp = (className == null);
19988        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19989        String componentName = isApp ? packageName : className;
19990        int packageUid = -1;
19991        ArrayList<String> components;
19992
19993        // reader
19994        synchronized (mPackages) {
19995            pkgSetting = mSettings.mPackages.get(packageName);
19996            if (pkgSetting == null) {
19997                if (!isCallerInstantApp) {
19998                    if (className == null) {
19999                        throw new IllegalArgumentException("Unknown package: " + packageName);
20000                    }
20001                    throw new IllegalArgumentException(
20002                            "Unknown component: " + packageName + "/" + className);
20003                } else {
20004                    // throw SecurityException to prevent leaking package information
20005                    throw new SecurityException(
20006                            "Attempt to change component state; "
20007                            + "pid=" + Binder.getCallingPid()
20008                            + ", uid=" + callingUid
20009                            + (className == null
20010                                    ? ", package=" + packageName
20011                                    : ", component=" + packageName + "/" + className));
20012                }
20013            }
20014        }
20015
20016        // Limit who can change which apps
20017        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20018            // Don't allow apps that don't have permission to modify other apps
20019            if (!allowedByPermission
20020                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20021                throw new SecurityException(
20022                        "Attempt to change component state; "
20023                        + "pid=" + Binder.getCallingPid()
20024                        + ", uid=" + callingUid
20025                        + (className == null
20026                                ? ", package=" + packageName
20027                                : ", component=" + packageName + "/" + className));
20028            }
20029            // Don't allow changing protected packages.
20030            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20031                throw new SecurityException("Cannot disable a protected package: " + packageName);
20032            }
20033        }
20034
20035        synchronized (mPackages) {
20036            if (callingUid == Process.SHELL_UID
20037                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20038                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20039                // unless it is a test package.
20040                int oldState = pkgSetting.getEnabled(userId);
20041                if (className == null
20042                        &&
20043                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20044                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20045                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20046                        &&
20047                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20048                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20049                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20050                    // ok
20051                } else {
20052                    throw new SecurityException(
20053                            "Shell cannot change component state for " + packageName + "/"
20054                                    + className + " to " + newState);
20055                }
20056            }
20057        }
20058        if (className == null) {
20059            // We're dealing with an application/package level state change
20060            synchronized (mPackages) {
20061                if (pkgSetting.getEnabled(userId) == newState) {
20062                    // Nothing to do
20063                    return;
20064                }
20065            }
20066            // If we're enabling a system stub, there's a little more work to do.
20067            // Prior to enabling the package, we need to decompress the APK(s) to the
20068            // data partition and then replace the version on the system partition.
20069            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20070            final boolean isSystemStub = deletedPkg.isStub
20071                    && deletedPkg.isSystem();
20072            if (isSystemStub
20073                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20074                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20075                final File codePath = decompressPackage(deletedPkg);
20076                if (codePath == null) {
20077                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20078                    return;
20079                }
20080                // TODO remove direct parsing of the package object during internal cleanup
20081                // of scan package
20082                // We need to call parse directly here for no other reason than we need
20083                // the new package in order to disable the old one [we use the information
20084                // for some internal optimization to optionally create a new package setting
20085                // object on replace]. However, we can't get the package from the scan
20086                // because the scan modifies live structures and we need to remove the
20087                // old [system] package from the system before a scan can be attempted.
20088                // Once scan is indempotent we can remove this parse and use the package
20089                // object we scanned, prior to adding it to package settings.
20090                final PackageParser pp = new PackageParser();
20091                pp.setSeparateProcesses(mSeparateProcesses);
20092                pp.setDisplayMetrics(mMetrics);
20093                pp.setCallback(mPackageParserCallback);
20094                final PackageParser.Package tmpPkg;
20095                try {
20096                    final @ParseFlags int parseFlags = mDefParseFlags
20097                            | PackageParser.PARSE_MUST_BE_APK
20098                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20099                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20100                } catch (PackageParserException e) {
20101                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20102                    return;
20103                }
20104                synchronized (mInstallLock) {
20105                    // Disable the stub and remove any package entries
20106                    removePackageLI(deletedPkg, true);
20107                    synchronized (mPackages) {
20108                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20109                    }
20110                    final PackageParser.Package pkg;
20111                    try (PackageFreezer freezer =
20112                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20113                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20114                                | PackageParser.PARSE_ENFORCE_CODE;
20115                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20116                                0 /*currentTime*/, null /*user*/);
20117                        prepareAppDataAfterInstallLIF(pkg);
20118                        synchronized (mPackages) {
20119                            try {
20120                                updateSharedLibrariesLPr(pkg, null);
20121                            } catch (PackageManagerException e) {
20122                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20123                            }
20124                            mPermissionManager.updatePermissions(
20125                                    pkg.packageName, pkg, true, mPackages.values(),
20126                                    mPermissionCallback);
20127                            mSettings.writeLPr();
20128                        }
20129                    } catch (PackageManagerException e) {
20130                        // Whoops! Something went wrong; try to roll back to the stub
20131                        Slog.w(TAG, "Failed to install compressed system package:"
20132                                + pkgSetting.name, e);
20133                        // Remove the failed install
20134                        removeCodePathLI(codePath);
20135
20136                        // Install the system package
20137                        try (PackageFreezer freezer =
20138                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20139                            synchronized (mPackages) {
20140                                // NOTE: The system package always needs to be enabled; even
20141                                // if it's for a compressed stub. If we don't, installing the
20142                                // system package fails during scan [scanning checks the disabled
20143                                // packages]. We will reverse this later, after we've "installed"
20144                                // the stub.
20145                                // This leaves us in a fragile state; the stub should never be
20146                                // enabled, so, cross your fingers and hope nothing goes wrong
20147                                // until we can disable the package later.
20148                                enableSystemPackageLPw(deletedPkg);
20149                            }
20150                            installPackageFromSystemLIF(deletedPkg.codePath,
20151                                    false /*isPrivileged*/, null /*allUserHandles*/,
20152                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20153                                    true /*writeSettings*/);
20154                        } catch (PackageManagerException pme) {
20155                            Slog.w(TAG, "Failed to restore system package:"
20156                                    + deletedPkg.packageName, pme);
20157                        } finally {
20158                            synchronized (mPackages) {
20159                                mSettings.disableSystemPackageLPw(
20160                                        deletedPkg.packageName, true /*replaced*/);
20161                                mSettings.writeLPr();
20162                            }
20163                        }
20164                        return;
20165                    }
20166                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20167                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20168                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20169                    mDexManager.notifyPackageUpdated(pkg.packageName,
20170                            pkg.baseCodePath, pkg.splitCodePaths);
20171                }
20172            }
20173            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20174                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20175                // Don't care about who enables an app.
20176                callingPackage = null;
20177            }
20178            synchronized (mPackages) {
20179                pkgSetting.setEnabled(newState, userId, callingPackage);
20180            }
20181        } else {
20182            synchronized (mPackages) {
20183                // We're dealing with a component level state change
20184                // First, verify that this is a valid class name.
20185                PackageParser.Package pkg = pkgSetting.pkg;
20186                if (pkg == null || !pkg.hasComponentClassName(className)) {
20187                    if (pkg != null &&
20188                            pkg.applicationInfo.targetSdkVersion >=
20189                                    Build.VERSION_CODES.JELLY_BEAN) {
20190                        throw new IllegalArgumentException("Component class " + className
20191                                + " does not exist in " + packageName);
20192                    } else {
20193                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20194                                + className + " does not exist in " + packageName);
20195                    }
20196                }
20197                switch (newState) {
20198                    case COMPONENT_ENABLED_STATE_ENABLED:
20199                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20200                            return;
20201                        }
20202                        break;
20203                    case COMPONENT_ENABLED_STATE_DISABLED:
20204                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20205                            return;
20206                        }
20207                        break;
20208                    case COMPONENT_ENABLED_STATE_DEFAULT:
20209                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20210                            return;
20211                        }
20212                        break;
20213                    default:
20214                        Slog.e(TAG, "Invalid new component state: " + newState);
20215                        return;
20216                }
20217            }
20218        }
20219        synchronized (mPackages) {
20220            scheduleWritePackageRestrictionsLocked(userId);
20221            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20222            final long callingId = Binder.clearCallingIdentity();
20223            try {
20224                updateInstantAppInstallerLocked(packageName);
20225            } finally {
20226                Binder.restoreCallingIdentity(callingId);
20227            }
20228            components = mPendingBroadcasts.get(userId, packageName);
20229            final boolean newPackage = components == null;
20230            if (newPackage) {
20231                components = new ArrayList<String>();
20232            }
20233            if (!components.contains(componentName)) {
20234                components.add(componentName);
20235            }
20236            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20237                sendNow = true;
20238                // Purge entry from pending broadcast list if another one exists already
20239                // since we are sending one right away.
20240                mPendingBroadcasts.remove(userId, packageName);
20241            } else {
20242                if (newPackage) {
20243                    mPendingBroadcasts.put(userId, packageName, components);
20244                }
20245                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20246                    // Schedule a message
20247                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20248                }
20249            }
20250        }
20251
20252        long callingId = Binder.clearCallingIdentity();
20253        try {
20254            if (sendNow) {
20255                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20256                sendPackageChangedBroadcast(packageName,
20257                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20258            }
20259        } finally {
20260            Binder.restoreCallingIdentity(callingId);
20261        }
20262    }
20263
20264    @Override
20265    public void flushPackageRestrictionsAsUser(int userId) {
20266        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20267            return;
20268        }
20269        if (!sUserManager.exists(userId)) {
20270            return;
20271        }
20272        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20273                false /* checkShell */, "flushPackageRestrictions");
20274        synchronized (mPackages) {
20275            mSettings.writePackageRestrictionsLPr(userId);
20276            mDirtyUsers.remove(userId);
20277            if (mDirtyUsers.isEmpty()) {
20278                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20279            }
20280        }
20281    }
20282
20283    private void sendPackageChangedBroadcast(String packageName,
20284            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20285        if (DEBUG_INSTALL)
20286            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20287                    + componentNames);
20288        Bundle extras = new Bundle(4);
20289        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20290        String nameList[] = new String[componentNames.size()];
20291        componentNames.toArray(nameList);
20292        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20293        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20294        extras.putInt(Intent.EXTRA_UID, packageUid);
20295        // If this is not reporting a change of the overall package, then only send it
20296        // to registered receivers.  We don't want to launch a swath of apps for every
20297        // little component state change.
20298        final int flags = !componentNames.contains(packageName)
20299                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20300        final int userId = UserHandle.getUserId(packageUid);
20301        final boolean isInstantApp = isInstantApp(packageName, userId);
20302        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20303        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20304        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20305                userIds, instantUserIds);
20306    }
20307
20308    @Override
20309    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20310        if (!sUserManager.exists(userId)) return;
20311        final int callingUid = Binder.getCallingUid();
20312        if (getInstantAppPackageName(callingUid) != null) {
20313            return;
20314        }
20315        final int permission = mContext.checkCallingOrSelfPermission(
20316                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20317        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20318        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20319                true /* requireFullPermission */, true /* checkShell */, "stop package");
20320        // writer
20321        synchronized (mPackages) {
20322            final PackageSetting ps = mSettings.mPackages.get(packageName);
20323            if (!filterAppAccessLPr(ps, callingUid, userId)
20324                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20325                            allowedByPermission, callingUid, userId)) {
20326                scheduleWritePackageRestrictionsLocked(userId);
20327            }
20328        }
20329    }
20330
20331    @Override
20332    public String getInstallerPackageName(String packageName) {
20333        final int callingUid = Binder.getCallingUid();
20334        if (getInstantAppPackageName(callingUid) != null) {
20335            return null;
20336        }
20337        // reader
20338        synchronized (mPackages) {
20339            final PackageSetting ps = mSettings.mPackages.get(packageName);
20340            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20341                return null;
20342            }
20343            return mSettings.getInstallerPackageNameLPr(packageName);
20344        }
20345    }
20346
20347    public boolean isOrphaned(String packageName) {
20348        // reader
20349        synchronized (mPackages) {
20350            return mSettings.isOrphaned(packageName);
20351        }
20352    }
20353
20354    @Override
20355    public int getApplicationEnabledSetting(String packageName, int userId) {
20356        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20357        int callingUid = Binder.getCallingUid();
20358        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20359                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20360        // reader
20361        synchronized (mPackages) {
20362            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20363                return COMPONENT_ENABLED_STATE_DISABLED;
20364            }
20365            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20366        }
20367    }
20368
20369    @Override
20370    public int getComponentEnabledSetting(ComponentName component, int userId) {
20371        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20372        int callingUid = Binder.getCallingUid();
20373        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20374                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20375        synchronized (mPackages) {
20376            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20377                    component, TYPE_UNKNOWN, userId)) {
20378                return COMPONENT_ENABLED_STATE_DISABLED;
20379            }
20380            return mSettings.getComponentEnabledSettingLPr(component, userId);
20381        }
20382    }
20383
20384    @Override
20385    public void enterSafeMode() {
20386        enforceSystemOrRoot("Only the system can request entering safe mode");
20387
20388        if (!mSystemReady) {
20389            mSafeMode = true;
20390        }
20391    }
20392
20393    @Override
20394    public void systemReady() {
20395        enforceSystemOrRoot("Only the system can claim the system is ready");
20396
20397        mSystemReady = true;
20398        final ContentResolver resolver = mContext.getContentResolver();
20399        ContentObserver co = new ContentObserver(mHandler) {
20400            @Override
20401            public void onChange(boolean selfChange) {
20402                mEphemeralAppsDisabled =
20403                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20404                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20405            }
20406        };
20407        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20408                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20409                false, co, UserHandle.USER_SYSTEM);
20410        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20411                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20412        co.onChange(true);
20413
20414        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20415        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20416        // it is done.
20417        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20418            @Override
20419            public void onChange(boolean selfChange) {
20420                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20421                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20422                        oobEnabled == 1 ? "true" : "false");
20423            }
20424        };
20425        mContext.getContentResolver().registerContentObserver(
20426                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20427                UserHandle.USER_SYSTEM);
20428        // At boot, restore the value from the setting, which persists across reboot.
20429        privAppOobObserver.onChange(true);
20430
20431        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20432        // disabled after already being started.
20433        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20434                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20435
20436        // Read the compatibilty setting when the system is ready.
20437        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20438                mContext.getContentResolver(),
20439                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20440        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20441        if (DEBUG_SETTINGS) {
20442            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20443        }
20444
20445        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20446
20447        synchronized (mPackages) {
20448            // Verify that all of the preferred activity components actually
20449            // exist.  It is possible for applications to be updated and at
20450            // that point remove a previously declared activity component that
20451            // had been set as a preferred activity.  We try to clean this up
20452            // the next time we encounter that preferred activity, but it is
20453            // possible for the user flow to never be able to return to that
20454            // situation so here we do a sanity check to make sure we haven't
20455            // left any junk around.
20456            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20457            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20458                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20459                removed.clear();
20460                for (PreferredActivity pa : pir.filterSet()) {
20461                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20462                        removed.add(pa);
20463                    }
20464                }
20465                if (removed.size() > 0) {
20466                    for (int r=0; r<removed.size(); r++) {
20467                        PreferredActivity pa = removed.get(r);
20468                        Slog.w(TAG, "Removing dangling preferred activity: "
20469                                + pa.mPref.mComponent);
20470                        pir.removeFilter(pa);
20471                    }
20472                    mSettings.writePackageRestrictionsLPr(
20473                            mSettings.mPreferredActivities.keyAt(i));
20474                }
20475            }
20476
20477            for (int userId : UserManagerService.getInstance().getUserIds()) {
20478                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20479                    grantPermissionsUserIds = ArrayUtils.appendInt(
20480                            grantPermissionsUserIds, userId);
20481                }
20482            }
20483        }
20484        sUserManager.systemReady();
20485        // If we upgraded grant all default permissions before kicking off.
20486        for (int userId : grantPermissionsUserIds) {
20487            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20488        }
20489
20490        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20491            // If we did not grant default permissions, we preload from this the
20492            // default permission exceptions lazily to ensure we don't hit the
20493            // disk on a new user creation.
20494            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20495        }
20496
20497        // Now that we've scanned all packages, and granted any default
20498        // permissions, ensure permissions are updated. Beware of dragons if you
20499        // try optimizing this.
20500        synchronized (mPackages) {
20501            mPermissionManager.updateAllPermissions(
20502                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20503                    mPermissionCallback);
20504        }
20505
20506        // Kick off any messages waiting for system ready
20507        if (mPostSystemReadyMessages != null) {
20508            for (Message msg : mPostSystemReadyMessages) {
20509                msg.sendToTarget();
20510            }
20511            mPostSystemReadyMessages = null;
20512        }
20513
20514        // Watch for external volumes that come and go over time
20515        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20516        storage.registerListener(mStorageListener);
20517
20518        mInstallerService.systemReady();
20519        mPackageDexOptimizer.systemReady();
20520
20521        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20522                StorageManagerInternal.class);
20523        StorageManagerInternal.addExternalStoragePolicy(
20524                new StorageManagerInternal.ExternalStorageMountPolicy() {
20525            @Override
20526            public int getMountMode(int uid, String packageName) {
20527                if (Process.isIsolated(uid)) {
20528                    return Zygote.MOUNT_EXTERNAL_NONE;
20529                }
20530                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20531                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20532                }
20533                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20534                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20535                }
20536                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20537                    return Zygote.MOUNT_EXTERNAL_READ;
20538                }
20539                return Zygote.MOUNT_EXTERNAL_WRITE;
20540            }
20541
20542            @Override
20543            public boolean hasExternalStorage(int uid, String packageName) {
20544                return true;
20545            }
20546        });
20547
20548        // Now that we're mostly running, clean up stale users and apps
20549        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20550        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20551
20552        mPermissionManager.systemReady();
20553    }
20554
20555    public void waitForAppDataPrepared() {
20556        if (mPrepareAppDataFuture == null) {
20557            return;
20558        }
20559        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20560        mPrepareAppDataFuture = null;
20561    }
20562
20563    @Override
20564    public boolean isSafeMode() {
20565        // allow instant applications
20566        return mSafeMode;
20567    }
20568
20569    @Override
20570    public boolean hasSystemUidErrors() {
20571        // allow instant applications
20572        return mHasSystemUidErrors;
20573    }
20574
20575    static String arrayToString(int[] array) {
20576        StringBuffer buf = new StringBuffer(128);
20577        buf.append('[');
20578        if (array != null) {
20579            for (int i=0; i<array.length; i++) {
20580                if (i > 0) buf.append(", ");
20581                buf.append(array[i]);
20582            }
20583        }
20584        buf.append(']');
20585        return buf.toString();
20586    }
20587
20588    @Override
20589    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20590            FileDescriptor err, String[] args, ShellCallback callback,
20591            ResultReceiver resultReceiver) {
20592        (new PackageManagerShellCommand(this)).exec(
20593                this, in, out, err, args, callback, resultReceiver);
20594    }
20595
20596    @Override
20597    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20598        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20599
20600        DumpState dumpState = new DumpState();
20601        boolean fullPreferred = false;
20602        boolean checkin = false;
20603
20604        String packageName = null;
20605        ArraySet<String> permissionNames = null;
20606
20607        int opti = 0;
20608        while (opti < args.length) {
20609            String opt = args[opti];
20610            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20611                break;
20612            }
20613            opti++;
20614
20615            if ("-a".equals(opt)) {
20616                // Right now we only know how to print all.
20617            } else if ("-h".equals(opt)) {
20618                pw.println("Package manager dump options:");
20619                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20620                pw.println("    --checkin: dump for a checkin");
20621                pw.println("    -f: print details of intent filters");
20622                pw.println("    -h: print this help");
20623                pw.println("  cmd may be one of:");
20624                pw.println("    l[ibraries]: list known shared libraries");
20625                pw.println("    f[eatures]: list device features");
20626                pw.println("    k[eysets]: print known keysets");
20627                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20628                pw.println("    perm[issions]: dump permissions");
20629                pw.println("    permission [name ...]: dump declaration and use of given permission");
20630                pw.println("    pref[erred]: print preferred package settings");
20631                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20632                pw.println("    prov[iders]: dump content providers");
20633                pw.println("    p[ackages]: dump installed packages");
20634                pw.println("    s[hared-users]: dump shared user IDs");
20635                pw.println("    m[essages]: print collected runtime messages");
20636                pw.println("    v[erifiers]: print package verifier info");
20637                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20638                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20639                pw.println("    version: print database version info");
20640                pw.println("    write: write current settings now");
20641                pw.println("    installs: details about install sessions");
20642                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20643                pw.println("    dexopt: dump dexopt state");
20644                pw.println("    compiler-stats: dump compiler statistics");
20645                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20646                pw.println("    service-permissions: dump permissions required by services");
20647                pw.println("    <package.name>: info about given package");
20648                return;
20649            } else if ("--checkin".equals(opt)) {
20650                checkin = true;
20651            } else if ("-f".equals(opt)) {
20652                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20653            } else if ("--proto".equals(opt)) {
20654                dumpProto(fd);
20655                return;
20656            } else {
20657                pw.println("Unknown argument: " + opt + "; use -h for help");
20658            }
20659        }
20660
20661        // Is the caller requesting to dump a particular piece of data?
20662        if (opti < args.length) {
20663            String cmd = args[opti];
20664            opti++;
20665            // Is this a package name?
20666            if ("android".equals(cmd) || cmd.contains(".")) {
20667                packageName = cmd;
20668                // When dumping a single package, we always dump all of its
20669                // filter information since the amount of data will be reasonable.
20670                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20671            } else if ("check-permission".equals(cmd)) {
20672                if (opti >= args.length) {
20673                    pw.println("Error: check-permission missing permission argument");
20674                    return;
20675                }
20676                String perm = args[opti];
20677                opti++;
20678                if (opti >= args.length) {
20679                    pw.println("Error: check-permission missing package argument");
20680                    return;
20681                }
20682
20683                String pkg = args[opti];
20684                opti++;
20685                int user = UserHandle.getUserId(Binder.getCallingUid());
20686                if (opti < args.length) {
20687                    try {
20688                        user = Integer.parseInt(args[opti]);
20689                    } catch (NumberFormatException e) {
20690                        pw.println("Error: check-permission user argument is not a number: "
20691                                + args[opti]);
20692                        return;
20693                    }
20694                }
20695
20696                // Normalize package name to handle renamed packages and static libs
20697                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20698
20699                pw.println(checkPermission(perm, pkg, user));
20700                return;
20701            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20702                dumpState.setDump(DumpState.DUMP_LIBS);
20703            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20704                dumpState.setDump(DumpState.DUMP_FEATURES);
20705            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20706                if (opti >= args.length) {
20707                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20708                            | DumpState.DUMP_SERVICE_RESOLVERS
20709                            | DumpState.DUMP_RECEIVER_RESOLVERS
20710                            | DumpState.DUMP_CONTENT_RESOLVERS);
20711                } else {
20712                    while (opti < args.length) {
20713                        String name = args[opti];
20714                        if ("a".equals(name) || "activity".equals(name)) {
20715                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20716                        } else if ("s".equals(name) || "service".equals(name)) {
20717                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20718                        } else if ("r".equals(name) || "receiver".equals(name)) {
20719                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20720                        } else if ("c".equals(name) || "content".equals(name)) {
20721                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20722                        } else {
20723                            pw.println("Error: unknown resolver table type: " + name);
20724                            return;
20725                        }
20726                        opti++;
20727                    }
20728                }
20729            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20730                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20731            } else if ("permission".equals(cmd)) {
20732                if (opti >= args.length) {
20733                    pw.println("Error: permission requires permission name");
20734                    return;
20735                }
20736                permissionNames = new ArraySet<>();
20737                while (opti < args.length) {
20738                    permissionNames.add(args[opti]);
20739                    opti++;
20740                }
20741                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20742                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20743            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20744                dumpState.setDump(DumpState.DUMP_PREFERRED);
20745            } else if ("preferred-xml".equals(cmd)) {
20746                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20747                if (opti < args.length && "--full".equals(args[opti])) {
20748                    fullPreferred = true;
20749                    opti++;
20750                }
20751            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20752                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20753            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20754                dumpState.setDump(DumpState.DUMP_PACKAGES);
20755            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20756                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20757            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20758                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20759            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20760                dumpState.setDump(DumpState.DUMP_MESSAGES);
20761            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20762                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20763            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20764                    || "intent-filter-verifiers".equals(cmd)) {
20765                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20766            } else if ("version".equals(cmd)) {
20767                dumpState.setDump(DumpState.DUMP_VERSION);
20768            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20769                dumpState.setDump(DumpState.DUMP_KEYSETS);
20770            } else if ("installs".equals(cmd)) {
20771                dumpState.setDump(DumpState.DUMP_INSTALLS);
20772            } else if ("frozen".equals(cmd)) {
20773                dumpState.setDump(DumpState.DUMP_FROZEN);
20774            } else if ("volumes".equals(cmd)) {
20775                dumpState.setDump(DumpState.DUMP_VOLUMES);
20776            } else if ("dexopt".equals(cmd)) {
20777                dumpState.setDump(DumpState.DUMP_DEXOPT);
20778            } else if ("compiler-stats".equals(cmd)) {
20779                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20780            } else if ("changes".equals(cmd)) {
20781                dumpState.setDump(DumpState.DUMP_CHANGES);
20782            } else if ("service-permissions".equals(cmd)) {
20783                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
20784            } else if ("write".equals(cmd)) {
20785                synchronized (mPackages) {
20786                    mSettings.writeLPr();
20787                    pw.println("Settings written.");
20788                    return;
20789                }
20790            }
20791        }
20792
20793        if (checkin) {
20794            pw.println("vers,1");
20795        }
20796
20797        // reader
20798        synchronized (mPackages) {
20799            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20800                if (!checkin) {
20801                    if (dumpState.onTitlePrinted())
20802                        pw.println();
20803                    pw.println("Database versions:");
20804                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20805                }
20806            }
20807
20808            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20809                if (!checkin) {
20810                    if (dumpState.onTitlePrinted())
20811                        pw.println();
20812                    pw.println("Verifiers:");
20813                    pw.print("  Required: ");
20814                    pw.print(mRequiredVerifierPackage);
20815                    pw.print(" (uid=");
20816                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20817                            UserHandle.USER_SYSTEM));
20818                    pw.println(")");
20819                } else if (mRequiredVerifierPackage != null) {
20820                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20821                    pw.print(",");
20822                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20823                            UserHandle.USER_SYSTEM));
20824                }
20825            }
20826
20827            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20828                    packageName == null) {
20829                if (mIntentFilterVerifierComponent != null) {
20830                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20831                    if (!checkin) {
20832                        if (dumpState.onTitlePrinted())
20833                            pw.println();
20834                        pw.println("Intent Filter Verifier:");
20835                        pw.print("  Using: ");
20836                        pw.print(verifierPackageName);
20837                        pw.print(" (uid=");
20838                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20839                                UserHandle.USER_SYSTEM));
20840                        pw.println(")");
20841                    } else if (verifierPackageName != null) {
20842                        pw.print("ifv,"); pw.print(verifierPackageName);
20843                        pw.print(",");
20844                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20845                                UserHandle.USER_SYSTEM));
20846                    }
20847                } else {
20848                    pw.println();
20849                    pw.println("No Intent Filter Verifier available!");
20850                }
20851            }
20852
20853            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20854                boolean printedHeader = false;
20855                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20856                while (it.hasNext()) {
20857                    String libName = it.next();
20858                    LongSparseArray<SharedLibraryEntry> versionedLib
20859                            = mSharedLibraries.get(libName);
20860                    if (versionedLib == null) {
20861                        continue;
20862                    }
20863                    final int versionCount = versionedLib.size();
20864                    for (int i = 0; i < versionCount; i++) {
20865                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20866                        if (!checkin) {
20867                            if (!printedHeader) {
20868                                if (dumpState.onTitlePrinted())
20869                                    pw.println();
20870                                pw.println("Libraries:");
20871                                printedHeader = true;
20872                            }
20873                            pw.print("  ");
20874                        } else {
20875                            pw.print("lib,");
20876                        }
20877                        pw.print(libEntry.info.getName());
20878                        if (libEntry.info.isStatic()) {
20879                            pw.print(" version=" + libEntry.info.getLongVersion());
20880                        }
20881                        if (!checkin) {
20882                            pw.print(" -> ");
20883                        }
20884                        if (libEntry.path != null) {
20885                            pw.print(" (jar) ");
20886                            pw.print(libEntry.path);
20887                        } else {
20888                            pw.print(" (apk) ");
20889                            pw.print(libEntry.apk);
20890                        }
20891                        pw.println();
20892                    }
20893                }
20894            }
20895
20896            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20897                if (dumpState.onTitlePrinted())
20898                    pw.println();
20899                if (!checkin) {
20900                    pw.println("Features:");
20901                }
20902
20903                synchronized (mAvailableFeatures) {
20904                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20905                        if (checkin) {
20906                            pw.print("feat,");
20907                            pw.print(feat.name);
20908                            pw.print(",");
20909                            pw.println(feat.version);
20910                        } else {
20911                            pw.print("  ");
20912                            pw.print(feat.name);
20913                            if (feat.version > 0) {
20914                                pw.print(" version=");
20915                                pw.print(feat.version);
20916                            }
20917                            pw.println();
20918                        }
20919                    }
20920                }
20921            }
20922
20923            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20924                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20925                        : "Activity Resolver Table:", "  ", packageName,
20926                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20927                    dumpState.setTitlePrinted(true);
20928                }
20929            }
20930            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20931                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20932                        : "Receiver Resolver Table:", "  ", packageName,
20933                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20934                    dumpState.setTitlePrinted(true);
20935                }
20936            }
20937            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20938                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20939                        : "Service Resolver Table:", "  ", packageName,
20940                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20941                    dumpState.setTitlePrinted(true);
20942                }
20943            }
20944            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20945                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20946                        : "Provider Resolver Table:", "  ", packageName,
20947                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20948                    dumpState.setTitlePrinted(true);
20949                }
20950            }
20951
20952            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20953                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20954                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20955                    int user = mSettings.mPreferredActivities.keyAt(i);
20956                    if (pir.dump(pw,
20957                            dumpState.getTitlePrinted()
20958                                ? "\nPreferred Activities User " + user + ":"
20959                                : "Preferred Activities User " + user + ":", "  ",
20960                            packageName, true, false)) {
20961                        dumpState.setTitlePrinted(true);
20962                    }
20963                }
20964            }
20965
20966            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20967                pw.flush();
20968                FileOutputStream fout = new FileOutputStream(fd);
20969                BufferedOutputStream str = new BufferedOutputStream(fout);
20970                XmlSerializer serializer = new FastXmlSerializer();
20971                try {
20972                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20973                    serializer.startDocument(null, true);
20974                    serializer.setFeature(
20975                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20976                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20977                    serializer.endDocument();
20978                    serializer.flush();
20979                } catch (IllegalArgumentException e) {
20980                    pw.println("Failed writing: " + e);
20981                } catch (IllegalStateException e) {
20982                    pw.println("Failed writing: " + e);
20983                } catch (IOException e) {
20984                    pw.println("Failed writing: " + e);
20985                }
20986            }
20987
20988            if (!checkin
20989                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20990                    && packageName == null) {
20991                pw.println();
20992                int count = mSettings.mPackages.size();
20993                if (count == 0) {
20994                    pw.println("No applications!");
20995                    pw.println();
20996                } else {
20997                    final String prefix = "  ";
20998                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20999                    if (allPackageSettings.size() == 0) {
21000                        pw.println("No domain preferred apps!");
21001                        pw.println();
21002                    } else {
21003                        pw.println("App verification status:");
21004                        pw.println();
21005                        count = 0;
21006                        for (PackageSetting ps : allPackageSettings) {
21007                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21008                            if (ivi == null || ivi.getPackageName() == null) continue;
21009                            pw.println(prefix + "Package: " + ivi.getPackageName());
21010                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21011                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21012                            pw.println();
21013                            count++;
21014                        }
21015                        if (count == 0) {
21016                            pw.println(prefix + "No app verification established.");
21017                            pw.println();
21018                        }
21019                        for (int userId : sUserManager.getUserIds()) {
21020                            pw.println("App linkages for user " + userId + ":");
21021                            pw.println();
21022                            count = 0;
21023                            for (PackageSetting ps : allPackageSettings) {
21024                                final long status = ps.getDomainVerificationStatusForUser(userId);
21025                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21026                                        && !DEBUG_DOMAIN_VERIFICATION) {
21027                                    continue;
21028                                }
21029                                pw.println(prefix + "Package: " + ps.name);
21030                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21031                                String statusStr = IntentFilterVerificationInfo.
21032                                        getStatusStringFromValue(status);
21033                                pw.println(prefix + "Status:  " + statusStr);
21034                                pw.println();
21035                                count++;
21036                            }
21037                            if (count == 0) {
21038                                pw.println(prefix + "No configured app linkages.");
21039                                pw.println();
21040                            }
21041                        }
21042                    }
21043                }
21044            }
21045
21046            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21047                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21048            }
21049
21050            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21051                boolean printedSomething = false;
21052                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21053                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21054                        continue;
21055                    }
21056                    if (!printedSomething) {
21057                        if (dumpState.onTitlePrinted())
21058                            pw.println();
21059                        pw.println("Registered ContentProviders:");
21060                        printedSomething = true;
21061                    }
21062                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21063                    pw.print("    "); pw.println(p.toString());
21064                }
21065                printedSomething = false;
21066                for (Map.Entry<String, PackageParser.Provider> entry :
21067                        mProvidersByAuthority.entrySet()) {
21068                    PackageParser.Provider p = entry.getValue();
21069                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21070                        continue;
21071                    }
21072                    if (!printedSomething) {
21073                        if (dumpState.onTitlePrinted())
21074                            pw.println();
21075                        pw.println("ContentProvider Authorities:");
21076                        printedSomething = true;
21077                    }
21078                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21079                    pw.print("    "); pw.println(p.toString());
21080                    if (p.info != null && p.info.applicationInfo != null) {
21081                        final String appInfo = p.info.applicationInfo.toString();
21082                        pw.print("      applicationInfo="); pw.println(appInfo);
21083                    }
21084                }
21085            }
21086
21087            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21088                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21089            }
21090
21091            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21092                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21093            }
21094
21095            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21096                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21097            }
21098
21099            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21100                if (dumpState.onTitlePrinted()) pw.println();
21101                pw.println("Package Changes:");
21102                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21103                final int K = mChangedPackages.size();
21104                for (int i = 0; i < K; i++) {
21105                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21106                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21107                    final int N = changes.size();
21108                    if (N == 0) {
21109                        pw.print("    "); pw.println("No packages changed");
21110                    } else {
21111                        for (int j = 0; j < N; j++) {
21112                            final String pkgName = changes.valueAt(j);
21113                            final int sequenceNumber = changes.keyAt(j);
21114                            pw.print("    ");
21115                            pw.print("seq=");
21116                            pw.print(sequenceNumber);
21117                            pw.print(", package=");
21118                            pw.println(pkgName);
21119                        }
21120                    }
21121                }
21122            }
21123
21124            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21125                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21126            }
21127
21128            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21129                // XXX should handle packageName != null by dumping only install data that
21130                // the given package is involved with.
21131                if (dumpState.onTitlePrinted()) pw.println();
21132
21133                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21134                ipw.println();
21135                ipw.println("Frozen packages:");
21136                ipw.increaseIndent();
21137                if (mFrozenPackages.size() == 0) {
21138                    ipw.println("(none)");
21139                } else {
21140                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21141                        ipw.println(mFrozenPackages.valueAt(i));
21142                    }
21143                }
21144                ipw.decreaseIndent();
21145            }
21146
21147            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21148                if (dumpState.onTitlePrinted()) pw.println();
21149
21150                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21151                ipw.println();
21152                ipw.println("Loaded volumes:");
21153                ipw.increaseIndent();
21154                if (mLoadedVolumes.size() == 0) {
21155                    ipw.println("(none)");
21156                } else {
21157                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21158                        ipw.println(mLoadedVolumes.valueAt(i));
21159                    }
21160                }
21161                ipw.decreaseIndent();
21162            }
21163
21164            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21165                    && packageName == null) {
21166                if (dumpState.onTitlePrinted()) pw.println();
21167                pw.println("Service permissions:");
21168
21169                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21170                while (filterIterator.hasNext()) {
21171                    final ServiceIntentInfo info = filterIterator.next();
21172                    final ServiceInfo serviceInfo = info.service.info;
21173                    final String permission = serviceInfo.permission;
21174                    if (permission != null) {
21175                        pw.print("    ");
21176                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21177                        pw.print(": ");
21178                        pw.println(permission);
21179                    }
21180                }
21181            }
21182
21183            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21184                if (dumpState.onTitlePrinted()) pw.println();
21185                dumpDexoptStateLPr(pw, packageName);
21186            }
21187
21188            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21189                if (dumpState.onTitlePrinted()) pw.println();
21190                dumpCompilerStatsLPr(pw, packageName);
21191            }
21192
21193            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21194                if (dumpState.onTitlePrinted()) pw.println();
21195                mSettings.dumpReadMessagesLPr(pw, dumpState);
21196
21197                pw.println();
21198                pw.println("Package warning messages:");
21199                dumpCriticalInfo(pw, null);
21200            }
21201
21202            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21203                dumpCriticalInfo(pw, "msg,");
21204            }
21205        }
21206
21207        // PackageInstaller should be called outside of mPackages lock
21208        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21209            // XXX should handle packageName != null by dumping only install data that
21210            // the given package is involved with.
21211            if (dumpState.onTitlePrinted()) pw.println();
21212            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21213        }
21214    }
21215
21216    private void dumpProto(FileDescriptor fd) {
21217        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21218
21219        synchronized (mPackages) {
21220            final long requiredVerifierPackageToken =
21221                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21222            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21223            proto.write(
21224                    PackageServiceDumpProto.PackageShortProto.UID,
21225                    getPackageUid(
21226                            mRequiredVerifierPackage,
21227                            MATCH_DEBUG_TRIAGED_MISSING,
21228                            UserHandle.USER_SYSTEM));
21229            proto.end(requiredVerifierPackageToken);
21230
21231            if (mIntentFilterVerifierComponent != null) {
21232                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21233                final long verifierPackageToken =
21234                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21235                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21236                proto.write(
21237                        PackageServiceDumpProto.PackageShortProto.UID,
21238                        getPackageUid(
21239                                verifierPackageName,
21240                                MATCH_DEBUG_TRIAGED_MISSING,
21241                                UserHandle.USER_SYSTEM));
21242                proto.end(verifierPackageToken);
21243            }
21244
21245            dumpSharedLibrariesProto(proto);
21246            dumpFeaturesProto(proto);
21247            mSettings.dumpPackagesProto(proto);
21248            mSettings.dumpSharedUsersProto(proto);
21249            dumpCriticalInfo(proto);
21250        }
21251        proto.flush();
21252    }
21253
21254    private void dumpFeaturesProto(ProtoOutputStream proto) {
21255        synchronized (mAvailableFeatures) {
21256            final int count = mAvailableFeatures.size();
21257            for (int i = 0; i < count; i++) {
21258                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21259            }
21260        }
21261    }
21262
21263    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21264        final int count = mSharedLibraries.size();
21265        for (int i = 0; i < count; i++) {
21266            final String libName = mSharedLibraries.keyAt(i);
21267            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21268            if (versionedLib == null) {
21269                continue;
21270            }
21271            final int versionCount = versionedLib.size();
21272            for (int j = 0; j < versionCount; j++) {
21273                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21274                final long sharedLibraryToken =
21275                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21276                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21277                final boolean isJar = (libEntry.path != null);
21278                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21279                if (isJar) {
21280                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21281                } else {
21282                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21283                }
21284                proto.end(sharedLibraryToken);
21285            }
21286        }
21287    }
21288
21289    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21290        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21291        ipw.println();
21292        ipw.println("Dexopt state:");
21293        ipw.increaseIndent();
21294        Collection<PackageParser.Package> packages = null;
21295        if (packageName != null) {
21296            PackageParser.Package targetPackage = mPackages.get(packageName);
21297            if (targetPackage != null) {
21298                packages = Collections.singletonList(targetPackage);
21299            } else {
21300                ipw.println("Unable to find package: " + packageName);
21301                return;
21302            }
21303        } else {
21304            packages = mPackages.values();
21305        }
21306
21307        for (PackageParser.Package pkg : packages) {
21308            ipw.println("[" + pkg.packageName + "]");
21309            ipw.increaseIndent();
21310            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21311                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21312            ipw.decreaseIndent();
21313        }
21314    }
21315
21316    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21317        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21318        ipw.println();
21319        ipw.println("Compiler stats:");
21320        ipw.increaseIndent();
21321        Collection<PackageParser.Package> packages = null;
21322        if (packageName != null) {
21323            PackageParser.Package targetPackage = mPackages.get(packageName);
21324            if (targetPackage != null) {
21325                packages = Collections.singletonList(targetPackage);
21326            } else {
21327                ipw.println("Unable to find package: " + packageName);
21328                return;
21329            }
21330        } else {
21331            packages = mPackages.values();
21332        }
21333
21334        for (PackageParser.Package pkg : packages) {
21335            ipw.println("[" + pkg.packageName + "]");
21336            ipw.increaseIndent();
21337
21338            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21339            if (stats == null) {
21340                ipw.println("(No recorded stats)");
21341            } else {
21342                stats.dump(ipw);
21343            }
21344            ipw.decreaseIndent();
21345        }
21346    }
21347
21348    private String dumpDomainString(String packageName) {
21349        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21350                .getList();
21351        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21352
21353        ArraySet<String> result = new ArraySet<>();
21354        if (iviList.size() > 0) {
21355            for (IntentFilterVerificationInfo ivi : iviList) {
21356                for (String host : ivi.getDomains()) {
21357                    result.add(host);
21358                }
21359            }
21360        }
21361        if (filters != null && filters.size() > 0) {
21362            for (IntentFilter filter : filters) {
21363                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21364                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21365                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21366                    result.addAll(filter.getHostsList());
21367                }
21368            }
21369        }
21370
21371        StringBuilder sb = new StringBuilder(result.size() * 16);
21372        for (String domain : result) {
21373            if (sb.length() > 0) sb.append(" ");
21374            sb.append(domain);
21375        }
21376        return sb.toString();
21377    }
21378
21379    // ------- apps on sdcard specific code -------
21380    static final boolean DEBUG_SD_INSTALL = false;
21381
21382    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21383
21384    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21385
21386    private boolean mMediaMounted = false;
21387
21388    static String getEncryptKey() {
21389        try {
21390            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21391                    SD_ENCRYPTION_KEYSTORE_NAME);
21392            if (sdEncKey == null) {
21393                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21394                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21395                if (sdEncKey == null) {
21396                    Slog.e(TAG, "Failed to create encryption keys");
21397                    return null;
21398                }
21399            }
21400            return sdEncKey;
21401        } catch (NoSuchAlgorithmException nsae) {
21402            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21403            return null;
21404        } catch (IOException ioe) {
21405            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21406            return null;
21407        }
21408    }
21409
21410    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21411            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21412        final int size = infos.size();
21413        final String[] packageNames = new String[size];
21414        final int[] packageUids = new int[size];
21415        for (int i = 0; i < size; i++) {
21416            final ApplicationInfo info = infos.get(i);
21417            packageNames[i] = info.packageName;
21418            packageUids[i] = info.uid;
21419        }
21420        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21421                finishedReceiver);
21422    }
21423
21424    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21425            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21426        sendResourcesChangedBroadcast(mediaStatus, replacing,
21427                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21428    }
21429
21430    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21431            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21432        int size = pkgList.length;
21433        if (size > 0) {
21434            // Send broadcasts here
21435            Bundle extras = new Bundle();
21436            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21437            if (uidArr != null) {
21438                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21439            }
21440            if (replacing) {
21441                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21442            }
21443            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21444                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21445            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21446        }
21447    }
21448
21449    private void loadPrivatePackages(final VolumeInfo vol) {
21450        mHandler.post(new Runnable() {
21451            @Override
21452            public void run() {
21453                loadPrivatePackagesInner(vol);
21454            }
21455        });
21456    }
21457
21458    private void loadPrivatePackagesInner(VolumeInfo vol) {
21459        final String volumeUuid = vol.fsUuid;
21460        if (TextUtils.isEmpty(volumeUuid)) {
21461            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21462            return;
21463        }
21464
21465        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21466        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21467        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21468
21469        final VersionInfo ver;
21470        final List<PackageSetting> packages;
21471        synchronized (mPackages) {
21472            ver = mSettings.findOrCreateVersion(volumeUuid);
21473            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21474        }
21475
21476        for (PackageSetting ps : packages) {
21477            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21478            synchronized (mInstallLock) {
21479                final PackageParser.Package pkg;
21480                try {
21481                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21482                    loaded.add(pkg.applicationInfo);
21483
21484                } catch (PackageManagerException e) {
21485                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21486                }
21487
21488                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21489                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21490                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21491                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21492                }
21493            }
21494        }
21495
21496        // Reconcile app data for all started/unlocked users
21497        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21498        final UserManager um = mContext.getSystemService(UserManager.class);
21499        UserManagerInternal umInternal = getUserManagerInternal();
21500        for (UserInfo user : um.getUsers()) {
21501            final int flags;
21502            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21503                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21504            } else if (umInternal.isUserRunning(user.id)) {
21505                flags = StorageManager.FLAG_STORAGE_DE;
21506            } else {
21507                continue;
21508            }
21509
21510            try {
21511                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21512                synchronized (mInstallLock) {
21513                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21514                }
21515            } catch (IllegalStateException e) {
21516                // Device was probably ejected, and we'll process that event momentarily
21517                Slog.w(TAG, "Failed to prepare storage: " + e);
21518            }
21519        }
21520
21521        synchronized (mPackages) {
21522            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21523            if (sdkUpdated) {
21524                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21525                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21526            }
21527            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21528                    mPermissionCallback);
21529
21530            // Yay, everything is now upgraded
21531            ver.forceCurrent();
21532
21533            mSettings.writeLPr();
21534        }
21535
21536        for (PackageFreezer freezer : freezers) {
21537            freezer.close();
21538        }
21539
21540        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21541        sendResourcesChangedBroadcast(true, false, loaded, null);
21542        mLoadedVolumes.add(vol.getId());
21543    }
21544
21545    private void unloadPrivatePackages(final VolumeInfo vol) {
21546        mHandler.post(new Runnable() {
21547            @Override
21548            public void run() {
21549                unloadPrivatePackagesInner(vol);
21550            }
21551        });
21552    }
21553
21554    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21555        final String volumeUuid = vol.fsUuid;
21556        if (TextUtils.isEmpty(volumeUuid)) {
21557            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21558            return;
21559        }
21560
21561        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21562        synchronized (mInstallLock) {
21563        synchronized (mPackages) {
21564            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21565            for (PackageSetting ps : packages) {
21566                if (ps.pkg == null) continue;
21567
21568                final ApplicationInfo info = ps.pkg.applicationInfo;
21569                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21570                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21571
21572                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21573                        "unloadPrivatePackagesInner")) {
21574                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21575                            false, null)) {
21576                        unloaded.add(info);
21577                    } else {
21578                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21579                    }
21580                }
21581
21582                // Try very hard to release any references to this package
21583                // so we don't risk the system server being killed due to
21584                // open FDs
21585                AttributeCache.instance().removePackage(ps.name);
21586            }
21587
21588            mSettings.writeLPr();
21589        }
21590        }
21591
21592        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21593        sendResourcesChangedBroadcast(false, false, unloaded, null);
21594        mLoadedVolumes.remove(vol.getId());
21595
21596        // Try very hard to release any references to this path so we don't risk
21597        // the system server being killed due to open FDs
21598        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21599
21600        for (int i = 0; i < 3; i++) {
21601            System.gc();
21602            System.runFinalization();
21603        }
21604    }
21605
21606    private void assertPackageKnown(String volumeUuid, String packageName)
21607            throws PackageManagerException {
21608        synchronized (mPackages) {
21609            // Normalize package name to handle renamed packages
21610            packageName = normalizePackageNameLPr(packageName);
21611
21612            final PackageSetting ps = mSettings.mPackages.get(packageName);
21613            if (ps == null) {
21614                throw new PackageManagerException("Package " + packageName + " is unknown");
21615            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21616                throw new PackageManagerException(
21617                        "Package " + packageName + " found on unknown volume " + volumeUuid
21618                                + "; expected volume " + ps.volumeUuid);
21619            }
21620        }
21621    }
21622
21623    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21624            throws PackageManagerException {
21625        synchronized (mPackages) {
21626            // Normalize package name to handle renamed packages
21627            packageName = normalizePackageNameLPr(packageName);
21628
21629            final PackageSetting ps = mSettings.mPackages.get(packageName);
21630            if (ps == null) {
21631                throw new PackageManagerException("Package " + packageName + " is unknown");
21632            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21633                throw new PackageManagerException(
21634                        "Package " + packageName + " found on unknown volume " + volumeUuid
21635                                + "; expected volume " + ps.volumeUuid);
21636            } else if (!ps.getInstalled(userId)) {
21637                throw new PackageManagerException(
21638                        "Package " + packageName + " not installed for user " + userId);
21639            }
21640        }
21641    }
21642
21643    private List<String> collectAbsoluteCodePaths() {
21644        synchronized (mPackages) {
21645            List<String> codePaths = new ArrayList<>();
21646            final int packageCount = mSettings.mPackages.size();
21647            for (int i = 0; i < packageCount; i++) {
21648                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21649                codePaths.add(ps.codePath.getAbsolutePath());
21650            }
21651            return codePaths;
21652        }
21653    }
21654
21655    /**
21656     * Examine all apps present on given mounted volume, and destroy apps that
21657     * aren't expected, either due to uninstallation or reinstallation on
21658     * another volume.
21659     */
21660    private void reconcileApps(String volumeUuid) {
21661        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21662        List<File> filesToDelete = null;
21663
21664        final File[] files = FileUtils.listFilesOrEmpty(
21665                Environment.getDataAppDirectory(volumeUuid));
21666        for (File file : files) {
21667            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21668                    && !PackageInstallerService.isStageName(file.getName());
21669            if (!isPackage) {
21670                // Ignore entries which are not packages
21671                continue;
21672            }
21673
21674            String absolutePath = file.getAbsolutePath();
21675
21676            boolean pathValid = false;
21677            final int absoluteCodePathCount = absoluteCodePaths.size();
21678            for (int i = 0; i < absoluteCodePathCount; i++) {
21679                String absoluteCodePath = absoluteCodePaths.get(i);
21680                if (absolutePath.startsWith(absoluteCodePath)) {
21681                    pathValid = true;
21682                    break;
21683                }
21684            }
21685
21686            if (!pathValid) {
21687                if (filesToDelete == null) {
21688                    filesToDelete = new ArrayList<>();
21689                }
21690                filesToDelete.add(file);
21691            }
21692        }
21693
21694        if (filesToDelete != null) {
21695            final int fileToDeleteCount = filesToDelete.size();
21696            for (int i = 0; i < fileToDeleteCount; i++) {
21697                File fileToDelete = filesToDelete.get(i);
21698                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21699                synchronized (mInstallLock) {
21700                    removeCodePathLI(fileToDelete);
21701                }
21702            }
21703        }
21704    }
21705
21706    /**
21707     * Reconcile all app data for the given user.
21708     * <p>
21709     * Verifies that directories exist and that ownership and labeling is
21710     * correct for all installed apps on all mounted volumes.
21711     */
21712    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21713        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21714        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21715            final String volumeUuid = vol.getFsUuid();
21716            synchronized (mInstallLock) {
21717                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21718            }
21719        }
21720    }
21721
21722    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21723            boolean migrateAppData) {
21724        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21725    }
21726
21727    /**
21728     * Reconcile all app data on given mounted volume.
21729     * <p>
21730     * Destroys app data that isn't expected, either due to uninstallation or
21731     * reinstallation on another volume.
21732     * <p>
21733     * Verifies that directories exist and that ownership and labeling is
21734     * correct for all installed apps.
21735     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21736     */
21737    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21738            boolean migrateAppData, boolean onlyCoreApps) {
21739        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21740                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21741        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21742
21743        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21744        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21745
21746        // First look for stale data that doesn't belong, and check if things
21747        // have changed since we did our last restorecon
21748        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21749            if (StorageManager.isFileEncryptedNativeOrEmulated()
21750                    && !StorageManager.isUserKeyUnlocked(userId)) {
21751                throw new RuntimeException(
21752                        "Yikes, someone asked us to reconcile CE storage while " + userId
21753                                + " was still locked; this would have caused massive data loss!");
21754            }
21755
21756            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21757            for (File file : files) {
21758                final String packageName = file.getName();
21759                try {
21760                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21761                } catch (PackageManagerException e) {
21762                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21763                    try {
21764                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21765                                StorageManager.FLAG_STORAGE_CE, 0);
21766                    } catch (InstallerException e2) {
21767                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21768                    }
21769                }
21770            }
21771        }
21772        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21773            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21774            for (File file : files) {
21775                final String packageName = file.getName();
21776                try {
21777                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21778                } catch (PackageManagerException e) {
21779                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21780                    try {
21781                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21782                                StorageManager.FLAG_STORAGE_DE, 0);
21783                    } catch (InstallerException e2) {
21784                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21785                    }
21786                }
21787            }
21788        }
21789
21790        // Ensure that data directories are ready to roll for all packages
21791        // installed for this volume and user
21792        final List<PackageSetting> packages;
21793        synchronized (mPackages) {
21794            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21795        }
21796        int preparedCount = 0;
21797        for (PackageSetting ps : packages) {
21798            final String packageName = ps.name;
21799            if (ps.pkg == null) {
21800                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21801                // TODO: might be due to legacy ASEC apps; we should circle back
21802                // and reconcile again once they're scanned
21803                continue;
21804            }
21805            // Skip non-core apps if requested
21806            if (onlyCoreApps && !ps.pkg.coreApp) {
21807                result.add(packageName);
21808                continue;
21809            }
21810
21811            if (ps.getInstalled(userId)) {
21812                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21813                preparedCount++;
21814            }
21815        }
21816
21817        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21818        return result;
21819    }
21820
21821    /**
21822     * Prepare app data for the given app just after it was installed or
21823     * upgraded. This method carefully only touches users that it's installed
21824     * for, and it forces a restorecon to handle any seinfo changes.
21825     * <p>
21826     * Verifies that directories exist and that ownership and labeling is
21827     * correct for all installed apps. If there is an ownership mismatch, it
21828     * will try recovering system apps by wiping data; third-party app data is
21829     * left intact.
21830     * <p>
21831     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21832     */
21833    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21834        final PackageSetting ps;
21835        synchronized (mPackages) {
21836            ps = mSettings.mPackages.get(pkg.packageName);
21837            mSettings.writeKernelMappingLPr(ps);
21838        }
21839
21840        final UserManager um = mContext.getSystemService(UserManager.class);
21841        UserManagerInternal umInternal = getUserManagerInternal();
21842        for (UserInfo user : um.getUsers()) {
21843            final int flags;
21844            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21845                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21846            } else if (umInternal.isUserRunning(user.id)) {
21847                flags = StorageManager.FLAG_STORAGE_DE;
21848            } else {
21849                continue;
21850            }
21851
21852            if (ps.getInstalled(user.id)) {
21853                // TODO: when user data is locked, mark that we're still dirty
21854                prepareAppDataLIF(pkg, user.id, flags);
21855            }
21856        }
21857    }
21858
21859    /**
21860     * Prepare app data for the given app.
21861     * <p>
21862     * Verifies that directories exist and that ownership and labeling is
21863     * correct for all installed apps. If there is an ownership mismatch, this
21864     * will try recovering system apps by wiping data; third-party app data is
21865     * left intact.
21866     */
21867    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21868        if (pkg == null) {
21869            Slog.wtf(TAG, "Package was null!", new Throwable());
21870            return;
21871        }
21872        prepareAppDataLeafLIF(pkg, userId, flags);
21873        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21874        for (int i = 0; i < childCount; i++) {
21875            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21876        }
21877    }
21878
21879    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21880            boolean maybeMigrateAppData) {
21881        prepareAppDataLIF(pkg, userId, flags);
21882
21883        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21884            // We may have just shuffled around app data directories, so
21885            // prepare them one more time
21886            prepareAppDataLIF(pkg, userId, flags);
21887        }
21888    }
21889
21890    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21891        if (DEBUG_APP_DATA) {
21892            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21893                    + Integer.toHexString(flags));
21894        }
21895
21896        final String volumeUuid = pkg.volumeUuid;
21897        final String packageName = pkg.packageName;
21898        final ApplicationInfo app = pkg.applicationInfo;
21899        final int appId = UserHandle.getAppId(app.uid);
21900
21901        Preconditions.checkNotNull(app.seInfo);
21902
21903        long ceDataInode = -1;
21904        try {
21905            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21906                    appId, app.seInfo, app.targetSdkVersion);
21907        } catch (InstallerException e) {
21908            if (app.isSystemApp()) {
21909                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21910                        + ", but trying to recover: " + e);
21911                destroyAppDataLeafLIF(pkg, userId, flags);
21912                try {
21913                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21914                            appId, app.seInfo, app.targetSdkVersion);
21915                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21916                } catch (InstallerException e2) {
21917                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21918                }
21919            } else {
21920                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21921            }
21922        }
21923        // Prepare the application profiles.
21924        mArtManagerService.prepareAppProfiles(pkg, userId);
21925
21926        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21927            // TODO: mark this structure as dirty so we persist it!
21928            synchronized (mPackages) {
21929                final PackageSetting ps = mSettings.mPackages.get(packageName);
21930                if (ps != null) {
21931                    ps.setCeDataInode(ceDataInode, userId);
21932                }
21933            }
21934        }
21935
21936        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21937    }
21938
21939    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21940        if (pkg == null) {
21941            Slog.wtf(TAG, "Package was null!", new Throwable());
21942            return;
21943        }
21944        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21945        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21946        for (int i = 0; i < childCount; i++) {
21947            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21948        }
21949    }
21950
21951    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21952        final String volumeUuid = pkg.volumeUuid;
21953        final String packageName = pkg.packageName;
21954        final ApplicationInfo app = pkg.applicationInfo;
21955
21956        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21957            // Create a native library symlink only if we have native libraries
21958            // and if the native libraries are 32 bit libraries. We do not provide
21959            // this symlink for 64 bit libraries.
21960            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21961                final String nativeLibPath = app.nativeLibraryDir;
21962                try {
21963                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21964                            nativeLibPath, userId);
21965                } catch (InstallerException e) {
21966                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21967                }
21968            }
21969        }
21970    }
21971
21972    /**
21973     * For system apps on non-FBE devices, this method migrates any existing
21974     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21975     * requested by the app.
21976     */
21977    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21978        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21979                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21980            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21981                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21982            try {
21983                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21984                        storageTarget);
21985            } catch (InstallerException e) {
21986                logCriticalInfo(Log.WARN,
21987                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21988            }
21989            return true;
21990        } else {
21991            return false;
21992        }
21993    }
21994
21995    public PackageFreezer freezePackage(String packageName, String killReason) {
21996        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21997    }
21998
21999    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22000        return new PackageFreezer(packageName, userId, killReason);
22001    }
22002
22003    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22004            String killReason) {
22005        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22006    }
22007
22008    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22009            String killReason) {
22010        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22011            return new PackageFreezer();
22012        } else {
22013            return freezePackage(packageName, userId, killReason);
22014        }
22015    }
22016
22017    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22018            String killReason) {
22019        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22020    }
22021
22022    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22023            String killReason) {
22024        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22025            return new PackageFreezer();
22026        } else {
22027            return freezePackage(packageName, userId, killReason);
22028        }
22029    }
22030
22031    /**
22032     * Class that freezes and kills the given package upon creation, and
22033     * unfreezes it upon closing. This is typically used when doing surgery on
22034     * app code/data to prevent the app from running while you're working.
22035     */
22036    private class PackageFreezer implements AutoCloseable {
22037        private final String mPackageName;
22038        private final PackageFreezer[] mChildren;
22039
22040        private final boolean mWeFroze;
22041
22042        private final AtomicBoolean mClosed = new AtomicBoolean();
22043        private final CloseGuard mCloseGuard = CloseGuard.get();
22044
22045        /**
22046         * Create and return a stub freezer that doesn't actually do anything,
22047         * typically used when someone requested
22048         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22049         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22050         */
22051        public PackageFreezer() {
22052            mPackageName = null;
22053            mChildren = null;
22054            mWeFroze = false;
22055            mCloseGuard.open("close");
22056        }
22057
22058        public PackageFreezer(String packageName, int userId, String killReason) {
22059            synchronized (mPackages) {
22060                mPackageName = packageName;
22061                mWeFroze = mFrozenPackages.add(mPackageName);
22062
22063                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22064                if (ps != null) {
22065                    killApplication(ps.name, ps.appId, userId, killReason);
22066                }
22067
22068                final PackageParser.Package p = mPackages.get(packageName);
22069                if (p != null && p.childPackages != null) {
22070                    final int N = p.childPackages.size();
22071                    mChildren = new PackageFreezer[N];
22072                    for (int i = 0; i < N; i++) {
22073                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22074                                userId, killReason);
22075                    }
22076                } else {
22077                    mChildren = null;
22078                }
22079            }
22080            mCloseGuard.open("close");
22081        }
22082
22083        @Override
22084        protected void finalize() throws Throwable {
22085            try {
22086                if (mCloseGuard != null) {
22087                    mCloseGuard.warnIfOpen();
22088                }
22089
22090                close();
22091            } finally {
22092                super.finalize();
22093            }
22094        }
22095
22096        @Override
22097        public void close() {
22098            mCloseGuard.close();
22099            if (mClosed.compareAndSet(false, true)) {
22100                synchronized (mPackages) {
22101                    if (mWeFroze) {
22102                        mFrozenPackages.remove(mPackageName);
22103                    }
22104
22105                    if (mChildren != null) {
22106                        for (PackageFreezer freezer : mChildren) {
22107                            freezer.close();
22108                        }
22109                    }
22110                }
22111            }
22112        }
22113    }
22114
22115    /**
22116     * Verify that given package is currently frozen.
22117     */
22118    private void checkPackageFrozen(String packageName) {
22119        synchronized (mPackages) {
22120            if (!mFrozenPackages.contains(packageName)) {
22121                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22122            }
22123        }
22124    }
22125
22126    @Override
22127    public int movePackage(final String packageName, final String volumeUuid) {
22128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22129
22130        final int callingUid = Binder.getCallingUid();
22131        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22132        final int moveId = mNextMoveId.getAndIncrement();
22133        mHandler.post(new Runnable() {
22134            @Override
22135            public void run() {
22136                try {
22137                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22138                } catch (PackageManagerException e) {
22139                    Slog.w(TAG, "Failed to move " + packageName, e);
22140                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22141                }
22142            }
22143        });
22144        return moveId;
22145    }
22146
22147    private void movePackageInternal(final String packageName, final String volumeUuid,
22148            final int moveId, final int callingUid, UserHandle user)
22149                    throws PackageManagerException {
22150        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22151        final PackageManager pm = mContext.getPackageManager();
22152
22153        final boolean currentAsec;
22154        final String currentVolumeUuid;
22155        final File codeFile;
22156        final String installerPackageName;
22157        final String packageAbiOverride;
22158        final int appId;
22159        final String seinfo;
22160        final String label;
22161        final int targetSdkVersion;
22162        final PackageFreezer freezer;
22163        final int[] installedUserIds;
22164
22165        // reader
22166        synchronized (mPackages) {
22167            final PackageParser.Package pkg = mPackages.get(packageName);
22168            final PackageSetting ps = mSettings.mPackages.get(packageName);
22169            if (pkg == null
22170                    || ps == null
22171                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22172                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22173            }
22174            if (pkg.applicationInfo.isSystemApp()) {
22175                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22176                        "Cannot move system application");
22177            }
22178
22179            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22180            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22181                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22182            if (isInternalStorage && !allow3rdPartyOnInternal) {
22183                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22184                        "3rd party apps are not allowed on internal storage");
22185            }
22186
22187            if (pkg.applicationInfo.isExternalAsec()) {
22188                currentAsec = true;
22189                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22190            } else if (pkg.applicationInfo.isForwardLocked()) {
22191                currentAsec = true;
22192                currentVolumeUuid = "forward_locked";
22193            } else {
22194                currentAsec = false;
22195                currentVolumeUuid = ps.volumeUuid;
22196
22197                final File probe = new File(pkg.codePath);
22198                final File probeOat = new File(probe, "oat");
22199                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22200                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22201                            "Move only supported for modern cluster style installs");
22202                }
22203            }
22204
22205            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22206                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22207                        "Package already moved to " + volumeUuid);
22208            }
22209            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22210                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22211                        "Device admin cannot be moved");
22212            }
22213
22214            if (mFrozenPackages.contains(packageName)) {
22215                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22216                        "Failed to move already frozen package");
22217            }
22218
22219            codeFile = new File(pkg.codePath);
22220            installerPackageName = ps.installerPackageName;
22221            packageAbiOverride = ps.cpuAbiOverrideString;
22222            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22223            seinfo = pkg.applicationInfo.seInfo;
22224            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22225            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22226            freezer = freezePackage(packageName, "movePackageInternal");
22227            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22228        }
22229
22230        final Bundle extras = new Bundle();
22231        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22232        extras.putString(Intent.EXTRA_TITLE, label);
22233        mMoveCallbacks.notifyCreated(moveId, extras);
22234
22235        int installFlags;
22236        final boolean moveCompleteApp;
22237        final File measurePath;
22238
22239        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22240            installFlags = INSTALL_INTERNAL;
22241            moveCompleteApp = !currentAsec;
22242            measurePath = Environment.getDataAppDirectory(volumeUuid);
22243        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22244            installFlags = INSTALL_EXTERNAL;
22245            moveCompleteApp = false;
22246            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22247        } else {
22248            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22249            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22250                    || !volume.isMountedWritable()) {
22251                freezer.close();
22252                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22253                        "Move location not mounted private volume");
22254            }
22255
22256            Preconditions.checkState(!currentAsec);
22257
22258            installFlags = INSTALL_INTERNAL;
22259            moveCompleteApp = true;
22260            measurePath = Environment.getDataAppDirectory(volumeUuid);
22261        }
22262
22263        // If we're moving app data around, we need all the users unlocked
22264        if (moveCompleteApp) {
22265            for (int userId : installedUserIds) {
22266                if (StorageManager.isFileEncryptedNativeOrEmulated()
22267                        && !StorageManager.isUserKeyUnlocked(userId)) {
22268                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22269                            "User " + userId + " must be unlocked");
22270                }
22271            }
22272        }
22273
22274        final PackageStats stats = new PackageStats(null, -1);
22275        synchronized (mInstaller) {
22276            for (int userId : installedUserIds) {
22277                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22278                    freezer.close();
22279                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22280                            "Failed to measure package size");
22281                }
22282            }
22283        }
22284
22285        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22286                + stats.dataSize);
22287
22288        final long startFreeBytes = measurePath.getUsableSpace();
22289        final long sizeBytes;
22290        if (moveCompleteApp) {
22291            sizeBytes = stats.codeSize + stats.dataSize;
22292        } else {
22293            sizeBytes = stats.codeSize;
22294        }
22295
22296        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22297            freezer.close();
22298            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22299                    "Not enough free space to move");
22300        }
22301
22302        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22303
22304        final CountDownLatch installedLatch = new CountDownLatch(1);
22305        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22306            @Override
22307            public void onUserActionRequired(Intent intent) throws RemoteException {
22308                throw new IllegalStateException();
22309            }
22310
22311            @Override
22312            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22313                    Bundle extras) throws RemoteException {
22314                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22315                        + PackageManager.installStatusToString(returnCode, msg));
22316
22317                installedLatch.countDown();
22318                freezer.close();
22319
22320                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22321                switch (status) {
22322                    case PackageInstaller.STATUS_SUCCESS:
22323                        mMoveCallbacks.notifyStatusChanged(moveId,
22324                                PackageManager.MOVE_SUCCEEDED);
22325                        break;
22326                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22327                        mMoveCallbacks.notifyStatusChanged(moveId,
22328                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22329                        break;
22330                    default:
22331                        mMoveCallbacks.notifyStatusChanged(moveId,
22332                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22333                        break;
22334                }
22335            }
22336        };
22337
22338        final MoveInfo move;
22339        if (moveCompleteApp) {
22340            // Kick off a thread to report progress estimates
22341            new Thread() {
22342                @Override
22343                public void run() {
22344                    while (true) {
22345                        try {
22346                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22347                                break;
22348                            }
22349                        } catch (InterruptedException ignored) {
22350                        }
22351
22352                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22353                        final int progress = 10 + (int) MathUtils.constrain(
22354                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22355                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22356                    }
22357                }
22358            }.start();
22359
22360            final String dataAppName = codeFile.getName();
22361            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22362                    dataAppName, appId, seinfo, targetSdkVersion);
22363        } else {
22364            move = null;
22365        }
22366
22367        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22368
22369        final Message msg = mHandler.obtainMessage(INIT_COPY);
22370        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22371        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22372                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22373                packageAbiOverride, null /*grantedPermissions*/,
22374                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22375        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22376        msg.obj = params;
22377
22378        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22379                System.identityHashCode(msg.obj));
22380        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22381                System.identityHashCode(msg.obj));
22382
22383        mHandler.sendMessage(msg);
22384    }
22385
22386    @Override
22387    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22388        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22389
22390        final int realMoveId = mNextMoveId.getAndIncrement();
22391        final Bundle extras = new Bundle();
22392        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22393        mMoveCallbacks.notifyCreated(realMoveId, extras);
22394
22395        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22396            @Override
22397            public void onCreated(int moveId, Bundle extras) {
22398                // Ignored
22399            }
22400
22401            @Override
22402            public void onStatusChanged(int moveId, int status, long estMillis) {
22403                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22404            }
22405        };
22406
22407        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22408        storage.setPrimaryStorageUuid(volumeUuid, callback);
22409        return realMoveId;
22410    }
22411
22412    @Override
22413    public int getMoveStatus(int moveId) {
22414        mContext.enforceCallingOrSelfPermission(
22415                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22416        return mMoveCallbacks.mLastStatus.get(moveId);
22417    }
22418
22419    @Override
22420    public void registerMoveCallback(IPackageMoveObserver callback) {
22421        mContext.enforceCallingOrSelfPermission(
22422                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22423        mMoveCallbacks.register(callback);
22424    }
22425
22426    @Override
22427    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22428        mContext.enforceCallingOrSelfPermission(
22429                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22430        mMoveCallbacks.unregister(callback);
22431    }
22432
22433    @Override
22434    public boolean setInstallLocation(int loc) {
22435        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22436                null);
22437        if (getInstallLocation() == loc) {
22438            return true;
22439        }
22440        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22441                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22442            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22443                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22444            return true;
22445        }
22446        return false;
22447   }
22448
22449    @Override
22450    public int getInstallLocation() {
22451        // allow instant app access
22452        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22453                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22454                PackageHelper.APP_INSTALL_AUTO);
22455    }
22456
22457    /** Called by UserManagerService */
22458    void cleanUpUser(UserManagerService userManager, int userHandle) {
22459        synchronized (mPackages) {
22460            mDirtyUsers.remove(userHandle);
22461            mUserNeedsBadging.delete(userHandle);
22462            mSettings.removeUserLPw(userHandle);
22463            mPendingBroadcasts.remove(userHandle);
22464            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22465            removeUnusedPackagesLPw(userManager, userHandle);
22466        }
22467    }
22468
22469    /**
22470     * We're removing userHandle and would like to remove any downloaded packages
22471     * that are no longer in use by any other user.
22472     * @param userHandle the user being removed
22473     */
22474    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22475        final boolean DEBUG_CLEAN_APKS = false;
22476        int [] users = userManager.getUserIds();
22477        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22478        while (psit.hasNext()) {
22479            PackageSetting ps = psit.next();
22480            if (ps.pkg == null) {
22481                continue;
22482            }
22483            final String packageName = ps.pkg.packageName;
22484            // Skip over if system app
22485            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22486                continue;
22487            }
22488            if (DEBUG_CLEAN_APKS) {
22489                Slog.i(TAG, "Checking package " + packageName);
22490            }
22491            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22492            if (keep) {
22493                if (DEBUG_CLEAN_APKS) {
22494                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22495                }
22496            } else {
22497                for (int i = 0; i < users.length; i++) {
22498                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22499                        keep = true;
22500                        if (DEBUG_CLEAN_APKS) {
22501                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22502                                    + users[i]);
22503                        }
22504                        break;
22505                    }
22506                }
22507            }
22508            if (!keep) {
22509                if (DEBUG_CLEAN_APKS) {
22510                    Slog.i(TAG, "  Removing package " + packageName);
22511                }
22512                mHandler.post(new Runnable() {
22513                    public void run() {
22514                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22515                                userHandle, 0);
22516                    } //end run
22517                });
22518            }
22519        }
22520    }
22521
22522    /** Called by UserManagerService */
22523    void createNewUser(int userId, String[] disallowedPackages) {
22524        synchronized (mInstallLock) {
22525            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22526        }
22527        synchronized (mPackages) {
22528            scheduleWritePackageRestrictionsLocked(userId);
22529            scheduleWritePackageListLocked(userId);
22530            applyFactoryDefaultBrowserLPw(userId);
22531            primeDomainVerificationsLPw(userId);
22532        }
22533    }
22534
22535    void onNewUserCreated(final int userId) {
22536        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22537        synchronized(mPackages) {
22538            // If permission review for legacy apps is required, we represent
22539            // dagerous permissions for such apps as always granted runtime
22540            // permissions to keep per user flag state whether review is needed.
22541            // Hence, if a new user is added we have to propagate dangerous
22542            // permission grants for these legacy apps.
22543            if (mSettings.mPermissions.mPermissionReviewRequired) {
22544// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22545                mPermissionManager.updateAllPermissions(
22546                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22547                        mPermissionCallback);
22548            }
22549        }
22550    }
22551
22552    @Override
22553    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22554        mContext.enforceCallingOrSelfPermission(
22555                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22556                "Only package verification agents can read the verifier device identity");
22557
22558        synchronized (mPackages) {
22559            return mSettings.getVerifierDeviceIdentityLPw();
22560        }
22561    }
22562
22563    @Override
22564    public void setPermissionEnforced(String permission, boolean enforced) {
22565        // TODO: Now that we no longer change GID for storage, this should to away.
22566        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22567                "setPermissionEnforced");
22568        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22569            synchronized (mPackages) {
22570                if (mSettings.mReadExternalStorageEnforced == null
22571                        || mSettings.mReadExternalStorageEnforced != enforced) {
22572                    mSettings.mReadExternalStorageEnforced =
22573                            enforced ? Boolean.TRUE : Boolean.FALSE;
22574                    mSettings.writeLPr();
22575                }
22576            }
22577            // kill any non-foreground processes so we restart them and
22578            // grant/revoke the GID.
22579            final IActivityManager am = ActivityManager.getService();
22580            if (am != null) {
22581                final long token = Binder.clearCallingIdentity();
22582                try {
22583                    am.killProcessesBelowForeground("setPermissionEnforcement");
22584                } catch (RemoteException e) {
22585                } finally {
22586                    Binder.restoreCallingIdentity(token);
22587                }
22588            }
22589        } else {
22590            throw new IllegalArgumentException("No selective enforcement for " + permission);
22591        }
22592    }
22593
22594    @Override
22595    @Deprecated
22596    public boolean isPermissionEnforced(String permission) {
22597        // allow instant applications
22598        return true;
22599    }
22600
22601    @Override
22602    public boolean isStorageLow() {
22603        // allow instant applications
22604        final long token = Binder.clearCallingIdentity();
22605        try {
22606            final DeviceStorageMonitorInternal
22607                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22608            if (dsm != null) {
22609                return dsm.isMemoryLow();
22610            } else {
22611                return false;
22612            }
22613        } finally {
22614            Binder.restoreCallingIdentity(token);
22615        }
22616    }
22617
22618    @Override
22619    public IPackageInstaller getPackageInstaller() {
22620        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22621            return null;
22622        }
22623        return mInstallerService;
22624    }
22625
22626    @Override
22627    public IArtManager getArtManager() {
22628        return mArtManagerService;
22629    }
22630
22631    private boolean userNeedsBadging(int userId) {
22632        int index = mUserNeedsBadging.indexOfKey(userId);
22633        if (index < 0) {
22634            final UserInfo userInfo;
22635            final long token = Binder.clearCallingIdentity();
22636            try {
22637                userInfo = sUserManager.getUserInfo(userId);
22638            } finally {
22639                Binder.restoreCallingIdentity(token);
22640            }
22641            final boolean b;
22642            if (userInfo != null && userInfo.isManagedProfile()) {
22643                b = true;
22644            } else {
22645                b = false;
22646            }
22647            mUserNeedsBadging.put(userId, b);
22648            return b;
22649        }
22650        return mUserNeedsBadging.valueAt(index);
22651    }
22652
22653    @Override
22654    public KeySet getKeySetByAlias(String packageName, String alias) {
22655        if (packageName == null || alias == null) {
22656            return null;
22657        }
22658        synchronized(mPackages) {
22659            final PackageParser.Package pkg = mPackages.get(packageName);
22660            if (pkg == null) {
22661                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22662                throw new IllegalArgumentException("Unknown package: " + packageName);
22663            }
22664            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22665            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22666                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22667                throw new IllegalArgumentException("Unknown package: " + packageName);
22668            }
22669            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22670            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22671        }
22672    }
22673
22674    @Override
22675    public KeySet getSigningKeySet(String packageName) {
22676        if (packageName == null) {
22677            return null;
22678        }
22679        synchronized(mPackages) {
22680            final int callingUid = Binder.getCallingUid();
22681            final int callingUserId = UserHandle.getUserId(callingUid);
22682            final PackageParser.Package pkg = mPackages.get(packageName);
22683            if (pkg == null) {
22684                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22685                throw new IllegalArgumentException("Unknown package: " + packageName);
22686            }
22687            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22688            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22689                // filter and pretend the package doesn't exist
22690                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22691                        + ", uid:" + callingUid);
22692                throw new IllegalArgumentException("Unknown package: " + packageName);
22693            }
22694            if (pkg.applicationInfo.uid != callingUid
22695                    && Process.SYSTEM_UID != callingUid) {
22696                throw new SecurityException("May not access signing KeySet of other apps.");
22697            }
22698            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22699            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22700        }
22701    }
22702
22703    @Override
22704    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22705        final int callingUid = Binder.getCallingUid();
22706        if (getInstantAppPackageName(callingUid) != null) {
22707            return false;
22708        }
22709        if (packageName == null || ks == null) {
22710            return false;
22711        }
22712        synchronized(mPackages) {
22713            final PackageParser.Package pkg = mPackages.get(packageName);
22714            if (pkg == null
22715                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22716                            UserHandle.getUserId(callingUid))) {
22717                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22718                throw new IllegalArgumentException("Unknown package: " + packageName);
22719            }
22720            IBinder ksh = ks.getToken();
22721            if (ksh instanceof KeySetHandle) {
22722                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22723                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22724            }
22725            return false;
22726        }
22727    }
22728
22729    @Override
22730    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22731        final int callingUid = Binder.getCallingUid();
22732        if (getInstantAppPackageName(callingUid) != null) {
22733            return false;
22734        }
22735        if (packageName == null || ks == null) {
22736            return false;
22737        }
22738        synchronized(mPackages) {
22739            final PackageParser.Package pkg = mPackages.get(packageName);
22740            if (pkg == null
22741                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22742                            UserHandle.getUserId(callingUid))) {
22743                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22744                throw new IllegalArgumentException("Unknown package: " + packageName);
22745            }
22746            IBinder ksh = ks.getToken();
22747            if (ksh instanceof KeySetHandle) {
22748                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22749                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22750            }
22751            return false;
22752        }
22753    }
22754
22755    private void deletePackageIfUnusedLPr(final String packageName) {
22756        PackageSetting ps = mSettings.mPackages.get(packageName);
22757        if (ps == null) {
22758            return;
22759        }
22760        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22761            // TODO Implement atomic delete if package is unused
22762            // It is currently possible that the package will be deleted even if it is installed
22763            // after this method returns.
22764            mHandler.post(new Runnable() {
22765                public void run() {
22766                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22767                            0, PackageManager.DELETE_ALL_USERS);
22768                }
22769            });
22770        }
22771    }
22772
22773    /**
22774     * Check and throw if the given before/after packages would be considered a
22775     * downgrade.
22776     */
22777    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22778            throws PackageManagerException {
22779        if (after.getLongVersionCode() < before.getLongVersionCode()) {
22780            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22781                    "Update version code " + after.versionCode + " is older than current "
22782                    + before.getLongVersionCode());
22783        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
22784            if (after.baseRevisionCode < before.baseRevisionCode) {
22785                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22786                        "Update base revision code " + after.baseRevisionCode
22787                        + " is older than current " + before.baseRevisionCode);
22788            }
22789
22790            if (!ArrayUtils.isEmpty(after.splitNames)) {
22791                for (int i = 0; i < after.splitNames.length; i++) {
22792                    final String splitName = after.splitNames[i];
22793                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22794                    if (j != -1) {
22795                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22796                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22797                                    "Update split " + splitName + " revision code "
22798                                    + after.splitRevisionCodes[i] + " is older than current "
22799                                    + before.splitRevisionCodes[j]);
22800                        }
22801                    }
22802                }
22803            }
22804        }
22805    }
22806
22807    private static class MoveCallbacks extends Handler {
22808        private static final int MSG_CREATED = 1;
22809        private static final int MSG_STATUS_CHANGED = 2;
22810
22811        private final RemoteCallbackList<IPackageMoveObserver>
22812                mCallbacks = new RemoteCallbackList<>();
22813
22814        private final SparseIntArray mLastStatus = new SparseIntArray();
22815
22816        public MoveCallbacks(Looper looper) {
22817            super(looper);
22818        }
22819
22820        public void register(IPackageMoveObserver callback) {
22821            mCallbacks.register(callback);
22822        }
22823
22824        public void unregister(IPackageMoveObserver callback) {
22825            mCallbacks.unregister(callback);
22826        }
22827
22828        @Override
22829        public void handleMessage(Message msg) {
22830            final SomeArgs args = (SomeArgs) msg.obj;
22831            final int n = mCallbacks.beginBroadcast();
22832            for (int i = 0; i < n; i++) {
22833                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22834                try {
22835                    invokeCallback(callback, msg.what, args);
22836                } catch (RemoteException ignored) {
22837                }
22838            }
22839            mCallbacks.finishBroadcast();
22840            args.recycle();
22841        }
22842
22843        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22844                throws RemoteException {
22845            switch (what) {
22846                case MSG_CREATED: {
22847                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22848                    break;
22849                }
22850                case MSG_STATUS_CHANGED: {
22851                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22852                    break;
22853                }
22854            }
22855        }
22856
22857        private void notifyCreated(int moveId, Bundle extras) {
22858            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22859
22860            final SomeArgs args = SomeArgs.obtain();
22861            args.argi1 = moveId;
22862            args.arg2 = extras;
22863            obtainMessage(MSG_CREATED, args).sendToTarget();
22864        }
22865
22866        private void notifyStatusChanged(int moveId, int status) {
22867            notifyStatusChanged(moveId, status, -1);
22868        }
22869
22870        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22871            Slog.v(TAG, "Move " + moveId + " status " + status);
22872
22873            final SomeArgs args = SomeArgs.obtain();
22874            args.argi1 = moveId;
22875            args.argi2 = status;
22876            args.arg3 = estMillis;
22877            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22878
22879            synchronized (mLastStatus) {
22880                mLastStatus.put(moveId, status);
22881            }
22882        }
22883    }
22884
22885    private final static class OnPermissionChangeListeners extends Handler {
22886        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22887
22888        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22889                new RemoteCallbackList<>();
22890
22891        public OnPermissionChangeListeners(Looper looper) {
22892            super(looper);
22893        }
22894
22895        @Override
22896        public void handleMessage(Message msg) {
22897            switch (msg.what) {
22898                case MSG_ON_PERMISSIONS_CHANGED: {
22899                    final int uid = msg.arg1;
22900                    handleOnPermissionsChanged(uid);
22901                } break;
22902            }
22903        }
22904
22905        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22906            mPermissionListeners.register(listener);
22907
22908        }
22909
22910        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22911            mPermissionListeners.unregister(listener);
22912        }
22913
22914        public void onPermissionsChanged(int uid) {
22915            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22916                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22917            }
22918        }
22919
22920        private void handleOnPermissionsChanged(int uid) {
22921            final int count = mPermissionListeners.beginBroadcast();
22922            try {
22923                for (int i = 0; i < count; i++) {
22924                    IOnPermissionsChangeListener callback = mPermissionListeners
22925                            .getBroadcastItem(i);
22926                    try {
22927                        callback.onPermissionsChanged(uid);
22928                    } catch (RemoteException e) {
22929                        Log.e(TAG, "Permission listener is dead", e);
22930                    }
22931                }
22932            } finally {
22933                mPermissionListeners.finishBroadcast();
22934            }
22935        }
22936    }
22937
22938    private class PackageManagerNative extends IPackageManagerNative.Stub {
22939        @Override
22940        public String[] getNamesForUids(int[] uids) throws RemoteException {
22941            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22942            // massage results so they can be parsed by the native binder
22943            for (int i = results.length - 1; i >= 0; --i) {
22944                if (results[i] == null) {
22945                    results[i] = "";
22946                }
22947            }
22948            return results;
22949        }
22950
22951        // NB: this differentiates between preloads and sideloads
22952        @Override
22953        public String getInstallerForPackage(String packageName) throws RemoteException {
22954            final String installerName = getInstallerPackageName(packageName);
22955            if (!TextUtils.isEmpty(installerName)) {
22956                return installerName;
22957            }
22958            // differentiate between preload and sideload
22959            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22960            ApplicationInfo appInfo = getApplicationInfo(packageName,
22961                                    /*flags*/ 0,
22962                                    /*userId*/ callingUser);
22963            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22964                return "preload";
22965            }
22966            return "";
22967        }
22968
22969        @Override
22970        public long getVersionCodeForPackage(String packageName) throws RemoteException {
22971            try {
22972                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22973                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22974                if (pInfo != null) {
22975                    return pInfo.getLongVersionCode();
22976                }
22977            } catch (Exception e) {
22978            }
22979            return 0;
22980        }
22981    }
22982
22983    private class PackageManagerInternalImpl extends PackageManagerInternal {
22984        @Override
22985        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22986                int flagValues, int userId) {
22987            PackageManagerService.this.updatePermissionFlags(
22988                    permName, packageName, flagMask, flagValues, userId);
22989        }
22990
22991        @Override
22992        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22993            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22994        }
22995
22996        @Override
22997        public boolean isInstantApp(String packageName, int userId) {
22998            return PackageManagerService.this.isInstantApp(packageName, userId);
22999        }
23000
23001        @Override
23002        public String getInstantAppPackageName(int uid) {
23003            return PackageManagerService.this.getInstantAppPackageName(uid);
23004        }
23005
23006        @Override
23007        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23008            synchronized (mPackages) {
23009                return PackageManagerService.this.filterAppAccessLPr(
23010                        (PackageSetting) pkg.mExtras, callingUid, userId);
23011            }
23012        }
23013
23014        @Override
23015        public PackageParser.Package getPackage(String packageName) {
23016            synchronized (mPackages) {
23017                packageName = resolveInternalPackageNameLPr(
23018                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23019                return mPackages.get(packageName);
23020            }
23021        }
23022
23023        @Override
23024        public PackageList getPackageList(PackageListObserver observer) {
23025            synchronized (mPackages) {
23026                final int N = mPackages.size();
23027                final ArrayList<String> list = new ArrayList<>(N);
23028                for (int i = 0; i < N; i++) {
23029                    list.add(mPackages.keyAt(i));
23030                }
23031                final PackageList packageList = new PackageList(list, observer);
23032                if (observer != null) {
23033                    mPackageListObservers.add(packageList);
23034                }
23035                return packageList;
23036            }
23037        }
23038
23039        @Override
23040        public void removePackageListObserver(PackageListObserver observer) {
23041            synchronized (mPackages) {
23042                mPackageListObservers.remove(observer);
23043            }
23044        }
23045
23046        @Override
23047        public PackageParser.Package getDisabledPackage(String packageName) {
23048            synchronized (mPackages) {
23049                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23050                return (ps != null) ? ps.pkg : null;
23051            }
23052        }
23053
23054        @Override
23055        public String getKnownPackageName(int knownPackage, int userId) {
23056            switch(knownPackage) {
23057                case PackageManagerInternal.PACKAGE_BROWSER:
23058                    return getDefaultBrowserPackageName(userId);
23059                case PackageManagerInternal.PACKAGE_INSTALLER:
23060                    return mRequiredInstallerPackage;
23061                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23062                    return mSetupWizardPackage;
23063                case PackageManagerInternal.PACKAGE_SYSTEM:
23064                    return "android";
23065                case PackageManagerInternal.PACKAGE_VERIFIER:
23066                    return mRequiredVerifierPackage;
23067            }
23068            return null;
23069        }
23070
23071        @Override
23072        public boolean isResolveActivityComponent(ComponentInfo component) {
23073            return mResolveActivity.packageName.equals(component.packageName)
23074                    && mResolveActivity.name.equals(component.name);
23075        }
23076
23077        @Override
23078        public void setLocationPackagesProvider(PackagesProvider provider) {
23079            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23080        }
23081
23082        @Override
23083        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23084            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23085        }
23086
23087        @Override
23088        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23089            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23090        }
23091
23092        @Override
23093        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23094            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23095        }
23096
23097        @Override
23098        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23099            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23100        }
23101
23102        @Override
23103        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23104            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23105        }
23106
23107        @Override
23108        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23109            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23110        }
23111
23112        @Override
23113        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23114            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23115        }
23116
23117        @Override
23118        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23119            synchronized (mPackages) {
23120                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23121            }
23122            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23123        }
23124
23125        @Override
23126        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23127            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23128                    packageName, userId);
23129        }
23130
23131        @Override
23132        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23133            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23134                    packageName, userId);
23135        }
23136
23137        @Override
23138        public void setKeepUninstalledPackages(final List<String> packageList) {
23139            Preconditions.checkNotNull(packageList);
23140            List<String> removedFromList = null;
23141            synchronized (mPackages) {
23142                if (mKeepUninstalledPackages != null) {
23143                    final int packagesCount = mKeepUninstalledPackages.size();
23144                    for (int i = 0; i < packagesCount; i++) {
23145                        String oldPackage = mKeepUninstalledPackages.get(i);
23146                        if (packageList != null && packageList.contains(oldPackage)) {
23147                            continue;
23148                        }
23149                        if (removedFromList == null) {
23150                            removedFromList = new ArrayList<>();
23151                        }
23152                        removedFromList.add(oldPackage);
23153                    }
23154                }
23155                mKeepUninstalledPackages = new ArrayList<>(packageList);
23156                if (removedFromList != null) {
23157                    final int removedCount = removedFromList.size();
23158                    for (int i = 0; i < removedCount; i++) {
23159                        deletePackageIfUnusedLPr(removedFromList.get(i));
23160                    }
23161                }
23162            }
23163        }
23164
23165        @Override
23166        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23167            synchronized (mPackages) {
23168                return mPermissionManager.isPermissionsReviewRequired(
23169                        mPackages.get(packageName), userId);
23170            }
23171        }
23172
23173        @Override
23174        public PackageInfo getPackageInfo(
23175                String packageName, int flags, int filterCallingUid, int userId) {
23176            return PackageManagerService.this
23177                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23178                            flags, filterCallingUid, userId);
23179        }
23180
23181        @Override
23182        public int getPackageUid(String packageName, int flags, int userId) {
23183            return PackageManagerService.this
23184                    .getPackageUid(packageName, flags, userId);
23185        }
23186
23187        @Override
23188        public ApplicationInfo getApplicationInfo(
23189                String packageName, int flags, int filterCallingUid, int userId) {
23190            return PackageManagerService.this
23191                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23192        }
23193
23194        @Override
23195        public ActivityInfo getActivityInfo(
23196                ComponentName component, int flags, int filterCallingUid, int userId) {
23197            return PackageManagerService.this
23198                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23199        }
23200
23201        @Override
23202        public List<ResolveInfo> queryIntentActivities(
23203                Intent intent, int flags, int filterCallingUid, int userId) {
23204            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23205            return PackageManagerService.this
23206                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23207                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23208        }
23209
23210        @Override
23211        public List<ResolveInfo> queryIntentServices(
23212                Intent intent, int flags, int callingUid, int userId) {
23213            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23214            return PackageManagerService.this
23215                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23216                            false);
23217        }
23218
23219        @Override
23220        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23221                int userId) {
23222            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23223        }
23224
23225        @Override
23226        public void setDeviceAndProfileOwnerPackages(
23227                int deviceOwnerUserId, String deviceOwnerPackage,
23228                SparseArray<String> profileOwnerPackages) {
23229            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23230                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23231        }
23232
23233        @Override
23234        public boolean isPackageDataProtected(int userId, String packageName) {
23235            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23236        }
23237
23238        @Override
23239        public boolean isPackageEphemeral(int userId, String packageName) {
23240            synchronized (mPackages) {
23241                final PackageSetting ps = mSettings.mPackages.get(packageName);
23242                return ps != null ? ps.getInstantApp(userId) : false;
23243            }
23244        }
23245
23246        @Override
23247        public boolean wasPackageEverLaunched(String packageName, int userId) {
23248            synchronized (mPackages) {
23249                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23250            }
23251        }
23252
23253        @Override
23254        public void grantRuntimePermission(String packageName, String permName, int userId,
23255                boolean overridePolicy) {
23256            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23257                    permName, packageName, overridePolicy, getCallingUid(), userId,
23258                    mPermissionCallback);
23259        }
23260
23261        @Override
23262        public void revokeRuntimePermission(String packageName, String permName, int userId,
23263                boolean overridePolicy) {
23264            mPermissionManager.revokeRuntimePermission(
23265                    permName, packageName, overridePolicy, getCallingUid(), userId,
23266                    mPermissionCallback);
23267        }
23268
23269        @Override
23270        public String getNameForUid(int uid) {
23271            return PackageManagerService.this.getNameForUid(uid);
23272        }
23273
23274        @Override
23275        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23276                Intent origIntent, String resolvedType, String callingPackage,
23277                Bundle verificationBundle, int userId) {
23278            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23279                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23280                    userId);
23281        }
23282
23283        @Override
23284        public void grantEphemeralAccess(int userId, Intent intent,
23285                int targetAppId, int ephemeralAppId) {
23286            synchronized (mPackages) {
23287                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23288                        targetAppId, ephemeralAppId);
23289            }
23290        }
23291
23292        @Override
23293        public boolean isInstantAppInstallerComponent(ComponentName component) {
23294            synchronized (mPackages) {
23295                return mInstantAppInstallerActivity != null
23296                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23297            }
23298        }
23299
23300        @Override
23301        public void pruneInstantApps() {
23302            mInstantAppRegistry.pruneInstantApps();
23303        }
23304
23305        @Override
23306        public String getSetupWizardPackageName() {
23307            return mSetupWizardPackage;
23308        }
23309
23310        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23311            if (policy != null) {
23312                mExternalSourcesPolicy = policy;
23313            }
23314        }
23315
23316        @Override
23317        public boolean isPackagePersistent(String packageName) {
23318            synchronized (mPackages) {
23319                PackageParser.Package pkg = mPackages.get(packageName);
23320                return pkg != null
23321                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23322                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23323                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23324                        : false;
23325            }
23326        }
23327
23328        @Override
23329        public boolean isLegacySystemApp(Package pkg) {
23330            synchronized (mPackages) {
23331                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23332                return mPromoteSystemApps
23333                        && ps.isSystem()
23334                        && mExistingSystemPackages.contains(ps.name);
23335            }
23336        }
23337
23338        @Override
23339        public List<PackageInfo> getOverlayPackages(int userId) {
23340            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23341            synchronized (mPackages) {
23342                for (PackageParser.Package p : mPackages.values()) {
23343                    if (p.mOverlayTarget != null) {
23344                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23345                        if (pkg != null) {
23346                            overlayPackages.add(pkg);
23347                        }
23348                    }
23349                }
23350            }
23351            return overlayPackages;
23352        }
23353
23354        @Override
23355        public List<String> getTargetPackageNames(int userId) {
23356            List<String> targetPackages = new ArrayList<>();
23357            synchronized (mPackages) {
23358                for (PackageParser.Package p : mPackages.values()) {
23359                    if (p.mOverlayTarget == null) {
23360                        targetPackages.add(p.packageName);
23361                    }
23362                }
23363            }
23364            return targetPackages;
23365        }
23366
23367        @Override
23368        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23369                @Nullable List<String> overlayPackageNames) {
23370            synchronized (mPackages) {
23371                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23372                    Slog.e(TAG, "failed to find package " + targetPackageName);
23373                    return false;
23374                }
23375                ArrayList<String> overlayPaths = null;
23376                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23377                    final int N = overlayPackageNames.size();
23378                    overlayPaths = new ArrayList<>(N);
23379                    for (int i = 0; i < N; i++) {
23380                        final String packageName = overlayPackageNames.get(i);
23381                        final PackageParser.Package pkg = mPackages.get(packageName);
23382                        if (pkg == null) {
23383                            Slog.e(TAG, "failed to find package " + packageName);
23384                            return false;
23385                        }
23386                        overlayPaths.add(pkg.baseCodePath);
23387                    }
23388                }
23389
23390                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23391                ps.setOverlayPaths(overlayPaths, userId);
23392                return true;
23393            }
23394        }
23395
23396        @Override
23397        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23398                int flags, int userId, boolean resolveForStart) {
23399            return resolveIntentInternal(
23400                    intent, resolvedType, flags, userId, resolveForStart);
23401        }
23402
23403        @Override
23404        public ResolveInfo resolveService(Intent intent, String resolvedType,
23405                int flags, int userId, int callingUid) {
23406            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23407        }
23408
23409        @Override
23410        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23411            return PackageManagerService.this.resolveContentProviderInternal(
23412                    name, flags, userId);
23413        }
23414
23415        @Override
23416        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23417            synchronized (mPackages) {
23418                mIsolatedOwners.put(isolatedUid, ownerUid);
23419            }
23420        }
23421
23422        @Override
23423        public void removeIsolatedUid(int isolatedUid) {
23424            synchronized (mPackages) {
23425                mIsolatedOwners.delete(isolatedUid);
23426            }
23427        }
23428
23429        @Override
23430        public int getUidTargetSdkVersion(int uid) {
23431            synchronized (mPackages) {
23432                return getUidTargetSdkVersionLockedLPr(uid);
23433            }
23434        }
23435
23436        @Override
23437        public int getPackageTargetSdkVersion(String packageName) {
23438            synchronized (mPackages) {
23439                return getPackageTargetSdkVersionLockedLPr(packageName);
23440            }
23441        }
23442
23443        @Override
23444        public boolean canAccessInstantApps(int callingUid, int userId) {
23445            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23446        }
23447
23448        @Override
23449        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23450            synchronized (mPackages) {
23451                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23452            }
23453        }
23454
23455        @Override
23456        public void notifyPackageUse(String packageName, int reason) {
23457            synchronized (mPackages) {
23458                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23459            }
23460        }
23461    }
23462
23463    @Override
23464    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23465        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23466        synchronized (mPackages) {
23467            final long identity = Binder.clearCallingIdentity();
23468            try {
23469                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23470                        packageNames, userId);
23471            } finally {
23472                Binder.restoreCallingIdentity(identity);
23473            }
23474        }
23475    }
23476
23477    @Override
23478    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23479        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23480        synchronized (mPackages) {
23481            final long identity = Binder.clearCallingIdentity();
23482            try {
23483                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23484                        packageNames, userId);
23485            } finally {
23486                Binder.restoreCallingIdentity(identity);
23487            }
23488        }
23489    }
23490
23491    private static void enforceSystemOrPhoneCaller(String tag) {
23492        int callingUid = Binder.getCallingUid();
23493        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23494            throw new SecurityException(
23495                    "Cannot call " + tag + " from UID " + callingUid);
23496        }
23497    }
23498
23499    boolean isHistoricalPackageUsageAvailable() {
23500        return mPackageUsage.isHistoricalPackageUsageAvailable();
23501    }
23502
23503    /**
23504     * Return a <b>copy</b> of the collection of packages known to the package manager.
23505     * @return A copy of the values of mPackages.
23506     */
23507    Collection<PackageParser.Package> getPackages() {
23508        synchronized (mPackages) {
23509            return new ArrayList<>(mPackages.values());
23510        }
23511    }
23512
23513    /**
23514     * Logs process start information (including base APK hash) to the security log.
23515     * @hide
23516     */
23517    @Override
23518    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23519            String apkFile, int pid) {
23520        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23521            return;
23522        }
23523        if (!SecurityLog.isLoggingEnabled()) {
23524            return;
23525        }
23526        Bundle data = new Bundle();
23527        data.putLong("startTimestamp", System.currentTimeMillis());
23528        data.putString("processName", processName);
23529        data.putInt("uid", uid);
23530        data.putString("seinfo", seinfo);
23531        data.putString("apkFile", apkFile);
23532        data.putInt("pid", pid);
23533        Message msg = mProcessLoggingHandler.obtainMessage(
23534                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23535        msg.setData(data);
23536        mProcessLoggingHandler.sendMessage(msg);
23537    }
23538
23539    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23540        return mCompilerStats.getPackageStats(pkgName);
23541    }
23542
23543    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23544        return getOrCreateCompilerPackageStats(pkg.packageName);
23545    }
23546
23547    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23548        return mCompilerStats.getOrCreatePackageStats(pkgName);
23549    }
23550
23551    public void deleteCompilerPackageStats(String pkgName) {
23552        mCompilerStats.deletePackageStats(pkgName);
23553    }
23554
23555    @Override
23556    public int getInstallReason(String packageName, int userId) {
23557        final int callingUid = Binder.getCallingUid();
23558        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23559                true /* requireFullPermission */, false /* checkShell */,
23560                "get install reason");
23561        synchronized (mPackages) {
23562            final PackageSetting ps = mSettings.mPackages.get(packageName);
23563            if (filterAppAccessLPr(ps, callingUid, userId)) {
23564                return PackageManager.INSTALL_REASON_UNKNOWN;
23565            }
23566            if (ps != null) {
23567                return ps.getInstallReason(userId);
23568            }
23569        }
23570        return PackageManager.INSTALL_REASON_UNKNOWN;
23571    }
23572
23573    @Override
23574    public boolean canRequestPackageInstalls(String packageName, int userId) {
23575        return canRequestPackageInstallsInternal(packageName, 0, userId,
23576                true /* throwIfPermNotDeclared*/);
23577    }
23578
23579    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23580            boolean throwIfPermNotDeclared) {
23581        int callingUid = Binder.getCallingUid();
23582        int uid = getPackageUid(packageName, 0, userId);
23583        if (callingUid != uid && callingUid != Process.ROOT_UID
23584                && callingUid != Process.SYSTEM_UID) {
23585            throw new SecurityException(
23586                    "Caller uid " + callingUid + " does not own package " + packageName);
23587        }
23588        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23589        if (info == null) {
23590            return false;
23591        }
23592        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23593            return false;
23594        }
23595        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23596        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23597        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23598            if (throwIfPermNotDeclared) {
23599                throw new SecurityException("Need to declare " + appOpPermission
23600                        + " to call this api");
23601            } else {
23602                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23603                return false;
23604            }
23605        }
23606        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23607            return false;
23608        }
23609        if (mExternalSourcesPolicy != null) {
23610            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23611            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23612                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23613            }
23614        }
23615        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23616    }
23617
23618    @Override
23619    public ComponentName getInstantAppResolverSettingsComponent() {
23620        return mInstantAppResolverSettingsComponent;
23621    }
23622
23623    @Override
23624    public ComponentName getInstantAppInstallerComponent() {
23625        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23626            return null;
23627        }
23628        return mInstantAppInstallerActivity == null
23629                ? null : mInstantAppInstallerActivity.getComponentName();
23630    }
23631
23632    @Override
23633    public String getInstantAppAndroidId(String packageName, int userId) {
23634        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23635                "getInstantAppAndroidId");
23636        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23637                true /* requireFullPermission */, false /* checkShell */,
23638                "getInstantAppAndroidId");
23639        // Make sure the target is an Instant App.
23640        if (!isInstantApp(packageName, userId)) {
23641            return null;
23642        }
23643        synchronized (mPackages) {
23644            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23645        }
23646    }
23647
23648    boolean canHaveOatDir(String packageName) {
23649        synchronized (mPackages) {
23650            PackageParser.Package p = mPackages.get(packageName);
23651            if (p == null) {
23652                return false;
23653            }
23654            return p.canHaveOatDir();
23655        }
23656    }
23657
23658    private String getOatDir(PackageParser.Package pkg) {
23659        if (!pkg.canHaveOatDir()) {
23660            return null;
23661        }
23662        File codePath = new File(pkg.codePath);
23663        if (codePath.isDirectory()) {
23664            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23665        }
23666        return null;
23667    }
23668
23669    void deleteOatArtifactsOfPackage(String packageName) {
23670        final String[] instructionSets;
23671        final List<String> codePaths;
23672        final String oatDir;
23673        final PackageParser.Package pkg;
23674        synchronized (mPackages) {
23675            pkg = mPackages.get(packageName);
23676        }
23677        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23678        codePaths = pkg.getAllCodePaths();
23679        oatDir = getOatDir(pkg);
23680
23681        for (String codePath : codePaths) {
23682            for (String isa : instructionSets) {
23683                try {
23684                    mInstaller.deleteOdex(codePath, isa, oatDir);
23685                } catch (InstallerException e) {
23686                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23687                }
23688            }
23689        }
23690    }
23691
23692    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23693        Set<String> unusedPackages = new HashSet<>();
23694        long currentTimeInMillis = System.currentTimeMillis();
23695        synchronized (mPackages) {
23696            for (PackageParser.Package pkg : mPackages.values()) {
23697                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23698                if (ps == null) {
23699                    continue;
23700                }
23701                PackageDexUsage.PackageUseInfo packageUseInfo =
23702                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23703                if (PackageManagerServiceUtils
23704                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23705                                downgradeTimeThresholdMillis, packageUseInfo,
23706                                pkg.getLatestPackageUseTimeInMills(),
23707                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23708                    unusedPackages.add(pkg.packageName);
23709                }
23710            }
23711        }
23712        return unusedPackages;
23713    }
23714
23715    @Override
23716    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
23717            int userId) {
23718        final int callingUid = Binder.getCallingUid();
23719        final int callingAppId = UserHandle.getAppId(callingUid);
23720
23721        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23722                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
23723
23724        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
23725                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
23726            throw new SecurityException("Caller must have the "
23727                    + SET_HARMFUL_APP_WARNINGS + " permission.");
23728        }
23729
23730        synchronized(mPackages) {
23731            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
23732            scheduleWritePackageRestrictionsLocked(userId);
23733        }
23734    }
23735
23736    @Nullable
23737    @Override
23738    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
23739        final int callingUid = Binder.getCallingUid();
23740        final int callingAppId = UserHandle.getAppId(callingUid);
23741
23742        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23743                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
23744
23745        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
23746                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
23747            throw new SecurityException("Caller must have the "
23748                    + SET_HARMFUL_APP_WARNINGS + " permission.");
23749        }
23750
23751        synchronized(mPackages) {
23752            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
23753        }
23754    }
23755}
23756
23757interface PackageSender {
23758    /**
23759     * @param userIds User IDs where the action occurred on a full application
23760     * @param instantUserIds User IDs where the action occurred on an instant application
23761     */
23762    void sendPackageBroadcast(final String action, final String pkg,
23763        final Bundle extras, final int flags, final String targetPkg,
23764        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
23765    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23766        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
23767    void notifyPackageAdded(String packageName);
23768    void notifyPackageRemoved(String packageName);
23769}
23770