PackageManagerService.java revision 0f877fab392154c77251dbac321b732a2a747911
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
87import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
103import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
104import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
105import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
106import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
107import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
108import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
109import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
114
115import android.Manifest;
116import android.annotation.IntDef;
117import android.annotation.NonNull;
118import android.annotation.Nullable;
119import android.app.ActivityManager;
120import android.app.AppOpsManager;
121import android.app.IActivityManager;
122import android.app.ResourcesManager;
123import android.app.admin.IDevicePolicyManager;
124import android.app.admin.SecurityLog;
125import android.app.backup.IBackupManager;
126import android.content.BroadcastReceiver;
127import android.content.ComponentName;
128import android.content.ContentResolver;
129import android.content.Context;
130import android.content.IIntentReceiver;
131import android.content.Intent;
132import android.content.IntentFilter;
133import android.content.IntentSender;
134import android.content.IntentSender.SendIntentException;
135import android.content.ServiceConnection;
136import android.content.pm.ActivityInfo;
137import android.content.pm.ApplicationInfo;
138import android.content.pm.AppsQueryHelper;
139import android.content.pm.AuxiliaryResolveInfo;
140import android.content.pm.ChangedPackages;
141import android.content.pm.ComponentInfo;
142import android.content.pm.FallbackCategoryProvider;
143import android.content.pm.FeatureInfo;
144import android.content.pm.IDexModuleRegisterCallback;
145import android.content.pm.IOnPermissionsChangeListener;
146import android.content.pm.IPackageDataObserver;
147import android.content.pm.IPackageDeleteObserver;
148import android.content.pm.IPackageDeleteObserver2;
149import android.content.pm.IPackageInstallObserver2;
150import android.content.pm.IPackageInstaller;
151import android.content.pm.IPackageManager;
152import android.content.pm.IPackageManagerNative;
153import android.content.pm.IPackageMoveObserver;
154import android.content.pm.IPackageStatsObserver;
155import android.content.pm.InstantAppInfo;
156import android.content.pm.InstantAppRequest;
157import android.content.pm.InstantAppResolveInfo;
158import android.content.pm.InstrumentationInfo;
159import android.content.pm.IntentFilterVerificationInfo;
160import android.content.pm.KeySet;
161import android.content.pm.PackageCleanItem;
162import android.content.pm.PackageInfo;
163import android.content.pm.PackageInfoLite;
164import android.content.pm.PackageInstaller;
165import android.content.pm.PackageManager;
166import android.content.pm.PackageManagerInternal;
167import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
168import android.content.pm.PackageManager.PackageInfoFlags;
169import android.content.pm.PackageParser;
170import android.content.pm.PackageParser.ActivityIntentInfo;
171import android.content.pm.PackageParser.Package;
172import android.content.pm.PackageParser.PackageLite;
173import android.content.pm.PackageParser.PackageParserException;
174import android.content.pm.PackageParser.ParseFlags;
175import android.content.pm.PackageStats;
176import android.content.pm.PackageUserState;
177import android.content.pm.ParceledListSlice;
178import android.content.pm.PermissionGroupInfo;
179import android.content.pm.PermissionInfo;
180import android.content.pm.ProviderInfo;
181import android.content.pm.ResolveInfo;
182import android.content.pm.ServiceInfo;
183import android.content.pm.SharedLibraryInfo;
184import android.content.pm.Signature;
185import android.content.pm.UserInfo;
186import android.content.pm.VerifierDeviceIdentity;
187import android.content.pm.VerifierInfo;
188import android.content.pm.VersionedPackage;
189import android.content.pm.dex.IArtManager;
190import android.content.res.Resources;
191import android.database.ContentObserver;
192import android.graphics.Bitmap;
193import android.hardware.display.DisplayManager;
194import android.net.Uri;
195import android.os.Binder;
196import android.os.Build;
197import android.os.Bundle;
198import android.os.Debug;
199import android.os.Environment;
200import android.os.Environment.UserEnvironment;
201import android.os.FileUtils;
202import android.os.Handler;
203import android.os.IBinder;
204import android.os.Looper;
205import android.os.Message;
206import android.os.Parcel;
207import android.os.ParcelFileDescriptor;
208import android.os.PatternMatcher;
209import android.os.Process;
210import android.os.RemoteCallbackList;
211import android.os.RemoteException;
212import android.os.ResultReceiver;
213import android.os.SELinux;
214import android.os.ServiceManager;
215import android.os.ShellCallback;
216import android.os.SystemClock;
217import android.os.SystemProperties;
218import android.os.Trace;
219import android.os.UserHandle;
220import android.os.UserManager;
221import android.os.UserManagerInternal;
222import android.os.storage.IStorageManager;
223import android.os.storage.StorageEventListener;
224import android.os.storage.StorageManager;
225import android.os.storage.StorageManagerInternal;
226import android.os.storage.VolumeInfo;
227import android.os.storage.VolumeRecord;
228import android.provider.Settings.Global;
229import android.provider.Settings.Secure;
230import android.security.KeyStore;
231import android.security.SystemKeyStore;
232import android.service.pm.PackageServiceDumpProto;
233import android.system.ErrnoException;
234import android.system.Os;
235import android.text.TextUtils;
236import android.text.format.DateUtils;
237import android.util.ArrayMap;
238import android.util.ArraySet;
239import android.util.Base64;
240import android.util.DisplayMetrics;
241import android.util.EventLog;
242import android.util.ExceptionUtils;
243import android.util.Log;
244import android.util.LogPrinter;
245import android.util.LongSparseArray;
246import android.util.LongSparseLongArray;
247import android.util.MathUtils;
248import android.util.PackageUtils;
249import android.util.Pair;
250import android.util.PrintStreamPrinter;
251import android.util.Slog;
252import android.util.SparseArray;
253import android.util.SparseBooleanArray;
254import android.util.SparseIntArray;
255import android.util.TimingsTraceLog;
256import android.util.Xml;
257import android.util.jar.StrictJarFile;
258import android.util.proto.ProtoOutputStream;
259import android.view.Display;
260
261import com.android.internal.R;
262import com.android.internal.annotations.GuardedBy;
263import com.android.internal.app.IMediaContainerService;
264import com.android.internal.app.ResolverActivity;
265import com.android.internal.content.NativeLibraryHelper;
266import com.android.internal.content.PackageHelper;
267import com.android.internal.logging.MetricsLogger;
268import com.android.internal.os.IParcelFileDescriptorFactory;
269import com.android.internal.os.SomeArgs;
270import com.android.internal.os.Zygote;
271import com.android.internal.telephony.CarrierAppUtils;
272import com.android.internal.util.ArrayUtils;
273import com.android.internal.util.ConcurrentUtils;
274import com.android.internal.util.DumpUtils;
275import com.android.internal.util.FastXmlSerializer;
276import com.android.internal.util.IndentingPrintWriter;
277import com.android.internal.util.Preconditions;
278import com.android.internal.util.XmlUtils;
279import com.android.server.AttributeCache;
280import com.android.server.DeviceIdleController;
281import com.android.server.EventLogTags;
282import com.android.server.FgThread;
283import com.android.server.IntentResolver;
284import com.android.server.LocalServices;
285import com.android.server.LockGuard;
286import com.android.server.ServiceThread;
287import com.android.server.SystemConfig;
288import com.android.server.SystemServerInitThreadPool;
289import com.android.server.Watchdog;
290import com.android.server.net.NetworkPolicyManagerInternal;
291import com.android.server.pm.Installer.InstallerException;
292import com.android.server.pm.Settings.DatabaseVersion;
293import com.android.server.pm.Settings.VersionInfo;
294import com.android.server.pm.dex.ArtManagerService;
295import com.android.server.pm.dex.DexLogger;
296import com.android.server.pm.dex.DexManager;
297import com.android.server.pm.dex.DexoptOptions;
298import com.android.server.pm.dex.PackageDexUsage;
299import com.android.server.pm.permission.BasePermission;
300import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
301import com.android.server.pm.permission.PermissionManagerService;
302import com.android.server.pm.permission.PermissionManagerInternal;
303import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
304import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
305import com.android.server.pm.permission.PermissionsState;
306import com.android.server.pm.permission.PermissionsState.PermissionState;
307import com.android.server.storage.DeviceStorageMonitorInternal;
308
309import dalvik.system.CloseGuard;
310import dalvik.system.VMRuntime;
311
312import libcore.io.IoUtils;
313
314import org.xmlpull.v1.XmlPullParser;
315import org.xmlpull.v1.XmlPullParserException;
316import org.xmlpull.v1.XmlSerializer;
317
318import java.io.BufferedOutputStream;
319import java.io.ByteArrayInputStream;
320import java.io.ByteArrayOutputStream;
321import java.io.File;
322import java.io.FileDescriptor;
323import java.io.FileInputStream;
324import java.io.FileOutputStream;
325import java.io.FilenameFilter;
326import java.io.IOException;
327import java.io.PrintWriter;
328import java.lang.annotation.Retention;
329import java.lang.annotation.RetentionPolicy;
330import java.nio.charset.StandardCharsets;
331import java.security.DigestInputStream;
332import java.security.MessageDigest;
333import java.security.NoSuchAlgorithmException;
334import java.security.PublicKey;
335import java.security.SecureRandom;
336import java.security.cert.Certificate;
337import java.security.cert.CertificateException;
338import java.util.ArrayList;
339import java.util.Arrays;
340import java.util.Collection;
341import java.util.Collections;
342import java.util.Comparator;
343import java.util.HashMap;
344import java.util.HashSet;
345import java.util.Iterator;
346import java.util.LinkedHashSet;
347import java.util.List;
348import java.util.Map;
349import java.util.Objects;
350import java.util.Set;
351import java.util.concurrent.CountDownLatch;
352import java.util.concurrent.Future;
353import java.util.concurrent.TimeUnit;
354import java.util.concurrent.atomic.AtomicBoolean;
355import java.util.concurrent.atomic.AtomicInteger;
356
357/**
358 * Keep track of all those APKs everywhere.
359 * <p>
360 * Internally there are two important locks:
361 * <ul>
362 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
363 * and other related state. It is a fine-grained lock that should only be held
364 * momentarily, as it's one of the most contended locks in the system.
365 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
366 * operations typically involve heavy lifting of application data on disk. Since
367 * {@code installd} is single-threaded, and it's operations can often be slow,
368 * this lock should never be acquired while already holding {@link #mPackages}.
369 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
370 * holding {@link #mInstallLock}.
371 * </ul>
372 * Many internal methods rely on the caller to hold the appropriate locks, and
373 * this contract is expressed through method name suffixes:
374 * <ul>
375 * <li>fooLI(): the caller must hold {@link #mInstallLock}
376 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
377 * being modified must be frozen
378 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
379 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
380 * </ul>
381 * <p>
382 * Because this class is very central to the platform's security; please run all
383 * CTS and unit tests whenever making modifications:
384 *
385 * <pre>
386 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
387 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
388 * </pre>
389 */
390public class PackageManagerService extends IPackageManager.Stub
391        implements PackageSender {
392    static final String TAG = "PackageManager";
393    public static final boolean DEBUG_SETTINGS = false;
394    static final boolean DEBUG_PREFERRED = false;
395    static final boolean DEBUG_UPGRADE = false;
396    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
397    private static final boolean DEBUG_BACKUP = false;
398    public static final boolean DEBUG_INSTALL = false;
399    public static final boolean DEBUG_REMOVE = false;
400    private static final boolean DEBUG_BROADCASTS = false;
401    private static final boolean DEBUG_SHOW_INFO = false;
402    private static final boolean DEBUG_PACKAGE_INFO = false;
403    private static final boolean DEBUG_INTENT_MATCHING = false;
404    public static final boolean DEBUG_PACKAGE_SCANNING = false;
405    private static final boolean DEBUG_VERIFY = false;
406    private static final boolean DEBUG_FILTERS = false;
407    public static final boolean DEBUG_PERMISSIONS = false;
408    private static final boolean DEBUG_SHARED_LIBRARIES = false;
409    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
410
411    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
412    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
413    // user, but by default initialize to this.
414    public static final boolean DEBUG_DEXOPT = false;
415
416    private static final boolean DEBUG_ABI_SELECTION = false;
417    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
418    private static final boolean DEBUG_TRIAGED_MISSING = false;
419    private static final boolean DEBUG_APP_DATA = false;
420
421    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
422    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
423
424    private static final boolean HIDE_EPHEMERAL_APIS = false;
425
426    private static final boolean ENABLE_FREE_CACHE_V2 =
427            SystemProperties.getBoolean("fw.free_cache_v2", true);
428
429    private static final int RADIO_UID = Process.PHONE_UID;
430    private static final int LOG_UID = Process.LOG_UID;
431    private static final int NFC_UID = Process.NFC_UID;
432    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
433    private static final int SHELL_UID = Process.SHELL_UID;
434
435    // Suffix used during package installation when copying/moving
436    // package apks to install directory.
437    private static final String INSTALL_PACKAGE_SUFFIX = "-";
438
439    static final int SCAN_NO_DEX = 1<<0;
440    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
441    static final int SCAN_NEW_INSTALL = 1<<2;
442    static final int SCAN_UPDATE_TIME = 1<<3;
443    static final int SCAN_BOOTING = 1<<4;
444    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
445    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
446    static final int SCAN_REQUIRE_KNOWN = 1<<7;
447    static final int SCAN_MOVE = 1<<8;
448    static final int SCAN_INITIAL = 1<<9;
449    static final int SCAN_CHECK_ONLY = 1<<10;
450    static final int SCAN_DONT_KILL_APP = 1<<11;
451    static final int SCAN_IGNORE_FROZEN = 1<<12;
452    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
453    static final int SCAN_AS_INSTANT_APP = 1<<14;
454    static final int SCAN_AS_FULL_APP = 1<<15;
455    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
456    static final int SCAN_AS_SYSTEM = 1<<17;
457    static final int SCAN_AS_PRIVILEGED = 1<<18;
458    static final int SCAN_AS_OEM = 1<<19;
459    static final int SCAN_AS_VENDOR = 1<<20;
460
461    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
462            SCAN_NO_DEX,
463            SCAN_UPDATE_SIGNATURE,
464            SCAN_NEW_INSTALL,
465            SCAN_UPDATE_TIME,
466            SCAN_BOOTING,
467            SCAN_TRUSTED_OVERLAY,
468            SCAN_DELETE_DATA_ON_FAILURES,
469            SCAN_REQUIRE_KNOWN,
470            SCAN_MOVE,
471            SCAN_INITIAL,
472            SCAN_CHECK_ONLY,
473            SCAN_DONT_KILL_APP,
474            SCAN_IGNORE_FROZEN,
475            SCAN_FIRST_BOOT_OR_UPGRADE,
476            SCAN_AS_INSTANT_APP,
477            SCAN_AS_FULL_APP,
478            SCAN_AS_VIRTUAL_PRELOAD,
479    })
480    @Retention(RetentionPolicy.SOURCE)
481    public @interface ScanFlags {}
482
483    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
484    /** Extension of the compressed packages */
485    public final static String COMPRESSED_EXTENSION = ".gz";
486    /** Suffix of stub packages on the system partition */
487    public final static String STUB_SUFFIX = "-Stub";
488
489    private static final int[] EMPTY_INT_ARRAY = new int[0];
490
491    private static final int TYPE_UNKNOWN = 0;
492    private static final int TYPE_ACTIVITY = 1;
493    private static final int TYPE_RECEIVER = 2;
494    private static final int TYPE_SERVICE = 3;
495    private static final int TYPE_PROVIDER = 4;
496    @IntDef(prefix = { "TYPE_" }, value = {
497            TYPE_UNKNOWN,
498            TYPE_ACTIVITY,
499            TYPE_RECEIVER,
500            TYPE_SERVICE,
501            TYPE_PROVIDER,
502    })
503    @Retention(RetentionPolicy.SOURCE)
504    public @interface ComponentType {}
505
506    /**
507     * Timeout (in milliseconds) after which the watchdog should declare that
508     * our handler thread is wedged.  The usual default for such things is one
509     * minute but we sometimes do very lengthy I/O operations on this thread,
510     * such as installing multi-gigabyte applications, so ours needs to be longer.
511     */
512    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
513
514    /**
515     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
516     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
517     * settings entry if available, otherwise we use the hardcoded default.  If it's been
518     * more than this long since the last fstrim, we force one during the boot sequence.
519     *
520     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
521     * one gets run at the next available charging+idle time.  This final mandatory
522     * no-fstrim check kicks in only of the other scheduling criteria is never met.
523     */
524    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
525
526    /**
527     * Whether verification is enabled by default.
528     */
529    private static final boolean DEFAULT_VERIFY_ENABLE = true;
530
531    /**
532     * The default maximum time to wait for the verification agent to return in
533     * milliseconds.
534     */
535    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
536
537    /**
538     * The default response for package verification timeout.
539     *
540     * This can be either PackageManager.VERIFICATION_ALLOW or
541     * PackageManager.VERIFICATION_REJECT.
542     */
543    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
544
545    public static final String PLATFORM_PACKAGE_NAME = "android";
546
547    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
548
549    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
550            DEFAULT_CONTAINER_PACKAGE,
551            "com.android.defcontainer.DefaultContainerService");
552
553    private static final String KILL_APP_REASON_GIDS_CHANGED =
554            "permission grant or revoke changed gids";
555
556    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
557            "permissions revoked";
558
559    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
560
561    private static final String PACKAGE_SCHEME = "package";
562
563    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
564
565    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
566
567    /** Canonical intent used to identify what counts as a "web browser" app */
568    private static final Intent sBrowserIntent;
569    static {
570        sBrowserIntent = new Intent();
571        sBrowserIntent.setAction(Intent.ACTION_VIEW);
572        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
573        sBrowserIntent.setData(Uri.parse("http:"));
574    }
575
576    /**
577     * The set of all protected actions [i.e. those actions for which a high priority
578     * intent filter is disallowed].
579     */
580    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
581    static {
582        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
583        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
584        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
585        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
586    }
587
588    // Compilation reasons.
589    public static final int REASON_FIRST_BOOT = 0;
590    public static final int REASON_BOOT = 1;
591    public static final int REASON_INSTALL = 2;
592    public static final int REASON_BACKGROUND_DEXOPT = 3;
593    public static final int REASON_AB_OTA = 4;
594    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
595    public static final int REASON_SHARED = 6;
596
597    public static final int REASON_LAST = REASON_SHARED;
598
599    /**
600     * Version number for the package parser cache. Increment this whenever the format or
601     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
602     */
603    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
604
605    /**
606     * Whether the package parser cache is enabled.
607     */
608    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
609
610    /**
611     * Permissions required in order to receive instant application lifecycle broadcasts.
612     */
613    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
614            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
615
616    final ServiceThread mHandlerThread;
617
618    final PackageHandler mHandler;
619
620    private final ProcessLoggingHandler mProcessLoggingHandler;
621
622    /**
623     * Messages for {@link #mHandler} that need to wait for system ready before
624     * being dispatched.
625     */
626    private ArrayList<Message> mPostSystemReadyMessages;
627
628    final int mSdkVersion = Build.VERSION.SDK_INT;
629
630    final Context mContext;
631    final boolean mFactoryTest;
632    final boolean mOnlyCore;
633    final DisplayMetrics mMetrics;
634    final int mDefParseFlags;
635    final String[] mSeparateProcesses;
636    final boolean mIsUpgrade;
637    final boolean mIsPreNUpgrade;
638    final boolean mIsPreNMR1Upgrade;
639
640    // Have we told the Activity Manager to whitelist the default container service by uid yet?
641    @GuardedBy("mPackages")
642    boolean mDefaultContainerWhitelisted = false;
643
644    @GuardedBy("mPackages")
645    private boolean mDexOptDialogShown;
646
647    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
648    // LOCK HELD.  Can be called with mInstallLock held.
649    @GuardedBy("mInstallLock")
650    final Installer mInstaller;
651
652    /** Directory where installed applications are stored */
653    private static final File sAppInstallDir =
654            new File(Environment.getDataDirectory(), "app");
655    /** Directory where installed application's 32-bit native libraries are copied. */
656    private static final File sAppLib32InstallDir =
657            new File(Environment.getDataDirectory(), "app-lib");
658    /** Directory where code and non-resource assets of forward-locked applications are stored */
659    private static final File sDrmAppPrivateInstallDir =
660            new File(Environment.getDataDirectory(), "app-private");
661
662    // ----------------------------------------------------------------
663
664    // Lock for state used when installing and doing other long running
665    // operations.  Methods that must be called with this lock held have
666    // the suffix "LI".
667    final Object mInstallLock = new Object();
668
669    // ----------------------------------------------------------------
670
671    // Keys are String (package name), values are Package.  This also serves
672    // as the lock for the global state.  Methods that must be called with
673    // this lock held have the prefix "LP".
674    @GuardedBy("mPackages")
675    final ArrayMap<String, PackageParser.Package> mPackages =
676            new ArrayMap<String, PackageParser.Package>();
677
678    final ArrayMap<String, Set<String>> mKnownCodebase =
679            new ArrayMap<String, Set<String>>();
680
681    // Keys are isolated uids and values are the uid of the application
682    // that created the isolated proccess.
683    @GuardedBy("mPackages")
684    final SparseIntArray mIsolatedOwners = new SparseIntArray();
685
686    /**
687     * Tracks new system packages [received in an OTA] that we expect to
688     * find updated user-installed versions. Keys are package name, values
689     * are package location.
690     */
691    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
692    /**
693     * Tracks high priority intent filters for protected actions. During boot, certain
694     * filter actions are protected and should never be allowed to have a high priority
695     * intent filter for them. However, there is one, and only one exception -- the
696     * setup wizard. It must be able to define a high priority intent filter for these
697     * actions to ensure there are no escapes from the wizard. We need to delay processing
698     * of these during boot as we need to look at all of the system packages in order
699     * to know which component is the setup wizard.
700     */
701    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
702    /**
703     * Whether or not processing protected filters should be deferred.
704     */
705    private boolean mDeferProtectedFilters = true;
706
707    /**
708     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
709     */
710    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
711    /**
712     * Whether or not system app permissions should be promoted from install to runtime.
713     */
714    boolean mPromoteSystemApps;
715
716    @GuardedBy("mPackages")
717    final Settings mSettings;
718
719    /**
720     * Set of package names that are currently "frozen", which means active
721     * surgery is being done on the code/data for that package. The platform
722     * will refuse to launch frozen packages to avoid race conditions.
723     *
724     * @see PackageFreezer
725     */
726    @GuardedBy("mPackages")
727    final ArraySet<String> mFrozenPackages = new ArraySet<>();
728
729    final ProtectedPackages mProtectedPackages;
730
731    @GuardedBy("mLoadedVolumes")
732    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
733
734    boolean mFirstBoot;
735
736    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
737
738    @GuardedBy("mAvailableFeatures")
739    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
740
741    private final InstantAppRegistry mInstantAppRegistry;
742
743    @GuardedBy("mPackages")
744    int mChangedPackagesSequenceNumber;
745    /**
746     * List of changed [installed, removed or updated] packages.
747     * mapping from user id -> sequence number -> package name
748     */
749    @GuardedBy("mPackages")
750    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
751    /**
752     * The sequence number of the last change to a package.
753     * mapping from user id -> package name -> sequence number
754     */
755    @GuardedBy("mPackages")
756    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
757
758    class PackageParserCallback implements PackageParser.Callback {
759        @Override public final boolean hasFeature(String feature) {
760            return PackageManagerService.this.hasSystemFeature(feature, 0);
761        }
762
763        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
764                Collection<PackageParser.Package> allPackages, String targetPackageName) {
765            List<PackageParser.Package> overlayPackages = null;
766            for (PackageParser.Package p : allPackages) {
767                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
768                    if (overlayPackages == null) {
769                        overlayPackages = new ArrayList<PackageParser.Package>();
770                    }
771                    overlayPackages.add(p);
772                }
773            }
774            if (overlayPackages != null) {
775                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
776                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
777                        return p1.mOverlayPriority - p2.mOverlayPriority;
778                    }
779                };
780                Collections.sort(overlayPackages, cmp);
781            }
782            return overlayPackages;
783        }
784
785        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
786                String targetPackageName, String targetPath) {
787            if ("android".equals(targetPackageName)) {
788                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
789                // native AssetManager.
790                return null;
791            }
792            List<PackageParser.Package> overlayPackages =
793                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
794            if (overlayPackages == null || overlayPackages.isEmpty()) {
795                return null;
796            }
797            List<String> overlayPathList = null;
798            for (PackageParser.Package overlayPackage : overlayPackages) {
799                if (targetPath == null) {
800                    if (overlayPathList == null) {
801                        overlayPathList = new ArrayList<String>();
802                    }
803                    overlayPathList.add(overlayPackage.baseCodePath);
804                    continue;
805                }
806
807                try {
808                    // Creates idmaps for system to parse correctly the Android manifest of the
809                    // target package.
810                    //
811                    // OverlayManagerService will update each of them with a correct gid from its
812                    // target package app id.
813                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
814                            UserHandle.getSharedAppGid(
815                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                } catch (InstallerException e) {
821                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
822                            overlayPackage.baseCodePath);
823                }
824            }
825            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
826        }
827
828        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
829            synchronized (mPackages) {
830                return getStaticOverlayPathsLocked(
831                        mPackages.values(), targetPackageName, targetPath);
832            }
833        }
834
835        @Override public final String[] getOverlayApks(String targetPackageName) {
836            return getStaticOverlayPaths(targetPackageName, null);
837        }
838
839        @Override public final String[] getOverlayPaths(String targetPackageName,
840                String targetPath) {
841            return getStaticOverlayPaths(targetPackageName, targetPath);
842        }
843    }
844
845    class ParallelPackageParserCallback extends PackageParserCallback {
846        List<PackageParser.Package> mOverlayPackages = null;
847
848        void findStaticOverlayPackages() {
849            synchronized (mPackages) {
850                for (PackageParser.Package p : mPackages.values()) {
851                    if (p.mIsStaticOverlay) {
852                        if (mOverlayPackages == null) {
853                            mOverlayPackages = new ArrayList<PackageParser.Package>();
854                        }
855                        mOverlayPackages.add(p);
856                    }
857                }
858            }
859        }
860
861        @Override
862        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
863            // We can trust mOverlayPackages without holding mPackages because package uninstall
864            // can't happen while running parallel parsing.
865            // Moreover holding mPackages on each parsing thread causes dead-lock.
866            return mOverlayPackages == null ? null :
867                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
868        }
869    }
870
871    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
872    final ParallelPackageParserCallback mParallelPackageParserCallback =
873            new ParallelPackageParserCallback();
874
875    public static final class SharedLibraryEntry {
876        public final @Nullable String path;
877        public final @Nullable String apk;
878        public final @NonNull SharedLibraryInfo info;
879
880        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
881                String declaringPackageName, long declaringPackageVersionCode) {
882            path = _path;
883            apk = _apk;
884            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
885                    declaringPackageName, declaringPackageVersionCode), null);
886        }
887    }
888
889    // Currently known shared libraries.
890    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
891    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
892            new ArrayMap<>();
893
894    // All available activities, for your resolving pleasure.
895    final ActivityIntentResolver mActivities =
896            new ActivityIntentResolver();
897
898    // All available receivers, for your resolving pleasure.
899    final ActivityIntentResolver mReceivers =
900            new ActivityIntentResolver();
901
902    // All available services, for your resolving pleasure.
903    final ServiceIntentResolver mServices = new ServiceIntentResolver();
904
905    // All available providers, for your resolving pleasure.
906    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
907
908    // Mapping from provider base names (first directory in content URI codePath)
909    // to the provider information.
910    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
911            new ArrayMap<String, PackageParser.Provider>();
912
913    // Mapping from instrumentation class names to info about them.
914    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
915            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
916
917    // Packages whose data we have transfered into another package, thus
918    // should no longer exist.
919    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
920
921    // Broadcast actions that are only available to the system.
922    @GuardedBy("mProtectedBroadcasts")
923    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
924
925    /** List of packages waiting for verification. */
926    final SparseArray<PackageVerificationState> mPendingVerification
927            = new SparseArray<PackageVerificationState>();
928
929    final PackageInstallerService mInstallerService;
930
931    final ArtManagerService mArtManagerService;
932
933    private final PackageDexOptimizer mPackageDexOptimizer;
934    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
935    // is used by other apps).
936    private final DexManager mDexManager;
937
938    private AtomicInteger mNextMoveId = new AtomicInteger();
939    private final MoveCallbacks mMoveCallbacks;
940
941    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
942
943    // Cache of users who need badging.
944    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
945
946    /** Token for keys in mPendingVerification. */
947    private int mPendingVerificationToken = 0;
948
949    volatile boolean mSystemReady;
950    volatile boolean mSafeMode;
951    volatile boolean mHasSystemUidErrors;
952    private volatile boolean mEphemeralAppsDisabled;
953
954    ApplicationInfo mAndroidApplication;
955    final ActivityInfo mResolveActivity = new ActivityInfo();
956    final ResolveInfo mResolveInfo = new ResolveInfo();
957    ComponentName mResolveComponentName;
958    PackageParser.Package mPlatformPackage;
959    ComponentName mCustomResolverComponentName;
960
961    boolean mResolverReplaced = false;
962
963    private final @Nullable ComponentName mIntentFilterVerifierComponent;
964    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
965
966    private int mIntentFilterVerificationToken = 0;
967
968    /** The service connection to the ephemeral resolver */
969    final EphemeralResolverConnection mInstantAppResolverConnection;
970    /** Component used to show resolver settings for Instant Apps */
971    final ComponentName mInstantAppResolverSettingsComponent;
972
973    /** Activity used to install instant applications */
974    ActivityInfo mInstantAppInstallerActivity;
975    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
976
977    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
978            = new SparseArray<IntentFilterVerificationState>();
979
980    // TODO remove this and go through mPermissonManager directly
981    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
982    private final PermissionManagerInternal mPermissionManager;
983
984    // List of packages names to keep cached, even if they are uninstalled for all users
985    private List<String> mKeepUninstalledPackages;
986
987    private UserManagerInternal mUserManagerInternal;
988
989    private DeviceIdleController.LocalService mDeviceIdleController;
990
991    private File mCacheDir;
992
993    private Future<?> mPrepareAppDataFuture;
994
995    private static class IFVerificationParams {
996        PackageParser.Package pkg;
997        boolean replacing;
998        int userId;
999        int verifierUid;
1000
1001        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1002                int _userId, int _verifierUid) {
1003            pkg = _pkg;
1004            replacing = _replacing;
1005            userId = _userId;
1006            replacing = _replacing;
1007            verifierUid = _verifierUid;
1008        }
1009    }
1010
1011    private interface IntentFilterVerifier<T extends IntentFilter> {
1012        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1013                                               T filter, String packageName);
1014        void startVerifications(int userId);
1015        void receiveVerificationResponse(int verificationId);
1016    }
1017
1018    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1019        private Context mContext;
1020        private ComponentName mIntentFilterVerifierComponent;
1021        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1022
1023        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1024            mContext = context;
1025            mIntentFilterVerifierComponent = verifierComponent;
1026        }
1027
1028        private String getDefaultScheme() {
1029            return IntentFilter.SCHEME_HTTPS;
1030        }
1031
1032        @Override
1033        public void startVerifications(int userId) {
1034            // Launch verifications requests
1035            int count = mCurrentIntentFilterVerifications.size();
1036            for (int n=0; n<count; n++) {
1037                int verificationId = mCurrentIntentFilterVerifications.get(n);
1038                final IntentFilterVerificationState ivs =
1039                        mIntentFilterVerificationStates.get(verificationId);
1040
1041                String packageName = ivs.getPackageName();
1042
1043                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1044                final int filterCount = filters.size();
1045                ArraySet<String> domainsSet = new ArraySet<>();
1046                for (int m=0; m<filterCount; m++) {
1047                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1048                    domainsSet.addAll(filter.getHostsList());
1049                }
1050                synchronized (mPackages) {
1051                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1052                            packageName, domainsSet) != null) {
1053                        scheduleWriteSettingsLocked();
1054                    }
1055                }
1056                sendVerificationRequest(verificationId, ivs);
1057            }
1058            mCurrentIntentFilterVerifications.clear();
1059        }
1060
1061        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1062            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1063            verificationIntent.putExtra(
1064                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1065                    verificationId);
1066            verificationIntent.putExtra(
1067                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1068                    getDefaultScheme());
1069            verificationIntent.putExtra(
1070                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1071                    ivs.getHostsString());
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1074                    ivs.getPackageName());
1075            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1076            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1077
1078            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1079            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1080                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1081                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1082
1083            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1084            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1085                    "Sending IntentFilter verification broadcast");
1086        }
1087
1088        public void receiveVerificationResponse(int verificationId) {
1089            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1090
1091            final boolean verified = ivs.isVerified();
1092
1093            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1094            final int count = filters.size();
1095            if (DEBUG_DOMAIN_VERIFICATION) {
1096                Slog.i(TAG, "Received verification response " + verificationId
1097                        + " for " + count + " filters, verified=" + verified);
1098            }
1099            for (int n=0; n<count; n++) {
1100                PackageParser.ActivityIntentInfo filter = filters.get(n);
1101                filter.setVerified(verified);
1102
1103                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1104                        + " verified with result:" + verified + " and hosts:"
1105                        + ivs.getHostsString());
1106            }
1107
1108            mIntentFilterVerificationStates.remove(verificationId);
1109
1110            final String packageName = ivs.getPackageName();
1111            IntentFilterVerificationInfo ivi = null;
1112
1113            synchronized (mPackages) {
1114                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1115            }
1116            if (ivi == null) {
1117                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1118                        + verificationId + " packageName:" + packageName);
1119                return;
1120            }
1121            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1122                    "Updating IntentFilterVerificationInfo for package " + packageName
1123                            +" verificationId:" + verificationId);
1124
1125            synchronized (mPackages) {
1126                if (verified) {
1127                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1128                } else {
1129                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1130                }
1131                scheduleWriteSettingsLocked();
1132
1133                final int userId = ivs.getUserId();
1134                if (userId != UserHandle.USER_ALL) {
1135                    final int userStatus =
1136                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1137
1138                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1139                    boolean needUpdate = false;
1140
1141                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1142                    // already been set by the User thru the Disambiguation dialog
1143                    switch (userStatus) {
1144                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1145                            if (verified) {
1146                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1147                            } else {
1148                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1149                            }
1150                            needUpdate = true;
1151                            break;
1152
1153                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1154                            if (verified) {
1155                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1156                                needUpdate = true;
1157                            }
1158                            break;
1159
1160                        default:
1161                            // Nothing to do
1162                    }
1163
1164                    if (needUpdate) {
1165                        mSettings.updateIntentFilterVerificationStatusLPw(
1166                                packageName, updatedStatus, userId);
1167                        scheduleWritePackageRestrictionsLocked(userId);
1168                    }
1169                }
1170            }
1171        }
1172
1173        @Override
1174        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1175                    ActivityIntentInfo filter, String packageName) {
1176            if (!hasValidDomains(filter)) {
1177                return false;
1178            }
1179            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1180            if (ivs == null) {
1181                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1182                        packageName);
1183            }
1184            if (DEBUG_DOMAIN_VERIFICATION) {
1185                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1186            }
1187            ivs.addFilter(filter);
1188            return true;
1189        }
1190
1191        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1192                int userId, int verificationId, String packageName) {
1193            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1194                    verifierUid, userId, packageName);
1195            ivs.setPendingState();
1196            synchronized (mPackages) {
1197                mIntentFilterVerificationStates.append(verificationId, ivs);
1198                mCurrentIntentFilterVerifications.add(verificationId);
1199            }
1200            return ivs;
1201        }
1202    }
1203
1204    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1205        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1206                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1207                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1208    }
1209
1210    // Set of pending broadcasts for aggregating enable/disable of components.
1211    static class PendingPackageBroadcasts {
1212        // for each user id, a map of <package name -> components within that package>
1213        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1214
1215        public PendingPackageBroadcasts() {
1216            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1217        }
1218
1219        public ArrayList<String> get(int userId, String packageName) {
1220            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1221            return packages.get(packageName);
1222        }
1223
1224        public void put(int userId, String packageName, ArrayList<String> components) {
1225            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1226            packages.put(packageName, components);
1227        }
1228
1229        public void remove(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1231            if (packages != null) {
1232                packages.remove(packageName);
1233            }
1234        }
1235
1236        public void remove(int userId) {
1237            mUidMap.remove(userId);
1238        }
1239
1240        public int userIdCount() {
1241            return mUidMap.size();
1242        }
1243
1244        public int userIdAt(int n) {
1245            return mUidMap.keyAt(n);
1246        }
1247
1248        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1249            return mUidMap.get(userId);
1250        }
1251
1252        public int size() {
1253            // total number of pending broadcast entries across all userIds
1254            int num = 0;
1255            for (int i = 0; i< mUidMap.size(); i++) {
1256                num += mUidMap.valueAt(i).size();
1257            }
1258            return num;
1259        }
1260
1261        public void clear() {
1262            mUidMap.clear();
1263        }
1264
1265        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1266            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1267            if (map == null) {
1268                map = new ArrayMap<String, ArrayList<String>>();
1269                mUidMap.put(userId, map);
1270            }
1271            return map;
1272        }
1273    }
1274    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1275
1276    // Service Connection to remote media container service to copy
1277    // package uri's from external media onto secure containers
1278    // or internal storage.
1279    private IMediaContainerService mContainerService = null;
1280
1281    static final int SEND_PENDING_BROADCAST = 1;
1282    static final int MCS_BOUND = 3;
1283    static final int END_COPY = 4;
1284    static final int INIT_COPY = 5;
1285    static final int MCS_UNBIND = 6;
1286    static final int START_CLEANING_PACKAGE = 7;
1287    static final int FIND_INSTALL_LOC = 8;
1288    static final int POST_INSTALL = 9;
1289    static final int MCS_RECONNECT = 10;
1290    static final int MCS_GIVE_UP = 11;
1291    static final int WRITE_SETTINGS = 13;
1292    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1293    static final int PACKAGE_VERIFIED = 15;
1294    static final int CHECK_PENDING_VERIFICATION = 16;
1295    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1296    static final int INTENT_FILTER_VERIFIED = 18;
1297    static final int WRITE_PACKAGE_LIST = 19;
1298    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1299
1300    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1301
1302    // Delay time in millisecs
1303    static final int BROADCAST_DELAY = 10 * 1000;
1304
1305    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1306            2 * 60 * 60 * 1000L; /* two hours */
1307
1308    static UserManagerService sUserManager;
1309
1310    // Stores a list of users whose package restrictions file needs to be updated
1311    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1312
1313    final private DefaultContainerConnection mDefContainerConn =
1314            new DefaultContainerConnection();
1315    class DefaultContainerConnection implements ServiceConnection {
1316        public void onServiceConnected(ComponentName name, IBinder service) {
1317            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1318            final IMediaContainerService imcs = IMediaContainerService.Stub
1319                    .asInterface(Binder.allowBlocking(service));
1320            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1321        }
1322
1323        public void onServiceDisconnected(ComponentName name) {
1324            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1325        }
1326    }
1327
1328    // Recordkeeping of restore-after-install operations that are currently in flight
1329    // between the Package Manager and the Backup Manager
1330    static class PostInstallData {
1331        public InstallArgs args;
1332        public PackageInstalledInfo res;
1333
1334        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1335            args = _a;
1336            res = _r;
1337        }
1338    }
1339
1340    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1341    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1342
1343    // XML tags for backup/restore of various bits of state
1344    private static final String TAG_PREFERRED_BACKUP = "pa";
1345    private static final String TAG_DEFAULT_APPS = "da";
1346    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1347
1348    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1349    private static final String TAG_ALL_GRANTS = "rt-grants";
1350    private static final String TAG_GRANT = "grant";
1351    private static final String ATTR_PACKAGE_NAME = "pkg";
1352
1353    private static final String TAG_PERMISSION = "perm";
1354    private static final String ATTR_PERMISSION_NAME = "name";
1355    private static final String ATTR_IS_GRANTED = "g";
1356    private static final String ATTR_USER_SET = "set";
1357    private static final String ATTR_USER_FIXED = "fixed";
1358    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1359
1360    // System/policy permission grants are not backed up
1361    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1362            FLAG_PERMISSION_POLICY_FIXED
1363            | FLAG_PERMISSION_SYSTEM_FIXED
1364            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1365
1366    // And we back up these user-adjusted states
1367    private static final int USER_RUNTIME_GRANT_MASK =
1368            FLAG_PERMISSION_USER_SET
1369            | FLAG_PERMISSION_USER_FIXED
1370            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1371
1372    final @Nullable String mRequiredVerifierPackage;
1373    final @NonNull String mRequiredInstallerPackage;
1374    final @NonNull String mRequiredUninstallerPackage;
1375    final @Nullable String mSetupWizardPackage;
1376    final @Nullable String mStorageManagerPackage;
1377    final @NonNull String mServicesSystemSharedLibraryPackageName;
1378    final @NonNull String mSharedSystemSharedLibraryPackageName;
1379
1380    private final PackageUsage mPackageUsage = new PackageUsage();
1381    private final CompilerStats mCompilerStats = new CompilerStats();
1382
1383    class PackageHandler extends Handler {
1384        private boolean mBound = false;
1385        final ArrayList<HandlerParams> mPendingInstalls =
1386            new ArrayList<HandlerParams>();
1387
1388        private boolean connectToService() {
1389            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1390                    " DefaultContainerService");
1391            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1392            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1393            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1394                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1395                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1396                mBound = true;
1397                return true;
1398            }
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1400            return false;
1401        }
1402
1403        private void disconnectService() {
1404            mContainerService = null;
1405            mBound = false;
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407            mContext.unbindService(mDefContainerConn);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409        }
1410
1411        PackageHandler(Looper looper) {
1412            super(looper);
1413        }
1414
1415        public void handleMessage(Message msg) {
1416            try {
1417                doHandleMessage(msg);
1418            } finally {
1419                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420            }
1421        }
1422
1423        void doHandleMessage(Message msg) {
1424            switch (msg.what) {
1425                case INIT_COPY: {
1426                    HandlerParams params = (HandlerParams) msg.obj;
1427                    int idx = mPendingInstalls.size();
1428                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1429                    // If a bind was already initiated we dont really
1430                    // need to do anything. The pending install
1431                    // will be processed later on.
1432                    if (!mBound) {
1433                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1434                                System.identityHashCode(mHandler));
1435                        // If this is the only one pending we might
1436                        // have to bind to the service again.
1437                        if (!connectToService()) {
1438                            Slog.e(TAG, "Failed to bind to media container service");
1439                            params.serviceError();
1440                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1441                                    System.identityHashCode(mHandler));
1442                            if (params.traceMethod != null) {
1443                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1444                                        params.traceCookie);
1445                            }
1446                            return;
1447                        } else {
1448                            // Once we bind to the service, the first
1449                            // pending request will be processed.
1450                            mPendingInstalls.add(idx, params);
1451                        }
1452                    } else {
1453                        mPendingInstalls.add(idx, params);
1454                        // Already bound to the service. Just make
1455                        // sure we trigger off processing the first request.
1456                        if (idx == 0) {
1457                            mHandler.sendEmptyMessage(MCS_BOUND);
1458                        }
1459                    }
1460                    break;
1461                }
1462                case MCS_BOUND: {
1463                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1464                    if (msg.obj != null) {
1465                        mContainerService = (IMediaContainerService) msg.obj;
1466                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1467                                System.identityHashCode(mHandler));
1468                    }
1469                    if (mContainerService == null) {
1470                        if (!mBound) {
1471                            // Something seriously wrong since we are not bound and we are not
1472                            // waiting for connection. Bail out.
1473                            Slog.e(TAG, "Cannot bind to media container service");
1474                            for (HandlerParams params : mPendingInstalls) {
1475                                // Indicate service bind error
1476                                params.serviceError();
1477                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1478                                        System.identityHashCode(params));
1479                                if (params.traceMethod != null) {
1480                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1481                                            params.traceMethod, params.traceCookie);
1482                                }
1483                                return;
1484                            }
1485                            mPendingInstalls.clear();
1486                        } else {
1487                            Slog.w(TAG, "Waiting to connect to media container service");
1488                        }
1489                    } else if (mPendingInstalls.size() > 0) {
1490                        HandlerParams params = mPendingInstalls.get(0);
1491                        if (params != null) {
1492                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1493                                    System.identityHashCode(params));
1494                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1495                            if (params.startCopy()) {
1496                                // We are done...  look for more work or to
1497                                // go idle.
1498                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1499                                        "Checking for more work or unbind...");
1500                                // Delete pending install
1501                                if (mPendingInstalls.size() > 0) {
1502                                    mPendingInstalls.remove(0);
1503                                }
1504                                if (mPendingInstalls.size() == 0) {
1505                                    if (mBound) {
1506                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1507                                                "Posting delayed MCS_UNBIND");
1508                                        removeMessages(MCS_UNBIND);
1509                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1510                                        // Unbind after a little delay, to avoid
1511                                        // continual thrashing.
1512                                        sendMessageDelayed(ubmsg, 10000);
1513                                    }
1514                                } else {
1515                                    // There are more pending requests in queue.
1516                                    // Just post MCS_BOUND message to trigger processing
1517                                    // of next pending install.
1518                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1519                                            "Posting MCS_BOUND for next work");
1520                                    mHandler.sendEmptyMessage(MCS_BOUND);
1521                                }
1522                            }
1523                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1524                        }
1525                    } else {
1526                        // Should never happen ideally.
1527                        Slog.w(TAG, "Empty queue");
1528                    }
1529                    break;
1530                }
1531                case MCS_RECONNECT: {
1532                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1533                    if (mPendingInstalls.size() > 0) {
1534                        if (mBound) {
1535                            disconnectService();
1536                        }
1537                        if (!connectToService()) {
1538                            Slog.e(TAG, "Failed to bind to media container service");
1539                            for (HandlerParams params : mPendingInstalls) {
1540                                // Indicate service bind error
1541                                params.serviceError();
1542                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1543                                        System.identityHashCode(params));
1544                            }
1545                            mPendingInstalls.clear();
1546                        }
1547                    }
1548                    break;
1549                }
1550                case MCS_UNBIND: {
1551                    // If there is no actual work left, then time to unbind.
1552                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1553
1554                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1555                        if (mBound) {
1556                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1557
1558                            disconnectService();
1559                        }
1560                    } else if (mPendingInstalls.size() > 0) {
1561                        // There are more pending requests in queue.
1562                        // Just post MCS_BOUND message to trigger processing
1563                        // of next pending install.
1564                        mHandler.sendEmptyMessage(MCS_BOUND);
1565                    }
1566
1567                    break;
1568                }
1569                case MCS_GIVE_UP: {
1570                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1571                    HandlerParams params = mPendingInstalls.remove(0);
1572                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1573                            System.identityHashCode(params));
1574                    break;
1575                }
1576                case SEND_PENDING_BROADCAST: {
1577                    String packages[];
1578                    ArrayList<String> components[];
1579                    int size = 0;
1580                    int uids[];
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1582                    synchronized (mPackages) {
1583                        if (mPendingBroadcasts == null) {
1584                            return;
1585                        }
1586                        size = mPendingBroadcasts.size();
1587                        if (size <= 0) {
1588                            // Nothing to be done. Just return
1589                            return;
1590                        }
1591                        packages = new String[size];
1592                        components = new ArrayList[size];
1593                        uids = new int[size];
1594                        int i = 0;  // filling out the above arrays
1595
1596                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1597                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1598                            Iterator<Map.Entry<String, ArrayList<String>>> it
1599                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1600                                            .entrySet().iterator();
1601                            while (it.hasNext() && i < size) {
1602                                Map.Entry<String, ArrayList<String>> ent = it.next();
1603                                packages[i] = ent.getKey();
1604                                components[i] = ent.getValue();
1605                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1606                                uids[i] = (ps != null)
1607                                        ? UserHandle.getUid(packageUserId, ps.appId)
1608                                        : -1;
1609                                i++;
1610                            }
1611                        }
1612                        size = i;
1613                        mPendingBroadcasts.clear();
1614                    }
1615                    // Send broadcasts
1616                    for (int i = 0; i < size; i++) {
1617                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1618                    }
1619                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1620                    break;
1621                }
1622                case START_CLEANING_PACKAGE: {
1623                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1624                    final String packageName = (String)msg.obj;
1625                    final int userId = msg.arg1;
1626                    final boolean andCode = msg.arg2 != 0;
1627                    synchronized (mPackages) {
1628                        if (userId == UserHandle.USER_ALL) {
1629                            int[] users = sUserManager.getUserIds();
1630                            for (int user : users) {
1631                                mSettings.addPackageToCleanLPw(
1632                                        new PackageCleanItem(user, packageName, andCode));
1633                            }
1634                        } else {
1635                            mSettings.addPackageToCleanLPw(
1636                                    new PackageCleanItem(userId, packageName, andCode));
1637                        }
1638                    }
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1640                    startCleaningPackages();
1641                } break;
1642                case POST_INSTALL: {
1643                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1644
1645                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1646                    final boolean didRestore = (msg.arg2 != 0);
1647                    mRunningInstalls.delete(msg.arg1);
1648
1649                    if (data != null) {
1650                        InstallArgs args = data.args;
1651                        PackageInstalledInfo parentRes = data.res;
1652
1653                        final boolean grantPermissions = (args.installFlags
1654                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1655                        final boolean killApp = (args.installFlags
1656                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1657                        final boolean virtualPreload = ((args.installFlags
1658                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1659                        final String[] grantedPermissions = args.installGrantPermissions;
1660
1661                        // Handle the parent package
1662                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1663                                virtualPreload, grantedPermissions, didRestore,
1664                                args.installerPackageName, args.observer);
1665
1666                        // Handle the child packages
1667                        final int childCount = (parentRes.addedChildPackages != null)
1668                                ? parentRes.addedChildPackages.size() : 0;
1669                        for (int i = 0; i < childCount; i++) {
1670                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1671                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1672                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1673                                    args.installerPackageName, args.observer);
1674                        }
1675
1676                        // Log tracing if needed
1677                        if (args.traceMethod != null) {
1678                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1679                                    args.traceCookie);
1680                        }
1681                    } else {
1682                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1683                    }
1684
1685                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1686                } break;
1687                case WRITE_SETTINGS: {
1688                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1689                    synchronized (mPackages) {
1690                        removeMessages(WRITE_SETTINGS);
1691                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1692                        mSettings.writeLPr();
1693                        mDirtyUsers.clear();
1694                    }
1695                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1696                } break;
1697                case WRITE_PACKAGE_RESTRICTIONS: {
1698                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1699                    synchronized (mPackages) {
1700                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1701                        for (int userId : mDirtyUsers) {
1702                            mSettings.writePackageRestrictionsLPr(userId);
1703                        }
1704                        mDirtyUsers.clear();
1705                    }
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1707                } break;
1708                case WRITE_PACKAGE_LIST: {
1709                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1710                    synchronized (mPackages) {
1711                        removeMessages(WRITE_PACKAGE_LIST);
1712                        mSettings.writePackageListLPr(msg.arg1);
1713                    }
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1715                } break;
1716                case CHECK_PENDING_VERIFICATION: {
1717                    final int verificationId = msg.arg1;
1718                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1719
1720                    if ((state != null) && !state.timeoutExtended()) {
1721                        final InstallArgs args = state.getInstallArgs();
1722                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1723
1724                        Slog.i(TAG, "Verification timed out for " + originUri);
1725                        mPendingVerification.remove(verificationId);
1726
1727                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1728
1729                        final UserHandle user = args.getUser();
1730                        if (getDefaultVerificationResponse(user)
1731                                == PackageManager.VERIFICATION_ALLOW) {
1732                            Slog.i(TAG, "Continuing with installation of " + originUri);
1733                            state.setVerifierResponse(Binder.getCallingUid(),
1734                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1735                            broadcastPackageVerified(verificationId, originUri,
1736                                    PackageManager.VERIFICATION_ALLOW, user);
1737                            try {
1738                                ret = args.copyApk(mContainerService, true);
1739                            } catch (RemoteException e) {
1740                                Slog.e(TAG, "Could not contact the ContainerService");
1741                            }
1742                        } else {
1743                            broadcastPackageVerified(verificationId, originUri,
1744                                    PackageManager.VERIFICATION_REJECT, user);
1745                        }
1746
1747                        Trace.asyncTraceEnd(
1748                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1749
1750                        processPendingInstall(args, ret);
1751                        mHandler.sendEmptyMessage(MCS_UNBIND);
1752                    }
1753                    break;
1754                }
1755                case PACKAGE_VERIFIED: {
1756                    final int verificationId = msg.arg1;
1757
1758                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1759                    if (state == null) {
1760                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1761                        break;
1762                    }
1763
1764                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1765
1766                    state.setVerifierResponse(response.callerUid, response.code);
1767
1768                    if (state.isVerificationComplete()) {
1769                        mPendingVerification.remove(verificationId);
1770
1771                        final InstallArgs args = state.getInstallArgs();
1772                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1773
1774                        int ret;
1775                        if (state.isInstallAllowed()) {
1776                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1777                            broadcastPackageVerified(verificationId, originUri,
1778                                    response.code, state.getInstallArgs().getUser());
1779                            try {
1780                                ret = args.copyApk(mContainerService, true);
1781                            } catch (RemoteException e) {
1782                                Slog.e(TAG, "Could not contact the ContainerService");
1783                            }
1784                        } else {
1785                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1786                        }
1787
1788                        Trace.asyncTraceEnd(
1789                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1790
1791                        processPendingInstall(args, ret);
1792                        mHandler.sendEmptyMessage(MCS_UNBIND);
1793                    }
1794
1795                    break;
1796                }
1797                case START_INTENT_FILTER_VERIFICATIONS: {
1798                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1799                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1800                            params.replacing, params.pkg);
1801                    break;
1802                }
1803                case INTENT_FILTER_VERIFIED: {
1804                    final int verificationId = msg.arg1;
1805
1806                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1807                            verificationId);
1808                    if (state == null) {
1809                        Slog.w(TAG, "Invalid IntentFilter verification token "
1810                                + verificationId + " received");
1811                        break;
1812                    }
1813
1814                    final int userId = state.getUserId();
1815
1816                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1817                            "Processing IntentFilter verification with token:"
1818                            + verificationId + " and userId:" + userId);
1819
1820                    final IntentFilterVerificationResponse response =
1821                            (IntentFilterVerificationResponse) msg.obj;
1822
1823                    state.setVerifierResponse(response.callerUid, response.code);
1824
1825                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1826                            "IntentFilter verification with token:" + verificationId
1827                            + " and userId:" + userId
1828                            + " is settings verifier response with response code:"
1829                            + response.code);
1830
1831                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1832                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1833                                + response.getFailedDomainsString());
1834                    }
1835
1836                    if (state.isVerificationComplete()) {
1837                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1838                    } else {
1839                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1840                                "IntentFilter verification with token:" + verificationId
1841                                + " was not said to be complete");
1842                    }
1843
1844                    break;
1845                }
1846                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1847                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1848                            mInstantAppResolverConnection,
1849                            (InstantAppRequest) msg.obj,
1850                            mInstantAppInstallerActivity,
1851                            mHandler);
1852                }
1853            }
1854        }
1855    }
1856
1857    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1858        @Override
1859        public void onGidsChanged(int appId, int userId) {
1860            mHandler.post(new Runnable() {
1861                @Override
1862                public void run() {
1863                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1864                }
1865            });
1866        }
1867        @Override
1868        public void onPermissionGranted(int uid, int userId) {
1869            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1870
1871            // Not critical; if this is lost, the application has to request again.
1872            synchronized (mPackages) {
1873                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1874            }
1875        }
1876        @Override
1877        public void onInstallPermissionGranted() {
1878            synchronized (mPackages) {
1879                scheduleWriteSettingsLocked();
1880            }
1881        }
1882        @Override
1883        public void onPermissionRevoked(int uid, int userId) {
1884            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1885
1886            synchronized (mPackages) {
1887                // Critical; after this call the application should never have the permission
1888                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1889            }
1890
1891            final int appId = UserHandle.getAppId(uid);
1892            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1893        }
1894        @Override
1895        public void onInstallPermissionRevoked() {
1896            synchronized (mPackages) {
1897                scheduleWriteSettingsLocked();
1898            }
1899        }
1900        @Override
1901        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1902            synchronized (mPackages) {
1903                for (int userId : updatedUserIds) {
1904                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1905                }
1906            }
1907        }
1908        @Override
1909        public void onInstallPermissionUpdated() {
1910            synchronized (mPackages) {
1911                scheduleWriteSettingsLocked();
1912            }
1913        }
1914        @Override
1915        public void onPermissionRemoved() {
1916            synchronized (mPackages) {
1917                mSettings.writeLPr();
1918            }
1919        }
1920    };
1921
1922    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1923            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1924            boolean launchedForRestore, String installerPackage,
1925            IPackageInstallObserver2 installObserver) {
1926        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1927            // Send the removed broadcasts
1928            if (res.removedInfo != null) {
1929                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1930            }
1931
1932            // Now that we successfully installed the package, grant runtime
1933            // permissions if requested before broadcasting the install. Also
1934            // for legacy apps in permission review mode we clear the permission
1935            // review flag which is used to emulate runtime permissions for
1936            // legacy apps.
1937            if (grantPermissions) {
1938                final int callingUid = Binder.getCallingUid();
1939                mPermissionManager.grantRequestedRuntimePermissions(
1940                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1941                        mPermissionCallback);
1942            }
1943
1944            final boolean update = res.removedInfo != null
1945                    && res.removedInfo.removedPackage != null;
1946            final String installerPackageName =
1947                    res.installerPackageName != null
1948                            ? res.installerPackageName
1949                            : res.removedInfo != null
1950                                    ? res.removedInfo.installerPackageName
1951                                    : null;
1952
1953            // If this is the first time we have child packages for a disabled privileged
1954            // app that had no children, we grant requested runtime permissions to the new
1955            // children if the parent on the system image had them already granted.
1956            if (res.pkg.parentPackage != null) {
1957                final int callingUid = Binder.getCallingUid();
1958                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1959                        res.pkg, callingUid, mPermissionCallback);
1960            }
1961
1962            synchronized (mPackages) {
1963                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1964            }
1965
1966            final String packageName = res.pkg.applicationInfo.packageName;
1967
1968            // Determine the set of users who are adding this package for
1969            // the first time vs. those who are seeing an update.
1970            int[] firstUserIds = EMPTY_INT_ARRAY;
1971            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1972            int[] updateUserIds = EMPTY_INT_ARRAY;
1973            int[] instantUserIds = EMPTY_INT_ARRAY;
1974            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1975            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1976            for (int newUser : res.newUsers) {
1977                final boolean isInstantApp = ps.getInstantApp(newUser);
1978                if (allNewUsers) {
1979                    if (isInstantApp) {
1980                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1981                    } else {
1982                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1983                    }
1984                    continue;
1985                }
1986                boolean isNew = true;
1987                for (int origUser : res.origUsers) {
1988                    if (origUser == newUser) {
1989                        isNew = false;
1990                        break;
1991                    }
1992                }
1993                if (isNew) {
1994                    if (isInstantApp) {
1995                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1996                    } else {
1997                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1998                    }
1999                } else {
2000                    if (isInstantApp) {
2001                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2002                    } else {
2003                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2004                    }
2005                }
2006            }
2007
2008            // Send installed broadcasts if the package is not a static shared lib.
2009            if (res.pkg.staticSharedLibName == null) {
2010                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2011
2012                // Send added for users that see the package for the first time
2013                // sendPackageAddedForNewUsers also deals with system apps
2014                int appId = UserHandle.getAppId(res.uid);
2015                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2016                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2017                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2018
2019                // Send added for users that don't see the package for the first time
2020                Bundle extras = new Bundle(1);
2021                extras.putInt(Intent.EXTRA_UID, res.uid);
2022                if (update) {
2023                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2024                }
2025                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2026                        extras, 0 /*flags*/,
2027                        null /*targetPackage*/, null /*finishedReceiver*/,
2028                        updateUserIds, instantUserIds);
2029                if (installerPackageName != null) {
2030                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2031                            extras, 0 /*flags*/,
2032                            installerPackageName, null /*finishedReceiver*/,
2033                            updateUserIds, instantUserIds);
2034                }
2035
2036                // Send replaced for users that don't see the package for the first time
2037                if (update) {
2038                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2039                            packageName, extras, 0 /*flags*/,
2040                            null /*targetPackage*/, null /*finishedReceiver*/,
2041                            updateUserIds, instantUserIds);
2042                    if (installerPackageName != null) {
2043                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2044                                extras, 0 /*flags*/,
2045                                installerPackageName, null /*finishedReceiver*/,
2046                                updateUserIds, instantUserIds);
2047                    }
2048                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2049                            null /*package*/, null /*extras*/, 0 /*flags*/,
2050                            packageName /*targetPackage*/,
2051                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2052                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2053                    // First-install and we did a restore, so we're responsible for the
2054                    // first-launch broadcast.
2055                    if (DEBUG_BACKUP) {
2056                        Slog.i(TAG, "Post-restore of " + packageName
2057                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2058                    }
2059                    sendFirstLaunchBroadcast(packageName, installerPackage,
2060                            firstUserIds, firstInstantUserIds);
2061                }
2062
2063                // Send broadcast package appeared if forward locked/external for all users
2064                // treat asec-hosted packages like removable media on upgrade
2065                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2066                    if (DEBUG_INSTALL) {
2067                        Slog.i(TAG, "upgrading pkg " + res.pkg
2068                                + " is ASEC-hosted -> AVAILABLE");
2069                    }
2070                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2071                    ArrayList<String> pkgList = new ArrayList<>(1);
2072                    pkgList.add(packageName);
2073                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2074                }
2075            }
2076
2077            // Work that needs to happen on first install within each user
2078            if (firstUserIds != null && firstUserIds.length > 0) {
2079                synchronized (mPackages) {
2080                    for (int userId : firstUserIds) {
2081                        // If this app is a browser and it's newly-installed for some
2082                        // users, clear any default-browser state in those users. The
2083                        // app's nature doesn't depend on the user, so we can just check
2084                        // its browser nature in any user and generalize.
2085                        if (packageIsBrowser(packageName, userId)) {
2086                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2087                        }
2088
2089                        // We may also need to apply pending (restored) runtime
2090                        // permission grants within these users.
2091                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2092                    }
2093                }
2094            }
2095
2096            // Log current value of "unknown sources" setting
2097            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2098                    getUnknownSourcesSettings());
2099
2100            // Remove the replaced package's older resources safely now
2101            // We delete after a gc for applications  on sdcard.
2102            if (res.removedInfo != null && res.removedInfo.args != null) {
2103                Runtime.getRuntime().gc();
2104                synchronized (mInstallLock) {
2105                    res.removedInfo.args.doPostDeleteLI(true);
2106                }
2107            } else {
2108                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2109                // and not block here.
2110                VMRuntime.getRuntime().requestConcurrentGC();
2111            }
2112
2113            // Notify DexManager that the package was installed for new users.
2114            // The updated users should already be indexed and the package code paths
2115            // should not change.
2116            // Don't notify the manager for ephemeral apps as they are not expected to
2117            // survive long enough to benefit of background optimizations.
2118            for (int userId : firstUserIds) {
2119                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2120                // There's a race currently where some install events may interleave with an uninstall.
2121                // This can lead to package info being null (b/36642664).
2122                if (info != null) {
2123                    mDexManager.notifyPackageInstalled(info, userId);
2124                }
2125            }
2126        }
2127
2128        // If someone is watching installs - notify them
2129        if (installObserver != null) {
2130            try {
2131                Bundle extras = extrasForInstallResult(res);
2132                installObserver.onPackageInstalled(res.name, res.returnCode,
2133                        res.returnMsg, extras);
2134            } catch (RemoteException e) {
2135                Slog.i(TAG, "Observer no longer exists.");
2136            }
2137        }
2138    }
2139
2140    private StorageEventListener mStorageListener = new StorageEventListener() {
2141        @Override
2142        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2143            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2144                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2145                    final String volumeUuid = vol.getFsUuid();
2146
2147                    // Clean up any users or apps that were removed or recreated
2148                    // while this volume was missing
2149                    sUserManager.reconcileUsers(volumeUuid);
2150                    reconcileApps(volumeUuid);
2151
2152                    // Clean up any install sessions that expired or were
2153                    // cancelled while this volume was missing
2154                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2155
2156                    loadPrivatePackages(vol);
2157
2158                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2159                    unloadPrivatePackages(vol);
2160                }
2161            }
2162        }
2163
2164        @Override
2165        public void onVolumeForgotten(String fsUuid) {
2166            if (TextUtils.isEmpty(fsUuid)) {
2167                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2168                return;
2169            }
2170
2171            // Remove any apps installed on the forgotten volume
2172            synchronized (mPackages) {
2173                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2174                for (PackageSetting ps : packages) {
2175                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2176                    deletePackageVersioned(new VersionedPackage(ps.name,
2177                            PackageManager.VERSION_CODE_HIGHEST),
2178                            new LegacyPackageDeleteObserver(null).getBinder(),
2179                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2180                    // Try very hard to release any references to this package
2181                    // so we don't risk the system server being killed due to
2182                    // open FDs
2183                    AttributeCache.instance().removePackage(ps.name);
2184                }
2185
2186                mSettings.onVolumeForgotten(fsUuid);
2187                mSettings.writeLPr();
2188            }
2189        }
2190    };
2191
2192    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2193        Bundle extras = null;
2194        switch (res.returnCode) {
2195            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2196                extras = new Bundle();
2197                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2198                        res.origPermission);
2199                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2200                        res.origPackage);
2201                break;
2202            }
2203            case PackageManager.INSTALL_SUCCEEDED: {
2204                extras = new Bundle();
2205                extras.putBoolean(Intent.EXTRA_REPLACING,
2206                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2207                break;
2208            }
2209        }
2210        return extras;
2211    }
2212
2213    void scheduleWriteSettingsLocked() {
2214        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2215            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2216        }
2217    }
2218
2219    void scheduleWritePackageListLocked(int userId) {
2220        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2221            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2222            msg.arg1 = userId;
2223            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2224        }
2225    }
2226
2227    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2228        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2229        scheduleWritePackageRestrictionsLocked(userId);
2230    }
2231
2232    void scheduleWritePackageRestrictionsLocked(int userId) {
2233        final int[] userIds = (userId == UserHandle.USER_ALL)
2234                ? sUserManager.getUserIds() : new int[]{userId};
2235        for (int nextUserId : userIds) {
2236            if (!sUserManager.exists(nextUserId)) return;
2237            mDirtyUsers.add(nextUserId);
2238            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2239                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2240            }
2241        }
2242    }
2243
2244    public static PackageManagerService main(Context context, Installer installer,
2245            boolean factoryTest, boolean onlyCore) {
2246        // Self-check for initial settings.
2247        PackageManagerServiceCompilerMapping.checkProperties();
2248
2249        PackageManagerService m = new PackageManagerService(context, installer,
2250                factoryTest, onlyCore);
2251        m.enableSystemUserPackages();
2252        ServiceManager.addService("package", m);
2253        final PackageManagerNative pmn = m.new PackageManagerNative();
2254        ServiceManager.addService("package_native", pmn);
2255        return m;
2256    }
2257
2258    private void enableSystemUserPackages() {
2259        if (!UserManager.isSplitSystemUser()) {
2260            return;
2261        }
2262        // For system user, enable apps based on the following conditions:
2263        // - app is whitelisted or belong to one of these groups:
2264        //   -- system app which has no launcher icons
2265        //   -- system app which has INTERACT_ACROSS_USERS permission
2266        //   -- system IME app
2267        // - app is not in the blacklist
2268        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2269        Set<String> enableApps = new ArraySet<>();
2270        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2271                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2272                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2273        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2274        enableApps.addAll(wlApps);
2275        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2276                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2277        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2278        enableApps.removeAll(blApps);
2279        Log.i(TAG, "Applications installed for system user: " + enableApps);
2280        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2281                UserHandle.SYSTEM);
2282        final int allAppsSize = allAps.size();
2283        synchronized (mPackages) {
2284            for (int i = 0; i < allAppsSize; i++) {
2285                String pName = allAps.get(i);
2286                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2287                // Should not happen, but we shouldn't be failing if it does
2288                if (pkgSetting == null) {
2289                    continue;
2290                }
2291                boolean install = enableApps.contains(pName);
2292                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2293                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2294                            + " for system user");
2295                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2296                }
2297            }
2298            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2299        }
2300    }
2301
2302    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2303        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2304                Context.DISPLAY_SERVICE);
2305        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2306    }
2307
2308    /**
2309     * Requests that files preopted on a secondary system partition be copied to the data partition
2310     * if possible.  Note that the actual copying of the files is accomplished by init for security
2311     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2312     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2313     */
2314    private static void requestCopyPreoptedFiles() {
2315        final int WAIT_TIME_MS = 100;
2316        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2317        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2318            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2319            // We will wait for up to 100 seconds.
2320            final long timeStart = SystemClock.uptimeMillis();
2321            final long timeEnd = timeStart + 100 * 1000;
2322            long timeNow = timeStart;
2323            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2324                try {
2325                    Thread.sleep(WAIT_TIME_MS);
2326                } catch (InterruptedException e) {
2327                    // Do nothing
2328                }
2329                timeNow = SystemClock.uptimeMillis();
2330                if (timeNow > timeEnd) {
2331                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2332                    Slog.wtf(TAG, "cppreopt did not finish!");
2333                    break;
2334                }
2335            }
2336
2337            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2338        }
2339    }
2340
2341    public PackageManagerService(Context context, Installer installer,
2342            boolean factoryTest, boolean onlyCore) {
2343        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2344        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2345        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2346                SystemClock.uptimeMillis());
2347
2348        if (mSdkVersion <= 0) {
2349            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2350        }
2351
2352        mContext = context;
2353
2354        mFactoryTest = factoryTest;
2355        mOnlyCore = onlyCore;
2356        mMetrics = new DisplayMetrics();
2357        mInstaller = installer;
2358
2359        // Create sub-components that provide services / data. Order here is important.
2360        synchronized (mInstallLock) {
2361        synchronized (mPackages) {
2362            // Expose private service for system components to use.
2363            LocalServices.addService(
2364                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2365            sUserManager = new UserManagerService(context, this,
2366                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2367            mPermissionManager = PermissionManagerService.create(context,
2368                    new DefaultPermissionGrantedCallback() {
2369                        @Override
2370                        public void onDefaultRuntimePermissionsGranted(int userId) {
2371                            synchronized(mPackages) {
2372                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2373                            }
2374                        }
2375                    }, mPackages /*externalLock*/);
2376            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2377            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2378        }
2379        }
2380        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2391                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2392
2393        String separateProcesses = SystemProperties.get("debug.separate_processes");
2394        if (separateProcesses != null && separateProcesses.length() > 0) {
2395            if ("*".equals(separateProcesses)) {
2396                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2397                mSeparateProcesses = null;
2398                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2399            } else {
2400                mDefParseFlags = 0;
2401                mSeparateProcesses = separateProcesses.split(",");
2402                Slog.w(TAG, "Running with debug.separate_processes: "
2403                        + separateProcesses);
2404            }
2405        } else {
2406            mDefParseFlags = 0;
2407            mSeparateProcesses = null;
2408        }
2409
2410        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2411                "*dexopt*");
2412        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2413                installer, mInstallLock);
2414        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2415                dexManagerListener);
2416        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2417
2418        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2419                FgThread.get().getLooper());
2420
2421        getDefaultDisplayMetrics(context, mMetrics);
2422
2423        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2424        SystemConfig systemConfig = SystemConfig.getInstance();
2425        mAvailableFeatures = systemConfig.getAvailableFeatures();
2426        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2427
2428        mProtectedPackages = new ProtectedPackages(mContext);
2429
2430        synchronized (mInstallLock) {
2431        // writer
2432        synchronized (mPackages) {
2433            mHandlerThread = new ServiceThread(TAG,
2434                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2435            mHandlerThread.start();
2436            mHandler = new PackageHandler(mHandlerThread.getLooper());
2437            mProcessLoggingHandler = new ProcessLoggingHandler();
2438            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2439            mInstantAppRegistry = new InstantAppRegistry(this);
2440
2441            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2442            final int builtInLibCount = libConfig.size();
2443            for (int i = 0; i < builtInLibCount; i++) {
2444                String name = libConfig.keyAt(i);
2445                String path = libConfig.valueAt(i);
2446                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2447                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2448            }
2449
2450            SELinuxMMAC.readInstallPolicy();
2451
2452            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2453            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2454            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2455
2456            // Clean up orphaned packages for which the code path doesn't exist
2457            // and they are an update to a system app - caused by bug/32321269
2458            final int packageSettingCount = mSettings.mPackages.size();
2459            for (int i = packageSettingCount - 1; i >= 0; i--) {
2460                PackageSetting ps = mSettings.mPackages.valueAt(i);
2461                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2462                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2463                    mSettings.mPackages.removeAt(i);
2464                    mSettings.enableSystemPackageLPw(ps.name);
2465                }
2466            }
2467
2468            if (mFirstBoot) {
2469                requestCopyPreoptedFiles();
2470            }
2471
2472            String customResolverActivity = Resources.getSystem().getString(
2473                    R.string.config_customResolverActivity);
2474            if (TextUtils.isEmpty(customResolverActivity)) {
2475                customResolverActivity = null;
2476            } else {
2477                mCustomResolverComponentName = ComponentName.unflattenFromString(
2478                        customResolverActivity);
2479            }
2480
2481            long startTime = SystemClock.uptimeMillis();
2482
2483            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2484                    startTime);
2485
2486            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2487            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2488
2489            if (bootClassPath == null) {
2490                Slog.w(TAG, "No BOOTCLASSPATH found!");
2491            }
2492
2493            if (systemServerClassPath == null) {
2494                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2495            }
2496
2497            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2498
2499            final VersionInfo ver = mSettings.getInternalVersion();
2500            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2501            if (mIsUpgrade) {
2502                logCriticalInfo(Log.INFO,
2503                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2504            }
2505
2506            // when upgrading from pre-M, promote system app permissions from install to runtime
2507            mPromoteSystemApps =
2508                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2509
2510            // When upgrading from pre-N, we need to handle package extraction like first boot,
2511            // as there is no profiling data available.
2512            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2513
2514            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2515
2516            // save off the names of pre-existing system packages prior to scanning; we don't
2517            // want to automatically grant runtime permissions for new system apps
2518            if (mPromoteSystemApps) {
2519                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2520                while (pkgSettingIter.hasNext()) {
2521                    PackageSetting ps = pkgSettingIter.next();
2522                    if (isSystemApp(ps)) {
2523                        mExistingSystemPackages.add(ps.name);
2524                    }
2525                }
2526            }
2527
2528            mCacheDir = preparePackageParserCache(mIsUpgrade);
2529
2530            // Set flag to monitor and not change apk file paths when
2531            // scanning install directories.
2532            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2533
2534            if (mIsUpgrade || mFirstBoot) {
2535                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2536            }
2537
2538            // Collect vendor overlay packages. (Do this before scanning any apps.)
2539            // For security and version matching reason, only consider
2540            // overlay packages if they reside in the right directory.
2541            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2542                    mDefParseFlags
2543                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2544                    scanFlags
2545                    | SCAN_AS_SYSTEM
2546                    | SCAN_TRUSTED_OVERLAY,
2547                    0);
2548
2549            mParallelPackageParserCallback.findStaticOverlayPackages();
2550
2551            // Find base frameworks (resource packages without code).
2552            scanDirTracedLI(frameworkDir,
2553                    mDefParseFlags
2554                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2555                    scanFlags
2556                    | SCAN_NO_DEX
2557                    | SCAN_AS_SYSTEM
2558                    | SCAN_AS_PRIVILEGED,
2559                    0);
2560
2561            // Collected privileged system packages.
2562            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2563            scanDirTracedLI(privilegedAppDir,
2564                    mDefParseFlags
2565                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2566                    scanFlags
2567                    | SCAN_AS_SYSTEM
2568                    | SCAN_AS_PRIVILEGED,
2569                    0);
2570
2571            // Collect ordinary system packages.
2572            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2573            scanDirTracedLI(systemAppDir,
2574                    mDefParseFlags
2575                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2576                    scanFlags
2577                    | SCAN_AS_SYSTEM,
2578                    0);
2579
2580            // Collected privileged vendor packages.
2581                File privilegedVendorAppDir = new File(Environment.getVendorDirectory(),
2582                        "priv-app");
2583            try {
2584                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2585            } catch (IOException e) {
2586                // failed to look up canonical path, continue with original one
2587            }
2588            scanDirTracedLI(privilegedVendorAppDir,
2589                    mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2591                    scanFlags
2592                    | SCAN_AS_SYSTEM
2593                    | SCAN_AS_VENDOR
2594                    | SCAN_AS_PRIVILEGED,
2595                    0);
2596
2597            // Collect ordinary vendor packages.
2598            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2599            try {
2600                vendorAppDir = vendorAppDir.getCanonicalFile();
2601            } catch (IOException e) {
2602                // failed to look up canonical path, continue with original one
2603            }
2604            scanDirTracedLI(vendorAppDir,
2605                    mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2607                    scanFlags
2608                    | SCAN_AS_SYSTEM
2609                    | SCAN_AS_VENDOR,
2610                    0);
2611
2612            // Collect all OEM packages.
2613            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2614            scanDirTracedLI(oemAppDir,
2615                    mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2617                    scanFlags
2618                    | SCAN_AS_SYSTEM
2619                    | SCAN_AS_OEM,
2620                    0);
2621
2622            // Prune any system packages that no longer exist.
2623            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2624            // Stub packages must either be replaced with full versions in the /data
2625            // partition or be disabled.
2626            final List<String> stubSystemApps = new ArrayList<>();
2627            if (!mOnlyCore) {
2628                // do this first before mucking with mPackages for the "expecting better" case
2629                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2630                while (pkgIterator.hasNext()) {
2631                    final PackageParser.Package pkg = pkgIterator.next();
2632                    if (pkg.isStub) {
2633                        stubSystemApps.add(pkg.packageName);
2634                    }
2635                }
2636
2637                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2638                while (psit.hasNext()) {
2639                    PackageSetting ps = psit.next();
2640
2641                    /*
2642                     * If this is not a system app, it can't be a
2643                     * disable system app.
2644                     */
2645                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2646                        continue;
2647                    }
2648
2649                    /*
2650                     * If the package is scanned, it's not erased.
2651                     */
2652                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2653                    if (scannedPkg != null) {
2654                        /*
2655                         * If the system app is both scanned and in the
2656                         * disabled packages list, then it must have been
2657                         * added via OTA. Remove it from the currently
2658                         * scanned package so the previously user-installed
2659                         * application can be scanned.
2660                         */
2661                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2662                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2663                                    + ps.name + "; removing system app.  Last known codePath="
2664                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2665                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2666                                    + scannedPkg.getLongVersionCode());
2667                            removePackageLI(scannedPkg, true);
2668                            mExpectingBetter.put(ps.name, ps.codePath);
2669                        }
2670
2671                        continue;
2672                    }
2673
2674                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2675                        psit.remove();
2676                        logCriticalInfo(Log.WARN, "System package " + ps.name
2677                                + " no longer exists; it's data will be wiped");
2678                        // Actual deletion of code and data will be handled by later
2679                        // reconciliation step
2680                    } else {
2681                        // we still have a disabled system package, but, it still might have
2682                        // been removed. check the code path still exists and check there's
2683                        // still a package. the latter can happen if an OTA keeps the same
2684                        // code path, but, changes the package name.
2685                        final PackageSetting disabledPs =
2686                                mSettings.getDisabledSystemPkgLPr(ps.name);
2687                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2688                                || disabledPs.pkg == null) {
2689                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2690                        }
2691                    }
2692                }
2693            }
2694
2695            //look for any incomplete package installations
2696            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2697            for (int i = 0; i < deletePkgsList.size(); i++) {
2698                // Actual deletion of code and data will be handled by later
2699                // reconciliation step
2700                final String packageName = deletePkgsList.get(i).name;
2701                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2702                synchronized (mPackages) {
2703                    mSettings.removePackageLPw(packageName);
2704                }
2705            }
2706
2707            //delete tmp files
2708            deleteTempPackageFiles();
2709
2710            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2711
2712            // Remove any shared userIDs that have no associated packages
2713            mSettings.pruneSharedUsersLPw();
2714            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2715            final int systemPackagesCount = mPackages.size();
2716            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2717                    + " ms, packageCount: " + systemPackagesCount
2718                    + " , timePerPackage: "
2719                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2720                    + " , cached: " + cachedSystemApps);
2721            if (mIsUpgrade && systemPackagesCount > 0) {
2722                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2723                        ((int) systemScanTime) / systemPackagesCount);
2724            }
2725            if (!mOnlyCore) {
2726                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2727                        SystemClock.uptimeMillis());
2728                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2729
2730                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2731                        | PackageParser.PARSE_FORWARD_LOCK,
2732                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2733
2734                // Remove disable package settings for updated system apps that were
2735                // removed via an OTA. If the update is no longer present, remove the
2736                // app completely. Otherwise, revoke their system privileges.
2737                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2738                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2739                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2740
2741                    final String msg;
2742                    if (deletedPkg == null) {
2743                        // should have found an update, but, we didn't; remove everything
2744                        msg = "Updated system package " + deletedAppName
2745                                + " no longer exists; removing its data";
2746                        // Actual deletion of code and data will be handled by later
2747                        // reconciliation step
2748                    } else {
2749                        // found an update; revoke system privileges
2750                        msg = "Updated system package + " + deletedAppName
2751                                + " no longer exists; revoking system privileges";
2752
2753                        // Don't do anything if a stub is removed from the system image. If
2754                        // we were to remove the uncompressed version from the /data partition,
2755                        // this is where it'd be done.
2756
2757                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2758                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2759                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2760                    }
2761                    logCriticalInfo(Log.WARN, msg);
2762                }
2763
2764                /*
2765                 * Make sure all system apps that we expected to appear on
2766                 * the userdata partition actually showed up. If they never
2767                 * appeared, crawl back and revive the system version.
2768                 */
2769                for (int i = 0; i < mExpectingBetter.size(); i++) {
2770                    final String packageName = mExpectingBetter.keyAt(i);
2771                    if (!mPackages.containsKey(packageName)) {
2772                        final File scanFile = mExpectingBetter.valueAt(i);
2773
2774                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2775                                + " but never showed up; reverting to system");
2776
2777                        final @ParseFlags int reparseFlags;
2778                        final @ScanFlags int rescanFlags;
2779                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2780                            reparseFlags =
2781                                    mDefParseFlags |
2782                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2783                            rescanFlags =
2784                                    scanFlags
2785                                    | SCAN_AS_SYSTEM
2786                                    | SCAN_AS_PRIVILEGED;
2787                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2788                            reparseFlags =
2789                                    mDefParseFlags |
2790                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2791                            rescanFlags =
2792                                    scanFlags
2793                                    | SCAN_AS_SYSTEM;
2794                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2795                            reparseFlags =
2796                                    mDefParseFlags |
2797                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2798                            rescanFlags =
2799                                    scanFlags
2800                                    | SCAN_AS_SYSTEM
2801                                    | SCAN_AS_VENDOR
2802                                    | SCAN_AS_PRIVILEGED;
2803                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2804                            reparseFlags =
2805                                    mDefParseFlags |
2806                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2807                            rescanFlags =
2808                                    scanFlags
2809                                    | SCAN_AS_SYSTEM
2810                                    | SCAN_AS_VENDOR;
2811                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2812                            reparseFlags =
2813                                    mDefParseFlags |
2814                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2815                            rescanFlags =
2816                                    scanFlags
2817                                    | SCAN_AS_SYSTEM
2818                                    | SCAN_AS_OEM;
2819                        } else {
2820                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2821                            continue;
2822                        }
2823
2824                        mSettings.enableSystemPackageLPw(packageName);
2825
2826                        try {
2827                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2828                        } catch (PackageManagerException e) {
2829                            Slog.e(TAG, "Failed to parse original system package: "
2830                                    + e.getMessage());
2831                        }
2832                    }
2833                }
2834
2835                // Uncompress and install any stubbed system applications.
2836                // This must be done last to ensure all stubs are replaced or disabled.
2837                decompressSystemApplications(stubSystemApps, scanFlags);
2838
2839                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2840                                - cachedSystemApps;
2841
2842                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2843                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2844                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2845                        + " ms, packageCount: " + dataPackagesCount
2846                        + " , timePerPackage: "
2847                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2848                        + " , cached: " + cachedNonSystemApps);
2849                if (mIsUpgrade && dataPackagesCount > 0) {
2850                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2851                            ((int) dataScanTime) / dataPackagesCount);
2852                }
2853            }
2854            mExpectingBetter.clear();
2855
2856            // Resolve the storage manager.
2857            mStorageManagerPackage = getStorageManagerPackageName();
2858
2859            // Resolve protected action filters. Only the setup wizard is allowed to
2860            // have a high priority filter for these actions.
2861            mSetupWizardPackage = getSetupWizardPackageName();
2862            if (mProtectedFilters.size() > 0) {
2863                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2864                    Slog.i(TAG, "No setup wizard;"
2865                        + " All protected intents capped to priority 0");
2866                }
2867                for (ActivityIntentInfo filter : mProtectedFilters) {
2868                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2869                        if (DEBUG_FILTERS) {
2870                            Slog.i(TAG, "Found setup wizard;"
2871                                + " allow priority " + filter.getPriority() + ";"
2872                                + " package: " + filter.activity.info.packageName
2873                                + " activity: " + filter.activity.className
2874                                + " priority: " + filter.getPriority());
2875                        }
2876                        // skip setup wizard; allow it to keep the high priority filter
2877                        continue;
2878                    }
2879                    if (DEBUG_FILTERS) {
2880                        Slog.i(TAG, "Protected action; cap priority to 0;"
2881                                + " package: " + filter.activity.info.packageName
2882                                + " activity: " + filter.activity.className
2883                                + " origPrio: " + filter.getPriority());
2884                    }
2885                    filter.setPriority(0);
2886                }
2887            }
2888            mDeferProtectedFilters = false;
2889            mProtectedFilters.clear();
2890
2891            // Now that we know all of the shared libraries, update all clients to have
2892            // the correct library paths.
2893            updateAllSharedLibrariesLPw(null);
2894
2895            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2896                // NOTE: We ignore potential failures here during a system scan (like
2897                // the rest of the commands above) because there's precious little we
2898                // can do about it. A settings error is reported, though.
2899                final List<String> changedAbiCodePath =
2900                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2901                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2902                    for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
2903                        final String codePathString = changedAbiCodePath.get(i);
2904                        try {
2905                            mInstaller.rmdex(codePathString,
2906                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2907                        } catch (InstallerException ignored) {
2908                        }
2909                    }
2910                }
2911            }
2912
2913            // Now that we know all the packages we are keeping,
2914            // read and update their last usage times.
2915            mPackageUsage.read(mPackages);
2916            mCompilerStats.read();
2917
2918            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2919                    SystemClock.uptimeMillis());
2920            Slog.i(TAG, "Time to scan packages: "
2921                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2922                    + " seconds");
2923
2924            // If the platform SDK has changed since the last time we booted,
2925            // we need to re-grant app permission to catch any new ones that
2926            // appear.  This is really a hack, and means that apps can in some
2927            // cases get permissions that the user didn't initially explicitly
2928            // allow...  it would be nice to have some better way to handle
2929            // this situation.
2930            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2931            if (sdkUpdated) {
2932                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2933                        + mSdkVersion + "; regranting permissions for internal storage");
2934            }
2935            mPermissionManager.updateAllPermissions(
2936                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2937                    mPermissionCallback);
2938            ver.sdkVersion = mSdkVersion;
2939
2940            // If this is the first boot or an update from pre-M, and it is a normal
2941            // boot, then we need to initialize the default preferred apps across
2942            // all defined users.
2943            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2944                for (UserInfo user : sUserManager.getUsers(true)) {
2945                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2946                    applyFactoryDefaultBrowserLPw(user.id);
2947                    primeDomainVerificationsLPw(user.id);
2948                }
2949            }
2950
2951            // Prepare storage for system user really early during boot,
2952            // since core system apps like SettingsProvider and SystemUI
2953            // can't wait for user to start
2954            final int storageFlags;
2955            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2956                storageFlags = StorageManager.FLAG_STORAGE_DE;
2957            } else {
2958                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2959            }
2960            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2961                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2962                    true /* onlyCoreApps */);
2963            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2964                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2965                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2966                traceLog.traceBegin("AppDataFixup");
2967                try {
2968                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2969                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2970                } catch (InstallerException e) {
2971                    Slog.w(TAG, "Trouble fixing GIDs", e);
2972                }
2973                traceLog.traceEnd();
2974
2975                traceLog.traceBegin("AppDataPrepare");
2976                if (deferPackages == null || deferPackages.isEmpty()) {
2977                    return;
2978                }
2979                int count = 0;
2980                for (String pkgName : deferPackages) {
2981                    PackageParser.Package pkg = null;
2982                    synchronized (mPackages) {
2983                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2984                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2985                            pkg = ps.pkg;
2986                        }
2987                    }
2988                    if (pkg != null) {
2989                        synchronized (mInstallLock) {
2990                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2991                                    true /* maybeMigrateAppData */);
2992                        }
2993                        count++;
2994                    }
2995                }
2996                traceLog.traceEnd();
2997                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2998            }, "prepareAppData");
2999
3000            // If this is first boot after an OTA, and a normal boot, then
3001            // we need to clear code cache directories.
3002            // Note that we do *not* clear the application profiles. These remain valid
3003            // across OTAs and are used to drive profile verification (post OTA) and
3004            // profile compilation (without waiting to collect a fresh set of profiles).
3005            if (mIsUpgrade && !onlyCore) {
3006                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3007                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3008                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3009                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3010                        // No apps are running this early, so no need to freeze
3011                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3012                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3013                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3014                    }
3015                }
3016                ver.fingerprint = Build.FINGERPRINT;
3017            }
3018
3019            checkDefaultBrowser();
3020
3021            // clear only after permissions and other defaults have been updated
3022            mExistingSystemPackages.clear();
3023            mPromoteSystemApps = false;
3024
3025            // All the changes are done during package scanning.
3026            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3027
3028            // can downgrade to reader
3029            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3030            mSettings.writeLPr();
3031            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3032            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3033                    SystemClock.uptimeMillis());
3034
3035            if (!mOnlyCore) {
3036                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3037                mRequiredInstallerPackage = getRequiredInstallerLPr();
3038                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3039                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3040                if (mIntentFilterVerifierComponent != null) {
3041                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3042                            mIntentFilterVerifierComponent);
3043                } else {
3044                    mIntentFilterVerifier = null;
3045                }
3046                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3047                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3048                        SharedLibraryInfo.VERSION_UNDEFINED);
3049                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3050                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3051                        SharedLibraryInfo.VERSION_UNDEFINED);
3052            } else {
3053                mRequiredVerifierPackage = null;
3054                mRequiredInstallerPackage = null;
3055                mRequiredUninstallerPackage = null;
3056                mIntentFilterVerifierComponent = null;
3057                mIntentFilterVerifier = null;
3058                mServicesSystemSharedLibraryPackageName = null;
3059                mSharedSystemSharedLibraryPackageName = null;
3060            }
3061
3062            mInstallerService = new PackageInstallerService(context, this);
3063            mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock);
3064            final Pair<ComponentName, String> instantAppResolverComponent =
3065                    getInstantAppResolverLPr();
3066            if (instantAppResolverComponent != null) {
3067                if (DEBUG_EPHEMERAL) {
3068                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3069                }
3070                mInstantAppResolverConnection = new EphemeralResolverConnection(
3071                        mContext, instantAppResolverComponent.first,
3072                        instantAppResolverComponent.second);
3073                mInstantAppResolverSettingsComponent =
3074                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3075            } else {
3076                mInstantAppResolverConnection = null;
3077                mInstantAppResolverSettingsComponent = null;
3078            }
3079            updateInstantAppInstallerLocked(null);
3080
3081            // Read and update the usage of dex files.
3082            // Do this at the end of PM init so that all the packages have their
3083            // data directory reconciled.
3084            // At this point we know the code paths of the packages, so we can validate
3085            // the disk file and build the internal cache.
3086            // The usage file is expected to be small so loading and verifying it
3087            // should take a fairly small time compare to the other activities (e.g. package
3088            // scanning).
3089            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3090            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3091            for (int userId : currentUserIds) {
3092                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3093            }
3094            mDexManager.load(userPackages);
3095            if (mIsUpgrade) {
3096                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3097                        (int) (SystemClock.uptimeMillis() - startTime));
3098            }
3099        } // synchronized (mPackages)
3100        } // synchronized (mInstallLock)
3101
3102        // Now after opening every single application zip, make sure they
3103        // are all flushed.  Not really needed, but keeps things nice and
3104        // tidy.
3105        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3106        Runtime.getRuntime().gc();
3107        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3108
3109        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3110        FallbackCategoryProvider.loadFallbacks();
3111        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3112
3113        // The initial scanning above does many calls into installd while
3114        // holding the mPackages lock, but we're mostly interested in yelling
3115        // once we have a booted system.
3116        mInstaller.setWarnIfHeld(mPackages);
3117
3118        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3119    }
3120
3121    /**
3122     * Uncompress and install stub applications.
3123     * <p>In order to save space on the system partition, some applications are shipped in a
3124     * compressed form. In addition the compressed bits for the full application, the
3125     * system image contains a tiny stub comprised of only the Android manifest.
3126     * <p>During the first boot, attempt to uncompress and install the full application. If
3127     * the application can't be installed for any reason, disable the stub and prevent
3128     * uncompressing the full application during future boots.
3129     * <p>In order to forcefully attempt an installation of a full application, go to app
3130     * settings and enable the application.
3131     */
3132    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3133        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3134            final String pkgName = stubSystemApps.get(i);
3135            // skip if the system package is already disabled
3136            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3137                stubSystemApps.remove(i);
3138                continue;
3139            }
3140            // skip if the package isn't installed (?!); this should never happen
3141            final PackageParser.Package pkg = mPackages.get(pkgName);
3142            if (pkg == null) {
3143                stubSystemApps.remove(i);
3144                continue;
3145            }
3146            // skip if the package has been disabled by the user
3147            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3148            if (ps != null) {
3149                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3150                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3151                    stubSystemApps.remove(i);
3152                    continue;
3153                }
3154            }
3155
3156            if (DEBUG_COMPRESSION) {
3157                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3158            }
3159
3160            // uncompress the binary to its eventual destination on /data
3161            final File scanFile = decompressPackage(pkg);
3162            if (scanFile == null) {
3163                continue;
3164            }
3165
3166            // install the package to replace the stub on /system
3167            try {
3168                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3169                removePackageLI(pkg, true /*chatty*/);
3170                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3171                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3172                        UserHandle.USER_SYSTEM, "android");
3173                stubSystemApps.remove(i);
3174                continue;
3175            } catch (PackageManagerException e) {
3176                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3177            }
3178
3179            // any failed attempt to install the package will be cleaned up later
3180        }
3181
3182        // disable any stub still left; these failed to install the full application
3183        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3184            final String pkgName = stubSystemApps.get(i);
3185            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3186            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3187                    UserHandle.USER_SYSTEM, "android");
3188            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3189        }
3190    }
3191
3192    /**
3193     * Decompresses the given package on the system image onto
3194     * the /data partition.
3195     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3196     */
3197    private File decompressPackage(PackageParser.Package pkg) {
3198        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3199        if (compressedFiles == null || compressedFiles.length == 0) {
3200            if (DEBUG_COMPRESSION) {
3201                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3202            }
3203            return null;
3204        }
3205        final File dstCodePath =
3206                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3207        int ret = PackageManager.INSTALL_SUCCEEDED;
3208        try {
3209            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3210            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3211            for (File srcFile : compressedFiles) {
3212                final String srcFileName = srcFile.getName();
3213                final String dstFileName = srcFileName.substring(
3214                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3215                final File dstFile = new File(dstCodePath, dstFileName);
3216                ret = decompressFile(srcFile, dstFile);
3217                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3218                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3219                            + "; pkg: " + pkg.packageName
3220                            + ", file: " + dstFileName);
3221                    break;
3222                }
3223            }
3224        } catch (ErrnoException e) {
3225            logCriticalInfo(Log.ERROR, "Failed to decompress"
3226                    + "; pkg: " + pkg.packageName
3227                    + ", err: " + e.errno);
3228        }
3229        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3230            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3231            NativeLibraryHelper.Handle handle = null;
3232            try {
3233                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3234                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3235                        null /*abiOverride*/);
3236            } catch (IOException e) {
3237                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3238                        + "; pkg: " + pkg.packageName);
3239                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3240            } finally {
3241                IoUtils.closeQuietly(handle);
3242            }
3243        }
3244        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3245            if (dstCodePath == null || !dstCodePath.exists()) {
3246                return null;
3247            }
3248            removeCodePathLI(dstCodePath);
3249            return null;
3250        }
3251
3252        return dstCodePath;
3253    }
3254
3255    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3256        // we're only interested in updating the installer appliction when 1) it's not
3257        // already set or 2) the modified package is the installer
3258        if (mInstantAppInstallerActivity != null
3259                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3260                        .equals(modifiedPackage)) {
3261            return;
3262        }
3263        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3264    }
3265
3266    private static File preparePackageParserCache(boolean isUpgrade) {
3267        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3268            return null;
3269        }
3270
3271        // Disable package parsing on eng builds to allow for faster incremental development.
3272        if (Build.IS_ENG) {
3273            return null;
3274        }
3275
3276        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3277            Slog.i(TAG, "Disabling package parser cache due to system property.");
3278            return null;
3279        }
3280
3281        // The base directory for the package parser cache lives under /data/system/.
3282        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3283                "package_cache");
3284        if (cacheBaseDir == null) {
3285            return null;
3286        }
3287
3288        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3289        // This also serves to "GC" unused entries when the package cache version changes (which
3290        // can only happen during upgrades).
3291        if (isUpgrade) {
3292            FileUtils.deleteContents(cacheBaseDir);
3293        }
3294
3295
3296        // Return the versioned package cache directory. This is something like
3297        // "/data/system/package_cache/1"
3298        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3299
3300        // The following is a workaround to aid development on non-numbered userdebug
3301        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3302        // the system partition is newer.
3303        //
3304        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3305        // that starts with "eng." to signify that this is an engineering build and not
3306        // destined for release.
3307        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3308            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3309
3310            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3311            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3312            // in general and should not be used for production changes. In this specific case,
3313            // we know that they will work.
3314            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3315            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3316                FileUtils.deleteContents(cacheBaseDir);
3317                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3318            }
3319        }
3320
3321        return cacheDir;
3322    }
3323
3324    @Override
3325    public boolean isFirstBoot() {
3326        // allow instant applications
3327        return mFirstBoot;
3328    }
3329
3330    @Override
3331    public boolean isOnlyCoreApps() {
3332        // allow instant applications
3333        return mOnlyCore;
3334    }
3335
3336    @Override
3337    public boolean isUpgrade() {
3338        // allow instant applications
3339        // The system property allows testing ota flow when upgraded to the same image.
3340        return mIsUpgrade || SystemProperties.getBoolean(
3341                "persist.pm.mock-upgrade", false /* default */);
3342    }
3343
3344    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3345        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3346
3347        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3348                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3349                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3350        if (matches.size() == 1) {
3351            return matches.get(0).getComponentInfo().packageName;
3352        } else if (matches.size() == 0) {
3353            Log.e(TAG, "There should probably be a verifier, but, none were found");
3354            return null;
3355        }
3356        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3357    }
3358
3359    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3360        synchronized (mPackages) {
3361            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3362            if (libraryEntry == null) {
3363                throw new IllegalStateException("Missing required shared library:" + name);
3364            }
3365            return libraryEntry.apk;
3366        }
3367    }
3368
3369    private @NonNull String getRequiredInstallerLPr() {
3370        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3371        intent.addCategory(Intent.CATEGORY_DEFAULT);
3372        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3373
3374        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3375                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3376                UserHandle.USER_SYSTEM);
3377        if (matches.size() == 1) {
3378            ResolveInfo resolveInfo = matches.get(0);
3379            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3380                throw new RuntimeException("The installer must be a privileged app");
3381            }
3382            return matches.get(0).getComponentInfo().packageName;
3383        } else {
3384            throw new RuntimeException("There must be exactly one installer; found " + matches);
3385        }
3386    }
3387
3388    private @NonNull String getRequiredUninstallerLPr() {
3389        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3390        intent.addCategory(Intent.CATEGORY_DEFAULT);
3391        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3392
3393        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3394                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3395                UserHandle.USER_SYSTEM);
3396        if (resolveInfo == null ||
3397                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3398            throw new RuntimeException("There must be exactly one uninstaller; found "
3399                    + resolveInfo);
3400        }
3401        return resolveInfo.getComponentInfo().packageName;
3402    }
3403
3404    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3405        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3406
3407        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3408                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3409                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3410        ResolveInfo best = null;
3411        final int N = matches.size();
3412        for (int i = 0; i < N; i++) {
3413            final ResolveInfo cur = matches.get(i);
3414            final String packageName = cur.getComponentInfo().packageName;
3415            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3416                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3417                continue;
3418            }
3419
3420            if (best == null || cur.priority > best.priority) {
3421                best = cur;
3422            }
3423        }
3424
3425        if (best != null) {
3426            return best.getComponentInfo().getComponentName();
3427        }
3428        Slog.w(TAG, "Intent filter verifier not found");
3429        return null;
3430    }
3431
3432    @Override
3433    public @Nullable ComponentName getInstantAppResolverComponent() {
3434        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3435            return null;
3436        }
3437        synchronized (mPackages) {
3438            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3439            if (instantAppResolver == null) {
3440                return null;
3441            }
3442            return instantAppResolver.first;
3443        }
3444    }
3445
3446    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3447        final String[] packageArray =
3448                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3449        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3450            if (DEBUG_EPHEMERAL) {
3451                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3452            }
3453            return null;
3454        }
3455
3456        final int callingUid = Binder.getCallingUid();
3457        final int resolveFlags =
3458                MATCH_DIRECT_BOOT_AWARE
3459                | MATCH_DIRECT_BOOT_UNAWARE
3460                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3461        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3462        final Intent resolverIntent = new Intent(actionName);
3463        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3464                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3465        // temporarily look for the old action
3466        if (resolvers.size() == 0) {
3467            if (DEBUG_EPHEMERAL) {
3468                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3469            }
3470            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3471            resolverIntent.setAction(actionName);
3472            resolvers = queryIntentServicesInternal(resolverIntent, null,
3473                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3474        }
3475        final int N = resolvers.size();
3476        if (N == 0) {
3477            if (DEBUG_EPHEMERAL) {
3478                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3479            }
3480            return null;
3481        }
3482
3483        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3484        for (int i = 0; i < N; i++) {
3485            final ResolveInfo info = resolvers.get(i);
3486
3487            if (info.serviceInfo == null) {
3488                continue;
3489            }
3490
3491            final String packageName = info.serviceInfo.packageName;
3492            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3493                if (DEBUG_EPHEMERAL) {
3494                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3495                            + " pkg: " + packageName + ", info:" + info);
3496                }
3497                continue;
3498            }
3499
3500            if (DEBUG_EPHEMERAL) {
3501                Slog.v(TAG, "Ephemeral resolver found;"
3502                        + " pkg: " + packageName + ", info:" + info);
3503            }
3504            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3505        }
3506        if (DEBUG_EPHEMERAL) {
3507            Slog.v(TAG, "Ephemeral resolver NOT found");
3508        }
3509        return null;
3510    }
3511
3512    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3513        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3514        intent.addCategory(Intent.CATEGORY_DEFAULT);
3515        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3516
3517        final int resolveFlags =
3518                MATCH_DIRECT_BOOT_AWARE
3519                | MATCH_DIRECT_BOOT_UNAWARE
3520                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3521        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3522                resolveFlags, UserHandle.USER_SYSTEM);
3523        // temporarily look for the old action
3524        if (matches.isEmpty()) {
3525            if (DEBUG_EPHEMERAL) {
3526                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3527            }
3528            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3529            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3530                    resolveFlags, UserHandle.USER_SYSTEM);
3531        }
3532        Iterator<ResolveInfo> iter = matches.iterator();
3533        while (iter.hasNext()) {
3534            final ResolveInfo rInfo = iter.next();
3535            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3536            if (ps != null) {
3537                final PermissionsState permissionsState = ps.getPermissionsState();
3538                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3539                    continue;
3540                }
3541            }
3542            iter.remove();
3543        }
3544        if (matches.size() == 0) {
3545            return null;
3546        } else if (matches.size() == 1) {
3547            return (ActivityInfo) matches.get(0).getComponentInfo();
3548        } else {
3549            throw new RuntimeException(
3550                    "There must be at most one ephemeral installer; found " + matches);
3551        }
3552    }
3553
3554    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3555            @NonNull ComponentName resolver) {
3556        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3557                .addCategory(Intent.CATEGORY_DEFAULT)
3558                .setPackage(resolver.getPackageName());
3559        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3560        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3561                UserHandle.USER_SYSTEM);
3562        // temporarily look for the old action
3563        if (matches.isEmpty()) {
3564            if (DEBUG_EPHEMERAL) {
3565                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3566            }
3567            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3568            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3569                    UserHandle.USER_SYSTEM);
3570        }
3571        if (matches.isEmpty()) {
3572            return null;
3573        }
3574        return matches.get(0).getComponentInfo().getComponentName();
3575    }
3576
3577    private void primeDomainVerificationsLPw(int userId) {
3578        if (DEBUG_DOMAIN_VERIFICATION) {
3579            Slog.d(TAG, "Priming domain verifications in user " + userId);
3580        }
3581
3582        SystemConfig systemConfig = SystemConfig.getInstance();
3583        ArraySet<String> packages = systemConfig.getLinkedApps();
3584
3585        for (String packageName : packages) {
3586            PackageParser.Package pkg = mPackages.get(packageName);
3587            if (pkg != null) {
3588                if (!pkg.isSystem()) {
3589                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3590                    continue;
3591                }
3592
3593                ArraySet<String> domains = null;
3594                for (PackageParser.Activity a : pkg.activities) {
3595                    for (ActivityIntentInfo filter : a.intents) {
3596                        if (hasValidDomains(filter)) {
3597                            if (domains == null) {
3598                                domains = new ArraySet<String>();
3599                            }
3600                            domains.addAll(filter.getHostsList());
3601                        }
3602                    }
3603                }
3604
3605                if (domains != null && domains.size() > 0) {
3606                    if (DEBUG_DOMAIN_VERIFICATION) {
3607                        Slog.v(TAG, "      + " + packageName);
3608                    }
3609                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3610                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3611                    // and then 'always' in the per-user state actually used for intent resolution.
3612                    final IntentFilterVerificationInfo ivi;
3613                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3614                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3615                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3616                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3617                } else {
3618                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3619                            + "' does not handle web links");
3620                }
3621            } else {
3622                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3623            }
3624        }
3625
3626        scheduleWritePackageRestrictionsLocked(userId);
3627        scheduleWriteSettingsLocked();
3628    }
3629
3630    private void applyFactoryDefaultBrowserLPw(int userId) {
3631        // The default browser app's package name is stored in a string resource,
3632        // with a product-specific overlay used for vendor customization.
3633        String browserPkg = mContext.getResources().getString(
3634                com.android.internal.R.string.default_browser);
3635        if (!TextUtils.isEmpty(browserPkg)) {
3636            // non-empty string => required to be a known package
3637            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3638            if (ps == null) {
3639                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3640                browserPkg = null;
3641            } else {
3642                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3643            }
3644        }
3645
3646        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3647        // default.  If there's more than one, just leave everything alone.
3648        if (browserPkg == null) {
3649            calculateDefaultBrowserLPw(userId);
3650        }
3651    }
3652
3653    private void calculateDefaultBrowserLPw(int userId) {
3654        List<String> allBrowsers = resolveAllBrowserApps(userId);
3655        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3656        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3657    }
3658
3659    private List<String> resolveAllBrowserApps(int userId) {
3660        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3661        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3662                PackageManager.MATCH_ALL, userId);
3663
3664        final int count = list.size();
3665        List<String> result = new ArrayList<String>(count);
3666        for (int i=0; i<count; i++) {
3667            ResolveInfo info = list.get(i);
3668            if (info.activityInfo == null
3669                    || !info.handleAllWebDataURI
3670                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3671                    || result.contains(info.activityInfo.packageName)) {
3672                continue;
3673            }
3674            result.add(info.activityInfo.packageName);
3675        }
3676
3677        return result;
3678    }
3679
3680    private boolean packageIsBrowser(String packageName, int userId) {
3681        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3682                PackageManager.MATCH_ALL, userId);
3683        final int N = list.size();
3684        for (int i = 0; i < N; i++) {
3685            ResolveInfo info = list.get(i);
3686            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3687                return true;
3688            }
3689        }
3690        return false;
3691    }
3692
3693    private void checkDefaultBrowser() {
3694        final int myUserId = UserHandle.myUserId();
3695        final String packageName = getDefaultBrowserPackageName(myUserId);
3696        if (packageName != null) {
3697            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3698            if (info == null) {
3699                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3700                synchronized (mPackages) {
3701                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3702                }
3703            }
3704        }
3705    }
3706
3707    @Override
3708    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3709            throws RemoteException {
3710        try {
3711            return super.onTransact(code, data, reply, flags);
3712        } catch (RuntimeException e) {
3713            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3714                Slog.wtf(TAG, "Package Manager Crash", e);
3715            }
3716            throw e;
3717        }
3718    }
3719
3720    static int[] appendInts(int[] cur, int[] add) {
3721        if (add == null) return cur;
3722        if (cur == null) return add;
3723        final int N = add.length;
3724        for (int i=0; i<N; i++) {
3725            cur = appendInt(cur, add[i]);
3726        }
3727        return cur;
3728    }
3729
3730    /**
3731     * Returns whether or not a full application can see an instant application.
3732     * <p>
3733     * Currently, there are three cases in which this can occur:
3734     * <ol>
3735     * <li>The calling application is a "special" process. Special processes
3736     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3737     * <li>The calling application has the permission
3738     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3739     * <li>The calling application is the default launcher on the
3740     *     system partition.</li>
3741     * </ol>
3742     */
3743    private boolean canViewInstantApps(int callingUid, int userId) {
3744        if (callingUid < Process.FIRST_APPLICATION_UID) {
3745            return true;
3746        }
3747        if (mContext.checkCallingOrSelfPermission(
3748                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3749            return true;
3750        }
3751        if (mContext.checkCallingOrSelfPermission(
3752                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3753            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3754            if (homeComponent != null
3755                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3756                return true;
3757            }
3758        }
3759        return false;
3760    }
3761
3762    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3763        if (!sUserManager.exists(userId)) return null;
3764        if (ps == null) {
3765            return null;
3766        }
3767        PackageParser.Package p = ps.pkg;
3768        if (p == null) {
3769            return null;
3770        }
3771        final int callingUid = Binder.getCallingUid();
3772        // Filter out ephemeral app metadata:
3773        //   * The system/shell/root can see metadata for any app
3774        //   * An installed app can see metadata for 1) other installed apps
3775        //     and 2) ephemeral apps that have explicitly interacted with it
3776        //   * Ephemeral apps can only see their own data and exposed installed apps
3777        //   * Holding a signature permission allows seeing instant apps
3778        if (filterAppAccessLPr(ps, callingUid, userId)) {
3779            return null;
3780        }
3781
3782        final PermissionsState permissionsState = ps.getPermissionsState();
3783
3784        // Compute GIDs only if requested
3785        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3786                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3787        // Compute granted permissions only if package has requested permissions
3788        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3789                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3790        final PackageUserState state = ps.readUserState(userId);
3791
3792        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3793                && ps.isSystem()) {
3794            flags |= MATCH_ANY_USER;
3795        }
3796
3797        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3798                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3799
3800        if (packageInfo == null) {
3801            return null;
3802        }
3803
3804        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3805                resolveExternalPackageNameLPr(p);
3806
3807        return packageInfo;
3808    }
3809
3810    @Override
3811    public void checkPackageStartable(String packageName, int userId) {
3812        final int callingUid = Binder.getCallingUid();
3813        if (getInstantAppPackageName(callingUid) != null) {
3814            throw new SecurityException("Instant applications don't have access to this method");
3815        }
3816        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3817        synchronized (mPackages) {
3818            final PackageSetting ps = mSettings.mPackages.get(packageName);
3819            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3820                throw new SecurityException("Package " + packageName + " was not found!");
3821            }
3822
3823            if (!ps.getInstalled(userId)) {
3824                throw new SecurityException(
3825                        "Package " + packageName + " was not installed for user " + userId + "!");
3826            }
3827
3828            if (mSafeMode && !ps.isSystem()) {
3829                throw new SecurityException("Package " + packageName + " not a system app!");
3830            }
3831
3832            if (mFrozenPackages.contains(packageName)) {
3833                throw new SecurityException("Package " + packageName + " is currently frozen!");
3834            }
3835
3836            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3837                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3838            }
3839        }
3840    }
3841
3842    @Override
3843    public boolean isPackageAvailable(String packageName, int userId) {
3844        if (!sUserManager.exists(userId)) return false;
3845        final int callingUid = Binder.getCallingUid();
3846        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3847                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3848        synchronized (mPackages) {
3849            PackageParser.Package p = mPackages.get(packageName);
3850            if (p != null) {
3851                final PackageSetting ps = (PackageSetting) p.mExtras;
3852                if (filterAppAccessLPr(ps, callingUid, userId)) {
3853                    return false;
3854                }
3855                if (ps != null) {
3856                    final PackageUserState state = ps.readUserState(userId);
3857                    if (state != null) {
3858                        return PackageParser.isAvailable(state);
3859                    }
3860                }
3861            }
3862        }
3863        return false;
3864    }
3865
3866    @Override
3867    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3868        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3869                flags, Binder.getCallingUid(), userId);
3870    }
3871
3872    @Override
3873    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3874            int flags, int userId) {
3875        return getPackageInfoInternal(versionedPackage.getPackageName(),
3876                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3877    }
3878
3879    /**
3880     * Important: The provided filterCallingUid is used exclusively to filter out packages
3881     * that can be seen based on user state. It's typically the original caller uid prior
3882     * to clearing. Because it can only be provided by trusted code, it's value can be
3883     * trusted and will be used as-is; unlike userId which will be validated by this method.
3884     */
3885    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3886            int flags, int filterCallingUid, int userId) {
3887        if (!sUserManager.exists(userId)) return null;
3888        flags = updateFlagsForPackage(flags, userId, packageName);
3889        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3890                false /* requireFullPermission */, false /* checkShell */, "get package info");
3891
3892        // reader
3893        synchronized (mPackages) {
3894            // Normalize package name to handle renamed packages and static libs
3895            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3896
3897            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3898            if (matchFactoryOnly) {
3899                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3900                if (ps != null) {
3901                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3902                        return null;
3903                    }
3904                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3905                        return null;
3906                    }
3907                    return generatePackageInfo(ps, flags, userId);
3908                }
3909            }
3910
3911            PackageParser.Package p = mPackages.get(packageName);
3912            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3913                return null;
3914            }
3915            if (DEBUG_PACKAGE_INFO)
3916                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3917            if (p != null) {
3918                final PackageSetting ps = (PackageSetting) p.mExtras;
3919                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3920                    return null;
3921                }
3922                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3923                    return null;
3924                }
3925                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3926            }
3927            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3928                final PackageSetting ps = mSettings.mPackages.get(packageName);
3929                if (ps == null) return null;
3930                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3931                    return null;
3932                }
3933                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3934                    return null;
3935                }
3936                return generatePackageInfo(ps, flags, userId);
3937            }
3938        }
3939        return null;
3940    }
3941
3942    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3943        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3944            return true;
3945        }
3946        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3947            return true;
3948        }
3949        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3950            return true;
3951        }
3952        return false;
3953    }
3954
3955    private boolean isComponentVisibleToInstantApp(
3956            @Nullable ComponentName component, @ComponentType int type) {
3957        if (type == TYPE_ACTIVITY) {
3958            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3959            return activity != null
3960                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3961                    : false;
3962        } else if (type == TYPE_RECEIVER) {
3963            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3964            return activity != null
3965                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3966                    : false;
3967        } else if (type == TYPE_SERVICE) {
3968            final PackageParser.Service service = mServices.mServices.get(component);
3969            return service != null
3970                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3971                    : false;
3972        } else if (type == TYPE_PROVIDER) {
3973            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3974            return provider != null
3975                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3976                    : false;
3977        } else if (type == TYPE_UNKNOWN) {
3978            return isComponentVisibleToInstantApp(component);
3979        }
3980        return false;
3981    }
3982
3983    /**
3984     * Returns whether or not access to the application should be filtered.
3985     * <p>
3986     * Access may be limited based upon whether the calling or target applications
3987     * are instant applications.
3988     *
3989     * @see #canAccessInstantApps(int)
3990     */
3991    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3992            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3993        // if we're in an isolated process, get the real calling UID
3994        if (Process.isIsolated(callingUid)) {
3995            callingUid = mIsolatedOwners.get(callingUid);
3996        }
3997        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3998        final boolean callerIsInstantApp = instantAppPkgName != null;
3999        if (ps == null) {
4000            if (callerIsInstantApp) {
4001                // pretend the application exists, but, needs to be filtered
4002                return true;
4003            }
4004            return false;
4005        }
4006        // if the target and caller are the same application, don't filter
4007        if (isCallerSameApp(ps.name, callingUid)) {
4008            return false;
4009        }
4010        if (callerIsInstantApp) {
4011            // request for a specific component; if it hasn't been explicitly exposed, filter
4012            if (component != null) {
4013                return !isComponentVisibleToInstantApp(component, componentType);
4014            }
4015            // request for application; if no components have been explicitly exposed, filter
4016            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4017        }
4018        if (ps.getInstantApp(userId)) {
4019            // caller can see all components of all instant applications, don't filter
4020            if (canViewInstantApps(callingUid, userId)) {
4021                return false;
4022            }
4023            // request for a specific instant application component, filter
4024            if (component != null) {
4025                return true;
4026            }
4027            // request for an instant application; if the caller hasn't been granted access, filter
4028            return !mInstantAppRegistry.isInstantAccessGranted(
4029                    userId, UserHandle.getAppId(callingUid), ps.appId);
4030        }
4031        return false;
4032    }
4033
4034    /**
4035     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4036     */
4037    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4038        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4039    }
4040
4041    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4042            int flags) {
4043        // Callers can access only the libs they depend on, otherwise they need to explicitly
4044        // ask for the shared libraries given the caller is allowed to access all static libs.
4045        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4046            // System/shell/root get to see all static libs
4047            final int appId = UserHandle.getAppId(uid);
4048            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4049                    || appId == Process.ROOT_UID) {
4050                return false;
4051            }
4052        }
4053
4054        // No package means no static lib as it is always on internal storage
4055        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4056            return false;
4057        }
4058
4059        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4060                ps.pkg.staticSharedLibVersion);
4061        if (libEntry == null) {
4062            return false;
4063        }
4064
4065        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4066        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4067        if (uidPackageNames == null) {
4068            return true;
4069        }
4070
4071        for (String uidPackageName : uidPackageNames) {
4072            if (ps.name.equals(uidPackageName)) {
4073                return false;
4074            }
4075            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4076            if (uidPs != null) {
4077                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4078                        libEntry.info.getName());
4079                if (index < 0) {
4080                    continue;
4081                }
4082                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4083                    return false;
4084                }
4085            }
4086        }
4087        return true;
4088    }
4089
4090    @Override
4091    public String[] currentToCanonicalPackageNames(String[] names) {
4092        final int callingUid = Binder.getCallingUid();
4093        if (getInstantAppPackageName(callingUid) != null) {
4094            return names;
4095        }
4096        final String[] out = new String[names.length];
4097        // reader
4098        synchronized (mPackages) {
4099            final int callingUserId = UserHandle.getUserId(callingUid);
4100            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4101            for (int i=names.length-1; i>=0; i--) {
4102                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4103                boolean translateName = false;
4104                if (ps != null && ps.realName != null) {
4105                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4106                    translateName = !targetIsInstantApp
4107                            || canViewInstantApps
4108                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4109                                    UserHandle.getAppId(callingUid), ps.appId);
4110                }
4111                out[i] = translateName ? ps.realName : names[i];
4112            }
4113        }
4114        return out;
4115    }
4116
4117    @Override
4118    public String[] canonicalToCurrentPackageNames(String[] names) {
4119        final int callingUid = Binder.getCallingUid();
4120        if (getInstantAppPackageName(callingUid) != null) {
4121            return names;
4122        }
4123        final String[] out = new String[names.length];
4124        // reader
4125        synchronized (mPackages) {
4126            final int callingUserId = UserHandle.getUserId(callingUid);
4127            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4128            for (int i=names.length-1; i>=0; i--) {
4129                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4130                boolean translateName = false;
4131                if (cur != null) {
4132                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4133                    final boolean targetIsInstantApp =
4134                            ps != null && ps.getInstantApp(callingUserId);
4135                    translateName = !targetIsInstantApp
4136                            || canViewInstantApps
4137                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4138                                    UserHandle.getAppId(callingUid), ps.appId);
4139                }
4140                out[i] = translateName ? cur : names[i];
4141            }
4142        }
4143        return out;
4144    }
4145
4146    @Override
4147    public int getPackageUid(String packageName, int flags, int userId) {
4148        if (!sUserManager.exists(userId)) return -1;
4149        final int callingUid = Binder.getCallingUid();
4150        flags = updateFlagsForPackage(flags, userId, packageName);
4151        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4152                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4153
4154        // reader
4155        synchronized (mPackages) {
4156            final PackageParser.Package p = mPackages.get(packageName);
4157            if (p != null && p.isMatch(flags)) {
4158                PackageSetting ps = (PackageSetting) p.mExtras;
4159                if (filterAppAccessLPr(ps, callingUid, userId)) {
4160                    return -1;
4161                }
4162                return UserHandle.getUid(userId, p.applicationInfo.uid);
4163            }
4164            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4165                final PackageSetting ps = mSettings.mPackages.get(packageName);
4166                if (ps != null && ps.isMatch(flags)
4167                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4168                    return UserHandle.getUid(userId, ps.appId);
4169                }
4170            }
4171        }
4172
4173        return -1;
4174    }
4175
4176    @Override
4177    public int[] getPackageGids(String packageName, int flags, int userId) {
4178        if (!sUserManager.exists(userId)) return null;
4179        final int callingUid = Binder.getCallingUid();
4180        flags = updateFlagsForPackage(flags, userId, packageName);
4181        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4182                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4183
4184        // reader
4185        synchronized (mPackages) {
4186            final PackageParser.Package p = mPackages.get(packageName);
4187            if (p != null && p.isMatch(flags)) {
4188                PackageSetting ps = (PackageSetting) p.mExtras;
4189                if (filterAppAccessLPr(ps, callingUid, userId)) {
4190                    return null;
4191                }
4192                // TODO: Shouldn't this be checking for package installed state for userId and
4193                // return null?
4194                return ps.getPermissionsState().computeGids(userId);
4195            }
4196            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4197                final PackageSetting ps = mSettings.mPackages.get(packageName);
4198                if (ps != null && ps.isMatch(flags)
4199                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4200                    return ps.getPermissionsState().computeGids(userId);
4201                }
4202            }
4203        }
4204
4205        return null;
4206    }
4207
4208    @Override
4209    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4210        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4211    }
4212
4213    @Override
4214    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4215            int flags) {
4216        final List<PermissionInfo> permissionList =
4217                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4218        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4219    }
4220
4221    @Override
4222    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4223        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4224    }
4225
4226    @Override
4227    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4228        final List<PermissionGroupInfo> permissionList =
4229                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4230        return (permissionList == null)
4231                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4232    }
4233
4234    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4235            int filterCallingUid, int userId) {
4236        if (!sUserManager.exists(userId)) return null;
4237        PackageSetting ps = mSettings.mPackages.get(packageName);
4238        if (ps != null) {
4239            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4240                return null;
4241            }
4242            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4243                return null;
4244            }
4245            if (ps.pkg == null) {
4246                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4247                if (pInfo != null) {
4248                    return pInfo.applicationInfo;
4249                }
4250                return null;
4251            }
4252            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4253                    ps.readUserState(userId), userId);
4254            if (ai != null) {
4255                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4256            }
4257            return ai;
4258        }
4259        return null;
4260    }
4261
4262    @Override
4263    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4264        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4265    }
4266
4267    /**
4268     * Important: The provided filterCallingUid is used exclusively to filter out applications
4269     * that can be seen based on user state. It's typically the original caller uid prior
4270     * to clearing. Because it can only be provided by trusted code, it's value can be
4271     * trusted and will be used as-is; unlike userId which will be validated by this method.
4272     */
4273    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4274            int filterCallingUid, int userId) {
4275        if (!sUserManager.exists(userId)) return null;
4276        flags = updateFlagsForApplication(flags, userId, packageName);
4277        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4278                false /* requireFullPermission */, false /* checkShell */, "get application info");
4279
4280        // writer
4281        synchronized (mPackages) {
4282            // Normalize package name to handle renamed packages and static libs
4283            packageName = resolveInternalPackageNameLPr(packageName,
4284                    PackageManager.VERSION_CODE_HIGHEST);
4285
4286            PackageParser.Package p = mPackages.get(packageName);
4287            if (DEBUG_PACKAGE_INFO) Log.v(
4288                    TAG, "getApplicationInfo " + packageName
4289                    + ": " + p);
4290            if (p != null) {
4291                PackageSetting ps = mSettings.mPackages.get(packageName);
4292                if (ps == null) return null;
4293                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4294                    return null;
4295                }
4296                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4297                    return null;
4298                }
4299                // Note: isEnabledLP() does not apply here - always return info
4300                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4301                        p, flags, ps.readUserState(userId), userId);
4302                if (ai != null) {
4303                    ai.packageName = resolveExternalPackageNameLPr(p);
4304                }
4305                return ai;
4306            }
4307            if ("android".equals(packageName)||"system".equals(packageName)) {
4308                return mAndroidApplication;
4309            }
4310            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4311                // Already generates the external package name
4312                return generateApplicationInfoFromSettingsLPw(packageName,
4313                        flags, filterCallingUid, userId);
4314            }
4315        }
4316        return null;
4317    }
4318
4319    private String normalizePackageNameLPr(String packageName) {
4320        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4321        return normalizedPackageName != null ? normalizedPackageName : packageName;
4322    }
4323
4324    @Override
4325    public void deletePreloadsFileCache() {
4326        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4327            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4328        }
4329        File dir = Environment.getDataPreloadsFileCacheDirectory();
4330        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4331        FileUtils.deleteContents(dir);
4332    }
4333
4334    @Override
4335    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4336            final int storageFlags, final IPackageDataObserver observer) {
4337        mContext.enforceCallingOrSelfPermission(
4338                android.Manifest.permission.CLEAR_APP_CACHE, null);
4339        mHandler.post(() -> {
4340            boolean success = false;
4341            try {
4342                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4343                success = true;
4344            } catch (IOException e) {
4345                Slog.w(TAG, e);
4346            }
4347            if (observer != null) {
4348                try {
4349                    observer.onRemoveCompleted(null, success);
4350                } catch (RemoteException e) {
4351                    Slog.w(TAG, e);
4352                }
4353            }
4354        });
4355    }
4356
4357    @Override
4358    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4359            final int storageFlags, final IntentSender pi) {
4360        mContext.enforceCallingOrSelfPermission(
4361                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4362        mHandler.post(() -> {
4363            boolean success = false;
4364            try {
4365                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4366                success = true;
4367            } catch (IOException e) {
4368                Slog.w(TAG, e);
4369            }
4370            if (pi != null) {
4371                try {
4372                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4373                } catch (SendIntentException e) {
4374                    Slog.w(TAG, e);
4375                }
4376            }
4377        });
4378    }
4379
4380    /**
4381     * Blocking call to clear various types of cached data across the system
4382     * until the requested bytes are available.
4383     */
4384    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4385        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4386        final File file = storage.findPathForUuid(volumeUuid);
4387        if (file.getUsableSpace() >= bytes) return;
4388
4389        if (ENABLE_FREE_CACHE_V2) {
4390            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4391                    volumeUuid);
4392            final boolean aggressive = (storageFlags
4393                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4394            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4395
4396            // 1. Pre-flight to determine if we have any chance to succeed
4397            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4398            if (internalVolume && (aggressive || SystemProperties
4399                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4400                deletePreloadsFileCache();
4401                if (file.getUsableSpace() >= bytes) return;
4402            }
4403
4404            // 3. Consider parsed APK data (aggressive only)
4405            if (internalVolume && aggressive) {
4406                FileUtils.deleteContents(mCacheDir);
4407                if (file.getUsableSpace() >= bytes) return;
4408            }
4409
4410            // 4. Consider cached app data (above quotas)
4411            try {
4412                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4413                        Installer.FLAG_FREE_CACHE_V2);
4414            } catch (InstallerException ignored) {
4415            }
4416            if (file.getUsableSpace() >= bytes) return;
4417
4418            // 5. Consider shared libraries with refcount=0 and age>min cache period
4419            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4420                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4421                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4422                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4423                return;
4424            }
4425
4426            // 6. Consider dexopt output (aggressive only)
4427            // TODO: Implement
4428
4429            // 7. Consider installed instant apps unused longer than min cache period
4430            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4431                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4432                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4433                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4434                return;
4435            }
4436
4437            // 8. Consider cached app data (below quotas)
4438            try {
4439                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4440                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4441            } catch (InstallerException ignored) {
4442            }
4443            if (file.getUsableSpace() >= bytes) return;
4444
4445            // 9. Consider DropBox entries
4446            // TODO: Implement
4447
4448            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4449            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4450                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4451                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4452                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4453                return;
4454            }
4455        } else {
4456            try {
4457                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4458            } catch (InstallerException ignored) {
4459            }
4460            if (file.getUsableSpace() >= bytes) return;
4461        }
4462
4463        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4464    }
4465
4466    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4467            throws IOException {
4468        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4469        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4470
4471        List<VersionedPackage> packagesToDelete = null;
4472        final long now = System.currentTimeMillis();
4473
4474        synchronized (mPackages) {
4475            final int[] allUsers = sUserManager.getUserIds();
4476            final int libCount = mSharedLibraries.size();
4477            for (int i = 0; i < libCount; i++) {
4478                final LongSparseArray<SharedLibraryEntry> versionedLib
4479                        = mSharedLibraries.valueAt(i);
4480                if (versionedLib == null) {
4481                    continue;
4482                }
4483                final int versionCount = versionedLib.size();
4484                for (int j = 0; j < versionCount; j++) {
4485                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4486                    // Skip packages that are not static shared libs.
4487                    if (!libInfo.isStatic()) {
4488                        break;
4489                    }
4490                    // Important: We skip static shared libs used for some user since
4491                    // in such a case we need to keep the APK on the device. The check for
4492                    // a lib being used for any user is performed by the uninstall call.
4493                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4494                    // Resolve the package name - we use synthetic package names internally
4495                    final String internalPackageName = resolveInternalPackageNameLPr(
4496                            declaringPackage.getPackageName(),
4497                            declaringPackage.getLongVersionCode());
4498                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4499                    // Skip unused static shared libs cached less than the min period
4500                    // to prevent pruning a lib needed by a subsequently installed package.
4501                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4502                        continue;
4503                    }
4504                    if (packagesToDelete == null) {
4505                        packagesToDelete = new ArrayList<>();
4506                    }
4507                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4508                            declaringPackage.getLongVersionCode()));
4509                }
4510            }
4511        }
4512
4513        if (packagesToDelete != null) {
4514            final int packageCount = packagesToDelete.size();
4515            for (int i = 0; i < packageCount; i++) {
4516                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4517                // Delete the package synchronously (will fail of the lib used for any user).
4518                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4519                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4520                                == PackageManager.DELETE_SUCCEEDED) {
4521                    if (volume.getUsableSpace() >= neededSpace) {
4522                        return true;
4523                    }
4524                }
4525            }
4526        }
4527
4528        return false;
4529    }
4530
4531    /**
4532     * Update given flags based on encryption status of current user.
4533     */
4534    private int updateFlags(int flags, int userId) {
4535        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4536                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4537            // Caller expressed an explicit opinion about what encryption
4538            // aware/unaware components they want to see, so fall through and
4539            // give them what they want
4540        } else {
4541            // Caller expressed no opinion, so match based on user state
4542            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4543                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4544            } else {
4545                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4546            }
4547        }
4548        return flags;
4549    }
4550
4551    private UserManagerInternal getUserManagerInternal() {
4552        if (mUserManagerInternal == null) {
4553            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4554        }
4555        return mUserManagerInternal;
4556    }
4557
4558    private DeviceIdleController.LocalService getDeviceIdleController() {
4559        if (mDeviceIdleController == null) {
4560            mDeviceIdleController =
4561                    LocalServices.getService(DeviceIdleController.LocalService.class);
4562        }
4563        return mDeviceIdleController;
4564    }
4565
4566    /**
4567     * Update given flags when being used to request {@link PackageInfo}.
4568     */
4569    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4570        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4571        boolean triaged = true;
4572        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4573                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4574            // Caller is asking for component details, so they'd better be
4575            // asking for specific encryption matching behavior, or be triaged
4576            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4577                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4578                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4579                triaged = false;
4580            }
4581        }
4582        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4583                | PackageManager.MATCH_SYSTEM_ONLY
4584                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4585            triaged = false;
4586        }
4587        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4588            mPermissionManager.enforceCrossUserPermission(
4589                    Binder.getCallingUid(), userId, false, false,
4590                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4591                    + Debug.getCallers(5));
4592        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4593                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4594            // If the caller wants all packages and has a restricted profile associated with it,
4595            // then match all users. This is to make sure that launchers that need to access work
4596            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4597            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4598            flags |= PackageManager.MATCH_ANY_USER;
4599        }
4600        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4601            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4602                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4603        }
4604        return updateFlags(flags, userId);
4605    }
4606
4607    /**
4608     * Update given flags when being used to request {@link ApplicationInfo}.
4609     */
4610    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4611        return updateFlagsForPackage(flags, userId, cookie);
4612    }
4613
4614    /**
4615     * Update given flags when being used to request {@link ComponentInfo}.
4616     */
4617    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4618        if (cookie instanceof Intent) {
4619            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4620                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4621            }
4622        }
4623
4624        boolean triaged = true;
4625        // Caller is asking for component details, so they'd better be
4626        // asking for specific encryption matching behavior, or be triaged
4627        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4628                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4629                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4630            triaged = false;
4631        }
4632        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4633            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4634                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4635        }
4636
4637        return updateFlags(flags, userId);
4638    }
4639
4640    /**
4641     * Update given intent when being used to request {@link ResolveInfo}.
4642     */
4643    private Intent updateIntentForResolve(Intent intent) {
4644        if (intent.getSelector() != null) {
4645            intent = intent.getSelector();
4646        }
4647        if (DEBUG_PREFERRED) {
4648            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4649        }
4650        return intent;
4651    }
4652
4653    /**
4654     * Update given flags when being used to request {@link ResolveInfo}.
4655     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4656     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4657     * flag set. However, this flag is only honoured in three circumstances:
4658     * <ul>
4659     * <li>when called from a system process</li>
4660     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4661     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4662     * action and a {@code android.intent.category.BROWSABLE} category</li>
4663     * </ul>
4664     */
4665    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4666        return updateFlagsForResolve(flags, userId, intent, callingUid,
4667                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4668    }
4669    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4670            boolean wantInstantApps) {
4671        return updateFlagsForResolve(flags, userId, intent, callingUid,
4672                wantInstantApps, false /*onlyExposedExplicitly*/);
4673    }
4674    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4675            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4676        // Safe mode means we shouldn't match any third-party components
4677        if (mSafeMode) {
4678            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4679        }
4680        if (getInstantAppPackageName(callingUid) != null) {
4681            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4682            if (onlyExposedExplicitly) {
4683                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4684            }
4685            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4686            flags |= PackageManager.MATCH_INSTANT;
4687        } else {
4688            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4689            final boolean allowMatchInstant =
4690                    (wantInstantApps
4691                            && Intent.ACTION_VIEW.equals(intent.getAction())
4692                            && hasWebURI(intent))
4693                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4694            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4695                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4696            if (!allowMatchInstant) {
4697                flags &= ~PackageManager.MATCH_INSTANT;
4698            }
4699        }
4700        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4701    }
4702
4703    @Override
4704    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4705        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4706    }
4707
4708    /**
4709     * Important: The provided filterCallingUid is used exclusively to filter out activities
4710     * that can be seen based on user state. It's typically the original caller uid prior
4711     * to clearing. Because it can only be provided by trusted code, it's value can be
4712     * trusted and will be used as-is; unlike userId which will be validated by this method.
4713     */
4714    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4715            int filterCallingUid, int userId) {
4716        if (!sUserManager.exists(userId)) return null;
4717        flags = updateFlagsForComponent(flags, userId, component);
4718        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4719                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4720        synchronized (mPackages) {
4721            PackageParser.Activity a = mActivities.mActivities.get(component);
4722
4723            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4724            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4725                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4726                if (ps == null) return null;
4727                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4728                    return null;
4729                }
4730                return PackageParser.generateActivityInfo(
4731                        a, flags, ps.readUserState(userId), userId);
4732            }
4733            if (mResolveComponentName.equals(component)) {
4734                return PackageParser.generateActivityInfo(
4735                        mResolveActivity, flags, new PackageUserState(), userId);
4736            }
4737        }
4738        return null;
4739    }
4740
4741    @Override
4742    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4743            String resolvedType) {
4744        synchronized (mPackages) {
4745            if (component.equals(mResolveComponentName)) {
4746                // The resolver supports EVERYTHING!
4747                return true;
4748            }
4749            final int callingUid = Binder.getCallingUid();
4750            final int callingUserId = UserHandle.getUserId(callingUid);
4751            PackageParser.Activity a = mActivities.mActivities.get(component);
4752            if (a == null) {
4753                return false;
4754            }
4755            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4756            if (ps == null) {
4757                return false;
4758            }
4759            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4760                return false;
4761            }
4762            for (int i=0; i<a.intents.size(); i++) {
4763                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4764                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4765                    return true;
4766                }
4767            }
4768            return false;
4769        }
4770    }
4771
4772    @Override
4773    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4774        if (!sUserManager.exists(userId)) return null;
4775        final int callingUid = Binder.getCallingUid();
4776        flags = updateFlagsForComponent(flags, userId, component);
4777        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4778                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4779        synchronized (mPackages) {
4780            PackageParser.Activity a = mReceivers.mActivities.get(component);
4781            if (DEBUG_PACKAGE_INFO) Log.v(
4782                TAG, "getReceiverInfo " + component + ": " + a);
4783            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4784                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4785                if (ps == null) return null;
4786                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4787                    return null;
4788                }
4789                return PackageParser.generateActivityInfo(
4790                        a, flags, ps.readUserState(userId), userId);
4791            }
4792        }
4793        return null;
4794    }
4795
4796    @Override
4797    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4798            int flags, int userId) {
4799        if (!sUserManager.exists(userId)) return null;
4800        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4801        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4802            return null;
4803        }
4804
4805        flags = updateFlagsForPackage(flags, userId, null);
4806
4807        final boolean canSeeStaticLibraries =
4808                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4809                        == PERMISSION_GRANTED
4810                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4811                        == PERMISSION_GRANTED
4812                || canRequestPackageInstallsInternal(packageName,
4813                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4814                        false  /* throwIfPermNotDeclared*/)
4815                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4816                        == PERMISSION_GRANTED;
4817
4818        synchronized (mPackages) {
4819            List<SharedLibraryInfo> result = null;
4820
4821            final int libCount = mSharedLibraries.size();
4822            for (int i = 0; i < libCount; i++) {
4823                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4824                if (versionedLib == null) {
4825                    continue;
4826                }
4827
4828                final int versionCount = versionedLib.size();
4829                for (int j = 0; j < versionCount; j++) {
4830                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4831                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4832                        break;
4833                    }
4834                    final long identity = Binder.clearCallingIdentity();
4835                    try {
4836                        PackageInfo packageInfo = getPackageInfoVersioned(
4837                                libInfo.getDeclaringPackage(), flags
4838                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4839                        if (packageInfo == null) {
4840                            continue;
4841                        }
4842                    } finally {
4843                        Binder.restoreCallingIdentity(identity);
4844                    }
4845
4846                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4847                            libInfo.getLongVersion(), libInfo.getType(),
4848                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4849                            flags, userId));
4850
4851                    if (result == null) {
4852                        result = new ArrayList<>();
4853                    }
4854                    result.add(resLibInfo);
4855                }
4856            }
4857
4858            return result != null ? new ParceledListSlice<>(result) : null;
4859        }
4860    }
4861
4862    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4863            SharedLibraryInfo libInfo, int flags, int userId) {
4864        List<VersionedPackage> versionedPackages = null;
4865        final int packageCount = mSettings.mPackages.size();
4866        for (int i = 0; i < packageCount; i++) {
4867            PackageSetting ps = mSettings.mPackages.valueAt(i);
4868
4869            if (ps == null) {
4870                continue;
4871            }
4872
4873            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4874                continue;
4875            }
4876
4877            final String libName = libInfo.getName();
4878            if (libInfo.isStatic()) {
4879                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4880                if (libIdx < 0) {
4881                    continue;
4882                }
4883                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4884                    continue;
4885                }
4886                if (versionedPackages == null) {
4887                    versionedPackages = new ArrayList<>();
4888                }
4889                // If the dependent is a static shared lib, use the public package name
4890                String dependentPackageName = ps.name;
4891                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4892                    dependentPackageName = ps.pkg.manifestPackageName;
4893                }
4894                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4895            } else if (ps.pkg != null) {
4896                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4897                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4898                    if (versionedPackages == null) {
4899                        versionedPackages = new ArrayList<>();
4900                    }
4901                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4902                }
4903            }
4904        }
4905
4906        return versionedPackages;
4907    }
4908
4909    @Override
4910    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4911        if (!sUserManager.exists(userId)) return null;
4912        final int callingUid = Binder.getCallingUid();
4913        flags = updateFlagsForComponent(flags, userId, component);
4914        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4915                false /* requireFullPermission */, false /* checkShell */, "get service info");
4916        synchronized (mPackages) {
4917            PackageParser.Service s = mServices.mServices.get(component);
4918            if (DEBUG_PACKAGE_INFO) Log.v(
4919                TAG, "getServiceInfo " + component + ": " + s);
4920            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4921                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4922                if (ps == null) return null;
4923                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4924                    return null;
4925                }
4926                return PackageParser.generateServiceInfo(
4927                        s, flags, ps.readUserState(userId), userId);
4928            }
4929        }
4930        return null;
4931    }
4932
4933    @Override
4934    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4935        if (!sUserManager.exists(userId)) return null;
4936        final int callingUid = Binder.getCallingUid();
4937        flags = updateFlagsForComponent(flags, userId, component);
4938        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4939                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4940        synchronized (mPackages) {
4941            PackageParser.Provider p = mProviders.mProviders.get(component);
4942            if (DEBUG_PACKAGE_INFO) Log.v(
4943                TAG, "getProviderInfo " + component + ": " + p);
4944            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4945                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4946                if (ps == null) return null;
4947                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4948                    return null;
4949                }
4950                return PackageParser.generateProviderInfo(
4951                        p, flags, ps.readUserState(userId), userId);
4952            }
4953        }
4954        return null;
4955    }
4956
4957    @Override
4958    public String[] getSystemSharedLibraryNames() {
4959        // allow instant applications
4960        synchronized (mPackages) {
4961            Set<String> libs = null;
4962            final int libCount = mSharedLibraries.size();
4963            for (int i = 0; i < libCount; i++) {
4964                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4965                if (versionedLib == null) {
4966                    continue;
4967                }
4968                final int versionCount = versionedLib.size();
4969                for (int j = 0; j < versionCount; j++) {
4970                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4971                    if (!libEntry.info.isStatic()) {
4972                        if (libs == null) {
4973                            libs = new ArraySet<>();
4974                        }
4975                        libs.add(libEntry.info.getName());
4976                        break;
4977                    }
4978                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4979                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4980                            UserHandle.getUserId(Binder.getCallingUid()),
4981                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4982                        if (libs == null) {
4983                            libs = new ArraySet<>();
4984                        }
4985                        libs.add(libEntry.info.getName());
4986                        break;
4987                    }
4988                }
4989            }
4990
4991            if (libs != null) {
4992                String[] libsArray = new String[libs.size()];
4993                libs.toArray(libsArray);
4994                return libsArray;
4995            }
4996
4997            return null;
4998        }
4999    }
5000
5001    @Override
5002    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5003        // allow instant applications
5004        synchronized (mPackages) {
5005            return mServicesSystemSharedLibraryPackageName;
5006        }
5007    }
5008
5009    @Override
5010    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5011        // allow instant applications
5012        synchronized (mPackages) {
5013            return mSharedSystemSharedLibraryPackageName;
5014        }
5015    }
5016
5017    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5018        for (int i = userList.length - 1; i >= 0; --i) {
5019            final int userId = userList[i];
5020            // don't add instant app to the list of updates
5021            if (pkgSetting.getInstantApp(userId)) {
5022                continue;
5023            }
5024            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5025            if (changedPackages == null) {
5026                changedPackages = new SparseArray<>();
5027                mChangedPackages.put(userId, changedPackages);
5028            }
5029            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5030            if (sequenceNumbers == null) {
5031                sequenceNumbers = new HashMap<>();
5032                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5033            }
5034            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5035            if (sequenceNumber != null) {
5036                changedPackages.remove(sequenceNumber);
5037            }
5038            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5039            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5040        }
5041        mChangedPackagesSequenceNumber++;
5042    }
5043
5044    @Override
5045    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5047            return null;
5048        }
5049        synchronized (mPackages) {
5050            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5051                return null;
5052            }
5053            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5054            if (changedPackages == null) {
5055                return null;
5056            }
5057            final List<String> packageNames =
5058                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5059            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5060                final String packageName = changedPackages.get(i);
5061                if (packageName != null) {
5062                    packageNames.add(packageName);
5063                }
5064            }
5065            return packageNames.isEmpty()
5066                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5067        }
5068    }
5069
5070    @Override
5071    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5072        // allow instant applications
5073        ArrayList<FeatureInfo> res;
5074        synchronized (mAvailableFeatures) {
5075            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5076            res.addAll(mAvailableFeatures.values());
5077        }
5078        final FeatureInfo fi = new FeatureInfo();
5079        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5080                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5081        res.add(fi);
5082
5083        return new ParceledListSlice<>(res);
5084    }
5085
5086    @Override
5087    public boolean hasSystemFeature(String name, int version) {
5088        // allow instant applications
5089        synchronized (mAvailableFeatures) {
5090            final FeatureInfo feat = mAvailableFeatures.get(name);
5091            if (feat == null) {
5092                return false;
5093            } else {
5094                return feat.version >= version;
5095            }
5096        }
5097    }
5098
5099    @Override
5100    public int checkPermission(String permName, String pkgName, int userId) {
5101        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5102    }
5103
5104    @Override
5105    public int checkUidPermission(String permName, int uid) {
5106        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5107    }
5108
5109    @Override
5110    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5111        if (UserHandle.getCallingUserId() != userId) {
5112            mContext.enforceCallingPermission(
5113                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5114                    "isPermissionRevokedByPolicy for user " + userId);
5115        }
5116
5117        if (checkPermission(permission, packageName, userId)
5118                == PackageManager.PERMISSION_GRANTED) {
5119            return false;
5120        }
5121
5122        final int callingUid = Binder.getCallingUid();
5123        if (getInstantAppPackageName(callingUid) != null) {
5124            if (!isCallerSameApp(packageName, callingUid)) {
5125                return false;
5126            }
5127        } else {
5128            if (isInstantApp(packageName, userId)) {
5129                return false;
5130            }
5131        }
5132
5133        final long identity = Binder.clearCallingIdentity();
5134        try {
5135            final int flags = getPermissionFlags(permission, packageName, userId);
5136            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5137        } finally {
5138            Binder.restoreCallingIdentity(identity);
5139        }
5140    }
5141
5142    @Override
5143    public String getPermissionControllerPackageName() {
5144        synchronized (mPackages) {
5145            return mRequiredInstallerPackage;
5146        }
5147    }
5148
5149    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5150        return mPermissionManager.addDynamicPermission(
5151                info, async, getCallingUid(), new PermissionCallback() {
5152                    @Override
5153                    public void onPermissionChanged() {
5154                        if (!async) {
5155                            mSettings.writeLPr();
5156                        } else {
5157                            scheduleWriteSettingsLocked();
5158                        }
5159                    }
5160                });
5161    }
5162
5163    @Override
5164    public boolean addPermission(PermissionInfo info) {
5165        synchronized (mPackages) {
5166            return addDynamicPermission(info, false);
5167        }
5168    }
5169
5170    @Override
5171    public boolean addPermissionAsync(PermissionInfo info) {
5172        synchronized (mPackages) {
5173            return addDynamicPermission(info, true);
5174        }
5175    }
5176
5177    @Override
5178    public void removePermission(String permName) {
5179        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5180    }
5181
5182    @Override
5183    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5184        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5185                getCallingUid(), userId, mPermissionCallback);
5186    }
5187
5188    @Override
5189    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5190        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5191                getCallingUid(), userId, mPermissionCallback);
5192    }
5193
5194    @Override
5195    public void resetRuntimePermissions() {
5196        mContext.enforceCallingOrSelfPermission(
5197                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5198                "revokeRuntimePermission");
5199
5200        int callingUid = Binder.getCallingUid();
5201        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5202            mContext.enforceCallingOrSelfPermission(
5203                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5204                    "resetRuntimePermissions");
5205        }
5206
5207        synchronized (mPackages) {
5208            mPermissionManager.updateAllPermissions(
5209                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5210                    mPermissionCallback);
5211            for (int userId : UserManagerService.getInstance().getUserIds()) {
5212                final int packageCount = mPackages.size();
5213                for (int i = 0; i < packageCount; i++) {
5214                    PackageParser.Package pkg = mPackages.valueAt(i);
5215                    if (!(pkg.mExtras instanceof PackageSetting)) {
5216                        continue;
5217                    }
5218                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5219                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5220                }
5221            }
5222        }
5223    }
5224
5225    @Override
5226    public int getPermissionFlags(String permName, String packageName, int userId) {
5227        return mPermissionManager.getPermissionFlags(
5228                permName, packageName, getCallingUid(), userId);
5229    }
5230
5231    @Override
5232    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5233            int flagValues, int userId) {
5234        mPermissionManager.updatePermissionFlags(
5235                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5236                mPermissionCallback);
5237    }
5238
5239    /**
5240     * Update the permission flags for all packages and runtime permissions of a user in order
5241     * to allow device or profile owner to remove POLICY_FIXED.
5242     */
5243    @Override
5244    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5245        synchronized (mPackages) {
5246            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5247                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5248                    mPermissionCallback);
5249            if (changed) {
5250                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5251            }
5252        }
5253    }
5254
5255    @Override
5256    public boolean shouldShowRequestPermissionRationale(String permissionName,
5257            String packageName, int userId) {
5258        if (UserHandle.getCallingUserId() != userId) {
5259            mContext.enforceCallingPermission(
5260                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5261                    "canShowRequestPermissionRationale for user " + userId);
5262        }
5263
5264        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5265        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5266            return false;
5267        }
5268
5269        if (checkPermission(permissionName, packageName, userId)
5270                == PackageManager.PERMISSION_GRANTED) {
5271            return false;
5272        }
5273
5274        final int flags;
5275
5276        final long identity = Binder.clearCallingIdentity();
5277        try {
5278            flags = getPermissionFlags(permissionName,
5279                    packageName, userId);
5280        } finally {
5281            Binder.restoreCallingIdentity(identity);
5282        }
5283
5284        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5285                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5286                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5287
5288        if ((flags & fixedFlags) != 0) {
5289            return false;
5290        }
5291
5292        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5293    }
5294
5295    @Override
5296    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5297        mContext.enforceCallingOrSelfPermission(
5298                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5299                "addOnPermissionsChangeListener");
5300
5301        synchronized (mPackages) {
5302            mOnPermissionChangeListeners.addListenerLocked(listener);
5303        }
5304    }
5305
5306    @Override
5307    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5308        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5309            throw new SecurityException("Instant applications don't have access to this method");
5310        }
5311        synchronized (mPackages) {
5312            mOnPermissionChangeListeners.removeListenerLocked(listener);
5313        }
5314    }
5315
5316    @Override
5317    public boolean isProtectedBroadcast(String actionName) {
5318        // allow instant applications
5319        synchronized (mProtectedBroadcasts) {
5320            if (mProtectedBroadcasts.contains(actionName)) {
5321                return true;
5322            } else if (actionName != null) {
5323                // TODO: remove these terrible hacks
5324                if (actionName.startsWith("android.net.netmon.lingerExpired")
5325                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5326                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5327                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5328                    return true;
5329                }
5330            }
5331        }
5332        return false;
5333    }
5334
5335    @Override
5336    public int checkSignatures(String pkg1, String pkg2) {
5337        synchronized (mPackages) {
5338            final PackageParser.Package p1 = mPackages.get(pkg1);
5339            final PackageParser.Package p2 = mPackages.get(pkg2);
5340            if (p1 == null || p1.mExtras == null
5341                    || p2 == null || p2.mExtras == null) {
5342                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5343            }
5344            final int callingUid = Binder.getCallingUid();
5345            final int callingUserId = UserHandle.getUserId(callingUid);
5346            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5347            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5348            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5349                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5350                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5351            }
5352            return compareSignatures(p1.mSignatures, p2.mSignatures);
5353        }
5354    }
5355
5356    @Override
5357    public int checkUidSignatures(int uid1, int uid2) {
5358        final int callingUid = Binder.getCallingUid();
5359        final int callingUserId = UserHandle.getUserId(callingUid);
5360        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5361        // Map to base uids.
5362        uid1 = UserHandle.getAppId(uid1);
5363        uid2 = UserHandle.getAppId(uid2);
5364        // reader
5365        synchronized (mPackages) {
5366            Signature[] s1;
5367            Signature[] s2;
5368            Object obj = mSettings.getUserIdLPr(uid1);
5369            if (obj != null) {
5370                if (obj instanceof SharedUserSetting) {
5371                    if (isCallerInstantApp) {
5372                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5373                    }
5374                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5375                } else if (obj instanceof PackageSetting) {
5376                    final PackageSetting ps = (PackageSetting) obj;
5377                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5378                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5379                    }
5380                    s1 = ps.signatures.mSignatures;
5381                } else {
5382                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5383                }
5384            } else {
5385                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5386            }
5387            obj = mSettings.getUserIdLPr(uid2);
5388            if (obj != null) {
5389                if (obj instanceof SharedUserSetting) {
5390                    if (isCallerInstantApp) {
5391                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5392                    }
5393                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5394                } else if (obj instanceof PackageSetting) {
5395                    final PackageSetting ps = (PackageSetting) obj;
5396                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5397                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5398                    }
5399                    s2 = ps.signatures.mSignatures;
5400                } else {
5401                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5402                }
5403            } else {
5404                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5405            }
5406            return compareSignatures(s1, s2);
5407        }
5408    }
5409
5410    /**
5411     * This method should typically only be used when granting or revoking
5412     * permissions, since the app may immediately restart after this call.
5413     * <p>
5414     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5415     * guard your work against the app being relaunched.
5416     */
5417    private void killUid(int appId, int userId, String reason) {
5418        final long identity = Binder.clearCallingIdentity();
5419        try {
5420            IActivityManager am = ActivityManager.getService();
5421            if (am != null) {
5422                try {
5423                    am.killUid(appId, userId, reason);
5424                } catch (RemoteException e) {
5425                    /* ignore - same process */
5426                }
5427            }
5428        } finally {
5429            Binder.restoreCallingIdentity(identity);
5430        }
5431    }
5432
5433    /**
5434     * If the database version for this type of package (internal storage or
5435     * external storage) is less than the version where package signatures
5436     * were updated, return true.
5437     */
5438    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5439        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5440        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5441    }
5442
5443    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5444        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5445        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5446    }
5447
5448    @Override
5449    public List<String> getAllPackages() {
5450        final int callingUid = Binder.getCallingUid();
5451        final int callingUserId = UserHandle.getUserId(callingUid);
5452        synchronized (mPackages) {
5453            if (canViewInstantApps(callingUid, callingUserId)) {
5454                return new ArrayList<String>(mPackages.keySet());
5455            }
5456            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5457            final List<String> result = new ArrayList<>();
5458            if (instantAppPkgName != null) {
5459                // caller is an instant application; filter unexposed applications
5460                for (PackageParser.Package pkg : mPackages.values()) {
5461                    if (!pkg.visibleToInstantApps) {
5462                        continue;
5463                    }
5464                    result.add(pkg.packageName);
5465                }
5466            } else {
5467                // caller is a normal application; filter instant applications
5468                for (PackageParser.Package pkg : mPackages.values()) {
5469                    final PackageSetting ps =
5470                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5471                    if (ps != null
5472                            && ps.getInstantApp(callingUserId)
5473                            && !mInstantAppRegistry.isInstantAccessGranted(
5474                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5475                        continue;
5476                    }
5477                    result.add(pkg.packageName);
5478                }
5479            }
5480            return result;
5481        }
5482    }
5483
5484    @Override
5485    public String[] getPackagesForUid(int uid) {
5486        final int callingUid = Binder.getCallingUid();
5487        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5488        final int userId = UserHandle.getUserId(uid);
5489        uid = UserHandle.getAppId(uid);
5490        // reader
5491        synchronized (mPackages) {
5492            Object obj = mSettings.getUserIdLPr(uid);
5493            if (obj instanceof SharedUserSetting) {
5494                if (isCallerInstantApp) {
5495                    return null;
5496                }
5497                final SharedUserSetting sus = (SharedUserSetting) obj;
5498                final int N = sus.packages.size();
5499                String[] res = new String[N];
5500                final Iterator<PackageSetting> it = sus.packages.iterator();
5501                int i = 0;
5502                while (it.hasNext()) {
5503                    PackageSetting ps = it.next();
5504                    if (ps.getInstalled(userId)) {
5505                        res[i++] = ps.name;
5506                    } else {
5507                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5508                    }
5509                }
5510                return res;
5511            } else if (obj instanceof PackageSetting) {
5512                final PackageSetting ps = (PackageSetting) obj;
5513                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5514                    return new String[]{ps.name};
5515                }
5516            }
5517        }
5518        return null;
5519    }
5520
5521    @Override
5522    public String getNameForUid(int uid) {
5523        final int callingUid = Binder.getCallingUid();
5524        if (getInstantAppPackageName(callingUid) != null) {
5525            return null;
5526        }
5527        synchronized (mPackages) {
5528            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5529            if (obj instanceof SharedUserSetting) {
5530                final SharedUserSetting sus = (SharedUserSetting) obj;
5531                return sus.name + ":" + sus.userId;
5532            } else if (obj instanceof PackageSetting) {
5533                final PackageSetting ps = (PackageSetting) obj;
5534                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5535                    return null;
5536                }
5537                return ps.name;
5538            }
5539            return null;
5540        }
5541    }
5542
5543    @Override
5544    public String[] getNamesForUids(int[] uids) {
5545        if (uids == null || uids.length == 0) {
5546            return null;
5547        }
5548        final int callingUid = Binder.getCallingUid();
5549        if (getInstantAppPackageName(callingUid) != null) {
5550            return null;
5551        }
5552        final String[] names = new String[uids.length];
5553        synchronized (mPackages) {
5554            for (int i = uids.length - 1; i >= 0; i--) {
5555                final int uid = uids[i];
5556                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5557                if (obj instanceof SharedUserSetting) {
5558                    final SharedUserSetting sus = (SharedUserSetting) obj;
5559                    names[i] = "shared:" + sus.name;
5560                } else if (obj instanceof PackageSetting) {
5561                    final PackageSetting ps = (PackageSetting) obj;
5562                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5563                        names[i] = null;
5564                    } else {
5565                        names[i] = ps.name;
5566                    }
5567                } else {
5568                    names[i] = null;
5569                }
5570            }
5571        }
5572        return names;
5573    }
5574
5575    @Override
5576    public int getUidForSharedUser(String sharedUserName) {
5577        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5578            return -1;
5579        }
5580        if (sharedUserName == null) {
5581            return -1;
5582        }
5583        // reader
5584        synchronized (mPackages) {
5585            SharedUserSetting suid;
5586            try {
5587                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5588                if (suid != null) {
5589                    return suid.userId;
5590                }
5591            } catch (PackageManagerException ignore) {
5592                // can't happen, but, still need to catch it
5593            }
5594            return -1;
5595        }
5596    }
5597
5598    @Override
5599    public int getFlagsForUid(int uid) {
5600        final int callingUid = Binder.getCallingUid();
5601        if (getInstantAppPackageName(callingUid) != null) {
5602            return 0;
5603        }
5604        synchronized (mPackages) {
5605            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5606            if (obj instanceof SharedUserSetting) {
5607                final SharedUserSetting sus = (SharedUserSetting) obj;
5608                return sus.pkgFlags;
5609            } else if (obj instanceof PackageSetting) {
5610                final PackageSetting ps = (PackageSetting) obj;
5611                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5612                    return 0;
5613                }
5614                return ps.pkgFlags;
5615            }
5616        }
5617        return 0;
5618    }
5619
5620    @Override
5621    public int getPrivateFlagsForUid(int uid) {
5622        final int callingUid = Binder.getCallingUid();
5623        if (getInstantAppPackageName(callingUid) != null) {
5624            return 0;
5625        }
5626        synchronized (mPackages) {
5627            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5628            if (obj instanceof SharedUserSetting) {
5629                final SharedUserSetting sus = (SharedUserSetting) obj;
5630                return sus.pkgPrivateFlags;
5631            } else if (obj instanceof PackageSetting) {
5632                final PackageSetting ps = (PackageSetting) obj;
5633                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5634                    return 0;
5635                }
5636                return ps.pkgPrivateFlags;
5637            }
5638        }
5639        return 0;
5640    }
5641
5642    @Override
5643    public boolean isUidPrivileged(int uid) {
5644        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5645            return false;
5646        }
5647        uid = UserHandle.getAppId(uid);
5648        // reader
5649        synchronized (mPackages) {
5650            Object obj = mSettings.getUserIdLPr(uid);
5651            if (obj instanceof SharedUserSetting) {
5652                final SharedUserSetting sus = (SharedUserSetting) obj;
5653                final Iterator<PackageSetting> it = sus.packages.iterator();
5654                while (it.hasNext()) {
5655                    if (it.next().isPrivileged()) {
5656                        return true;
5657                    }
5658                }
5659            } else if (obj instanceof PackageSetting) {
5660                final PackageSetting ps = (PackageSetting) obj;
5661                return ps.isPrivileged();
5662            }
5663        }
5664        return false;
5665    }
5666
5667    @Override
5668    public String[] getAppOpPermissionPackages(String permName) {
5669        return mPermissionManager.getAppOpPermissionPackages(permName);
5670    }
5671
5672    @Override
5673    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5674            int flags, int userId) {
5675        return resolveIntentInternal(
5676                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5677    }
5678
5679    /**
5680     * Normally instant apps can only be resolved when they're visible to the caller.
5681     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5682     * since we need to allow the system to start any installed application.
5683     */
5684    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5685            int flags, int userId, boolean resolveForStart) {
5686        try {
5687            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5688
5689            if (!sUserManager.exists(userId)) return null;
5690            final int callingUid = Binder.getCallingUid();
5691            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5692            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5693                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5694
5695            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5696            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5697                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5698            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5699
5700            final ResolveInfo bestChoice =
5701                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5702            return bestChoice;
5703        } finally {
5704            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5705        }
5706    }
5707
5708    @Override
5709    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5710        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5711            throw new SecurityException(
5712                    "findPersistentPreferredActivity can only be run by the system");
5713        }
5714        if (!sUserManager.exists(userId)) {
5715            return null;
5716        }
5717        final int callingUid = Binder.getCallingUid();
5718        intent = updateIntentForResolve(intent);
5719        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5720        final int flags = updateFlagsForResolve(
5721                0, userId, intent, callingUid, false /*includeInstantApps*/);
5722        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5723                userId);
5724        synchronized (mPackages) {
5725            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5726                    userId);
5727        }
5728    }
5729
5730    @Override
5731    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5732            IntentFilter filter, int match, ComponentName activity) {
5733        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5734            return;
5735        }
5736        final int userId = UserHandle.getCallingUserId();
5737        if (DEBUG_PREFERRED) {
5738            Log.v(TAG, "setLastChosenActivity intent=" + intent
5739                + " resolvedType=" + resolvedType
5740                + " flags=" + flags
5741                + " filter=" + filter
5742                + " match=" + match
5743                + " activity=" + activity);
5744            filter.dump(new PrintStreamPrinter(System.out), "    ");
5745        }
5746        intent.setComponent(null);
5747        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5748                userId);
5749        // Find any earlier preferred or last chosen entries and nuke them
5750        findPreferredActivity(intent, resolvedType,
5751                flags, query, 0, false, true, false, userId);
5752        // Add the new activity as the last chosen for this filter
5753        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5754                "Setting last chosen");
5755    }
5756
5757    @Override
5758    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5759        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5760            return null;
5761        }
5762        final int userId = UserHandle.getCallingUserId();
5763        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5764        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5765                userId);
5766        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5767                false, false, false, userId);
5768    }
5769
5770    /**
5771     * Returns whether or not instant apps have been disabled remotely.
5772     */
5773    private boolean isEphemeralDisabled() {
5774        return mEphemeralAppsDisabled;
5775    }
5776
5777    private boolean isInstantAppAllowed(
5778            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5779            boolean skipPackageCheck) {
5780        if (mInstantAppResolverConnection == null) {
5781            return false;
5782        }
5783        if (mInstantAppInstallerActivity == null) {
5784            return false;
5785        }
5786        if (intent.getComponent() != null) {
5787            return false;
5788        }
5789        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5790            return false;
5791        }
5792        if (!skipPackageCheck && intent.getPackage() != null) {
5793            return false;
5794        }
5795        final boolean isWebUri = hasWebURI(intent);
5796        if (!isWebUri || intent.getData().getHost() == null) {
5797            return false;
5798        }
5799        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5800        // Or if there's already an ephemeral app installed that handles the action
5801        synchronized (mPackages) {
5802            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5803            for (int n = 0; n < count; n++) {
5804                final ResolveInfo info = resolvedActivities.get(n);
5805                final String packageName = info.activityInfo.packageName;
5806                final PackageSetting ps = mSettings.mPackages.get(packageName);
5807                if (ps != null) {
5808                    // only check domain verification status if the app is not a browser
5809                    if (!info.handleAllWebDataURI) {
5810                        // Try to get the status from User settings first
5811                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5812                        final int status = (int) (packedStatus >> 32);
5813                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5814                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5815                            if (DEBUG_EPHEMERAL) {
5816                                Slog.v(TAG, "DENY instant app;"
5817                                    + " pkg: " + packageName + ", status: " + status);
5818                            }
5819                            return false;
5820                        }
5821                    }
5822                    if (ps.getInstantApp(userId)) {
5823                        if (DEBUG_EPHEMERAL) {
5824                            Slog.v(TAG, "DENY instant app installed;"
5825                                    + " pkg: " + packageName);
5826                        }
5827                        return false;
5828                    }
5829                }
5830            }
5831        }
5832        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5833        return true;
5834    }
5835
5836    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5837            Intent origIntent, String resolvedType, String callingPackage,
5838            Bundle verificationBundle, int userId) {
5839        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5840                new InstantAppRequest(responseObj, origIntent, resolvedType,
5841                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5842        mHandler.sendMessage(msg);
5843    }
5844
5845    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5846            int flags, List<ResolveInfo> query, int userId) {
5847        if (query != null) {
5848            final int N = query.size();
5849            if (N == 1) {
5850                return query.get(0);
5851            } else if (N > 1) {
5852                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5853                // If there is more than one activity with the same priority,
5854                // then let the user decide between them.
5855                ResolveInfo r0 = query.get(0);
5856                ResolveInfo r1 = query.get(1);
5857                if (DEBUG_INTENT_MATCHING || debug) {
5858                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5859                            + r1.activityInfo.name + "=" + r1.priority);
5860                }
5861                // If the first activity has a higher priority, or a different
5862                // default, then it is always desirable to pick it.
5863                if (r0.priority != r1.priority
5864                        || r0.preferredOrder != r1.preferredOrder
5865                        || r0.isDefault != r1.isDefault) {
5866                    return query.get(0);
5867                }
5868                // If we have saved a preference for a preferred activity for
5869                // this Intent, use that.
5870                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5871                        flags, query, r0.priority, true, false, debug, userId);
5872                if (ri != null) {
5873                    return ri;
5874                }
5875                // If we have an ephemeral app, use it
5876                for (int i = 0; i < N; i++) {
5877                    ri = query.get(i);
5878                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5879                        final String packageName = ri.activityInfo.packageName;
5880                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5881                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5882                        final int status = (int)(packedStatus >> 32);
5883                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5884                            return ri;
5885                        }
5886                    }
5887                }
5888                ri = new ResolveInfo(mResolveInfo);
5889                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5890                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5891                // If all of the options come from the same package, show the application's
5892                // label and icon instead of the generic resolver's.
5893                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5894                // and then throw away the ResolveInfo itself, meaning that the caller loses
5895                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5896                // a fallback for this case; we only set the target package's resources on
5897                // the ResolveInfo, not the ActivityInfo.
5898                final String intentPackage = intent.getPackage();
5899                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5900                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5901                    ri.resolvePackageName = intentPackage;
5902                    if (userNeedsBadging(userId)) {
5903                        ri.noResourceId = true;
5904                    } else {
5905                        ri.icon = appi.icon;
5906                    }
5907                    ri.iconResourceId = appi.icon;
5908                    ri.labelRes = appi.labelRes;
5909                }
5910                ri.activityInfo.applicationInfo = new ApplicationInfo(
5911                        ri.activityInfo.applicationInfo);
5912                if (userId != 0) {
5913                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5914                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5915                }
5916                // Make sure that the resolver is displayable in car mode
5917                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5918                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5919                return ri;
5920            }
5921        }
5922        return null;
5923    }
5924
5925    /**
5926     * Return true if the given list is not empty and all of its contents have
5927     * an activityInfo with the given package name.
5928     */
5929    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5930        if (ArrayUtils.isEmpty(list)) {
5931            return false;
5932        }
5933        for (int i = 0, N = list.size(); i < N; i++) {
5934            final ResolveInfo ri = list.get(i);
5935            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5936            if (ai == null || !packageName.equals(ai.packageName)) {
5937                return false;
5938            }
5939        }
5940        return true;
5941    }
5942
5943    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5944            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5945        final int N = query.size();
5946        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5947                .get(userId);
5948        // Get the list of persistent preferred activities that handle the intent
5949        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5950        List<PersistentPreferredActivity> pprefs = ppir != null
5951                ? ppir.queryIntent(intent, resolvedType,
5952                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5953                        userId)
5954                : null;
5955        if (pprefs != null && pprefs.size() > 0) {
5956            final int M = pprefs.size();
5957            for (int i=0; i<M; i++) {
5958                final PersistentPreferredActivity ppa = pprefs.get(i);
5959                if (DEBUG_PREFERRED || debug) {
5960                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5961                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5962                            + "\n  component=" + ppa.mComponent);
5963                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5964                }
5965                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5966                        flags | MATCH_DISABLED_COMPONENTS, userId);
5967                if (DEBUG_PREFERRED || debug) {
5968                    Slog.v(TAG, "Found persistent preferred activity:");
5969                    if (ai != null) {
5970                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5971                    } else {
5972                        Slog.v(TAG, "  null");
5973                    }
5974                }
5975                if (ai == null) {
5976                    // This previously registered persistent preferred activity
5977                    // component is no longer known. Ignore it and do NOT remove it.
5978                    continue;
5979                }
5980                for (int j=0; j<N; j++) {
5981                    final ResolveInfo ri = query.get(j);
5982                    if (!ri.activityInfo.applicationInfo.packageName
5983                            .equals(ai.applicationInfo.packageName)) {
5984                        continue;
5985                    }
5986                    if (!ri.activityInfo.name.equals(ai.name)) {
5987                        continue;
5988                    }
5989                    //  Found a persistent preference that can handle the intent.
5990                    if (DEBUG_PREFERRED || debug) {
5991                        Slog.v(TAG, "Returning persistent preferred activity: " +
5992                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5993                    }
5994                    return ri;
5995                }
5996            }
5997        }
5998        return null;
5999    }
6000
6001    // TODO: handle preferred activities missing while user has amnesia
6002    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6003            List<ResolveInfo> query, int priority, boolean always,
6004            boolean removeMatches, boolean debug, int userId) {
6005        if (!sUserManager.exists(userId)) return null;
6006        final int callingUid = Binder.getCallingUid();
6007        flags = updateFlagsForResolve(
6008                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6009        intent = updateIntentForResolve(intent);
6010        // writer
6011        synchronized (mPackages) {
6012            // Try to find a matching persistent preferred activity.
6013            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6014                    debug, userId);
6015
6016            // If a persistent preferred activity matched, use it.
6017            if (pri != null) {
6018                return pri;
6019            }
6020
6021            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6022            // Get the list of preferred activities that handle the intent
6023            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6024            List<PreferredActivity> prefs = pir != null
6025                    ? pir.queryIntent(intent, resolvedType,
6026                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6027                            userId)
6028                    : null;
6029            if (prefs != null && prefs.size() > 0) {
6030                boolean changed = false;
6031                try {
6032                    // First figure out how good the original match set is.
6033                    // We will only allow preferred activities that came
6034                    // from the same match quality.
6035                    int match = 0;
6036
6037                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6038
6039                    final int N = query.size();
6040                    for (int j=0; j<N; j++) {
6041                        final ResolveInfo ri = query.get(j);
6042                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6043                                + ": 0x" + Integer.toHexString(match));
6044                        if (ri.match > match) {
6045                            match = ri.match;
6046                        }
6047                    }
6048
6049                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6050                            + Integer.toHexString(match));
6051
6052                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6053                    final int M = prefs.size();
6054                    for (int i=0; i<M; i++) {
6055                        final PreferredActivity pa = prefs.get(i);
6056                        if (DEBUG_PREFERRED || debug) {
6057                            Slog.v(TAG, "Checking PreferredActivity ds="
6058                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6059                                    + "\n  component=" + pa.mPref.mComponent);
6060                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6061                        }
6062                        if (pa.mPref.mMatch != match) {
6063                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6064                                    + Integer.toHexString(pa.mPref.mMatch));
6065                            continue;
6066                        }
6067                        // If it's not an "always" type preferred activity and that's what we're
6068                        // looking for, skip it.
6069                        if (always && !pa.mPref.mAlways) {
6070                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6071                            continue;
6072                        }
6073                        final ActivityInfo ai = getActivityInfo(
6074                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6075                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6076                                userId);
6077                        if (DEBUG_PREFERRED || debug) {
6078                            Slog.v(TAG, "Found preferred activity:");
6079                            if (ai != null) {
6080                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6081                            } else {
6082                                Slog.v(TAG, "  null");
6083                            }
6084                        }
6085                        if (ai == null) {
6086                            // This previously registered preferred activity
6087                            // component is no longer known.  Most likely an update
6088                            // to the app was installed and in the new version this
6089                            // component no longer exists.  Clean it up by removing
6090                            // it from the preferred activities list, and skip it.
6091                            Slog.w(TAG, "Removing dangling preferred activity: "
6092                                    + pa.mPref.mComponent);
6093                            pir.removeFilter(pa);
6094                            changed = true;
6095                            continue;
6096                        }
6097                        for (int j=0; j<N; j++) {
6098                            final ResolveInfo ri = query.get(j);
6099                            if (!ri.activityInfo.applicationInfo.packageName
6100                                    .equals(ai.applicationInfo.packageName)) {
6101                                continue;
6102                            }
6103                            if (!ri.activityInfo.name.equals(ai.name)) {
6104                                continue;
6105                            }
6106
6107                            if (removeMatches) {
6108                                pir.removeFilter(pa);
6109                                changed = true;
6110                                if (DEBUG_PREFERRED) {
6111                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6112                                }
6113                                break;
6114                            }
6115
6116                            // Okay we found a previously set preferred or last chosen app.
6117                            // If the result set is different from when this
6118                            // was created, and is not a subset of the preferred set, we need to
6119                            // clear it and re-ask the user their preference, if we're looking for
6120                            // an "always" type entry.
6121                            if (always && !pa.mPref.sameSet(query)) {
6122                                if (pa.mPref.isSuperset(query)) {
6123                                    // some components of the set are no longer present in
6124                                    // the query, but the preferred activity can still be reused
6125                                    if (DEBUG_PREFERRED) {
6126                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6127                                                + " still valid as only non-preferred components"
6128                                                + " were removed for " + intent + " type "
6129                                                + resolvedType);
6130                                    }
6131                                    // remove obsolete components and re-add the up-to-date filter
6132                                    PreferredActivity freshPa = new PreferredActivity(pa,
6133                                            pa.mPref.mMatch,
6134                                            pa.mPref.discardObsoleteComponents(query),
6135                                            pa.mPref.mComponent,
6136                                            pa.mPref.mAlways);
6137                                    pir.removeFilter(pa);
6138                                    pir.addFilter(freshPa);
6139                                    changed = true;
6140                                } else {
6141                                    Slog.i(TAG,
6142                                            "Result set changed, dropping preferred activity for "
6143                                                    + intent + " type " + resolvedType);
6144                                    if (DEBUG_PREFERRED) {
6145                                        Slog.v(TAG, "Removing preferred activity since set changed "
6146                                                + pa.mPref.mComponent);
6147                                    }
6148                                    pir.removeFilter(pa);
6149                                    // Re-add the filter as a "last chosen" entry (!always)
6150                                    PreferredActivity lastChosen = new PreferredActivity(
6151                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6152                                    pir.addFilter(lastChosen);
6153                                    changed = true;
6154                                    return null;
6155                                }
6156                            }
6157
6158                            // Yay! Either the set matched or we're looking for the last chosen
6159                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6160                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6161                            return ri;
6162                        }
6163                    }
6164                } finally {
6165                    if (changed) {
6166                        if (DEBUG_PREFERRED) {
6167                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6168                        }
6169                        scheduleWritePackageRestrictionsLocked(userId);
6170                    }
6171                }
6172            }
6173        }
6174        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6175        return null;
6176    }
6177
6178    /*
6179     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6180     */
6181    @Override
6182    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6183            int targetUserId) {
6184        mContext.enforceCallingOrSelfPermission(
6185                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6186        List<CrossProfileIntentFilter> matches =
6187                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6188        if (matches != null) {
6189            int size = matches.size();
6190            for (int i = 0; i < size; i++) {
6191                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6192            }
6193        }
6194        if (hasWebURI(intent)) {
6195            // cross-profile app linking works only towards the parent.
6196            final int callingUid = Binder.getCallingUid();
6197            final UserInfo parent = getProfileParent(sourceUserId);
6198            synchronized(mPackages) {
6199                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6200                        false /*includeInstantApps*/);
6201                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6202                        intent, resolvedType, flags, sourceUserId, parent.id);
6203                return xpDomainInfo != null;
6204            }
6205        }
6206        return false;
6207    }
6208
6209    private UserInfo getProfileParent(int userId) {
6210        final long identity = Binder.clearCallingIdentity();
6211        try {
6212            return sUserManager.getProfileParent(userId);
6213        } finally {
6214            Binder.restoreCallingIdentity(identity);
6215        }
6216    }
6217
6218    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6219            String resolvedType, int userId) {
6220        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6221        if (resolver != null) {
6222            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6223        }
6224        return null;
6225    }
6226
6227    @Override
6228    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6229            String resolvedType, int flags, int userId) {
6230        try {
6231            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6232
6233            return new ParceledListSlice<>(
6234                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6235        } finally {
6236            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6237        }
6238    }
6239
6240    /**
6241     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6242     * instant, returns {@code null}.
6243     */
6244    private String getInstantAppPackageName(int callingUid) {
6245        synchronized (mPackages) {
6246            // If the caller is an isolated app use the owner's uid for the lookup.
6247            if (Process.isIsolated(callingUid)) {
6248                callingUid = mIsolatedOwners.get(callingUid);
6249            }
6250            final int appId = UserHandle.getAppId(callingUid);
6251            final Object obj = mSettings.getUserIdLPr(appId);
6252            if (obj instanceof PackageSetting) {
6253                final PackageSetting ps = (PackageSetting) obj;
6254                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6255                return isInstantApp ? ps.pkg.packageName : null;
6256            }
6257        }
6258        return null;
6259    }
6260
6261    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6262            String resolvedType, int flags, int userId) {
6263        return queryIntentActivitiesInternal(
6264                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6265                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6266    }
6267
6268    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6269            String resolvedType, int flags, int filterCallingUid, int userId,
6270            boolean resolveForStart, boolean allowDynamicSplits) {
6271        if (!sUserManager.exists(userId)) return Collections.emptyList();
6272        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6273        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6274                false /* requireFullPermission */, false /* checkShell */,
6275                "query intent activities");
6276        final String pkgName = intent.getPackage();
6277        ComponentName comp = intent.getComponent();
6278        if (comp == null) {
6279            if (intent.getSelector() != null) {
6280                intent = intent.getSelector();
6281                comp = intent.getComponent();
6282            }
6283        }
6284
6285        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6286                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6287        if (comp != null) {
6288            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6289            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6290            if (ai != null) {
6291                // When specifying an explicit component, we prevent the activity from being
6292                // used when either 1) the calling package is normal and the activity is within
6293                // an ephemeral application or 2) the calling package is ephemeral and the
6294                // activity is not visible to ephemeral applications.
6295                final boolean matchInstantApp =
6296                        (flags & PackageManager.MATCH_INSTANT) != 0;
6297                final boolean matchVisibleToInstantAppOnly =
6298                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6299                final boolean matchExplicitlyVisibleOnly =
6300                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6301                final boolean isCallerInstantApp =
6302                        instantAppPkgName != null;
6303                final boolean isTargetSameInstantApp =
6304                        comp.getPackageName().equals(instantAppPkgName);
6305                final boolean isTargetInstantApp =
6306                        (ai.applicationInfo.privateFlags
6307                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6308                final boolean isTargetVisibleToInstantApp =
6309                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6310                final boolean isTargetExplicitlyVisibleToInstantApp =
6311                        isTargetVisibleToInstantApp
6312                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6313                final boolean isTargetHiddenFromInstantApp =
6314                        !isTargetVisibleToInstantApp
6315                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6316                final boolean blockResolution =
6317                        !isTargetSameInstantApp
6318                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6319                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6320                                        && isTargetHiddenFromInstantApp));
6321                if (!blockResolution) {
6322                    final ResolveInfo ri = new ResolveInfo();
6323                    ri.activityInfo = ai;
6324                    list.add(ri);
6325                }
6326            }
6327            return applyPostResolutionFilter(
6328                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6329        }
6330
6331        // reader
6332        boolean sortResult = false;
6333        boolean addEphemeral = false;
6334        List<ResolveInfo> result;
6335        final boolean ephemeralDisabled = isEphemeralDisabled();
6336        synchronized (mPackages) {
6337            if (pkgName == null) {
6338                List<CrossProfileIntentFilter> matchingFilters =
6339                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6340                // Check for results that need to skip the current profile.
6341                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6342                        resolvedType, flags, userId);
6343                if (xpResolveInfo != null) {
6344                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6345                    xpResult.add(xpResolveInfo);
6346                    return applyPostResolutionFilter(
6347                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6348                            allowDynamicSplits, filterCallingUid, userId);
6349                }
6350
6351                // Check for results in the current profile.
6352                result = filterIfNotSystemUser(mActivities.queryIntent(
6353                        intent, resolvedType, flags, userId), userId);
6354                addEphemeral = !ephemeralDisabled
6355                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6356                // Check for cross profile results.
6357                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6358                xpResolveInfo = queryCrossProfileIntents(
6359                        matchingFilters, intent, resolvedType, flags, userId,
6360                        hasNonNegativePriorityResult);
6361                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6362                    boolean isVisibleToUser = filterIfNotSystemUser(
6363                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6364                    if (isVisibleToUser) {
6365                        result.add(xpResolveInfo);
6366                        sortResult = true;
6367                    }
6368                }
6369                if (hasWebURI(intent)) {
6370                    CrossProfileDomainInfo xpDomainInfo = null;
6371                    final UserInfo parent = getProfileParent(userId);
6372                    if (parent != null) {
6373                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6374                                flags, userId, parent.id);
6375                    }
6376                    if (xpDomainInfo != null) {
6377                        if (xpResolveInfo != null) {
6378                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6379                            // in the result.
6380                            result.remove(xpResolveInfo);
6381                        }
6382                        if (result.size() == 0 && !addEphemeral) {
6383                            // No result in current profile, but found candidate in parent user.
6384                            // And we are not going to add emphemeral app, so we can return the
6385                            // result straight away.
6386                            result.add(xpDomainInfo.resolveInfo);
6387                            return applyPostResolutionFilter(result, instantAppPkgName,
6388                                    allowDynamicSplits, filterCallingUid, userId);
6389                        }
6390                    } else if (result.size() <= 1 && !addEphemeral) {
6391                        // No result in parent user and <= 1 result in current profile, and we
6392                        // are not going to add emphemeral app, so we can return the result without
6393                        // further processing.
6394                        return applyPostResolutionFilter(result, instantAppPkgName,
6395                                allowDynamicSplits, filterCallingUid, userId);
6396                    }
6397                    // We have more than one candidate (combining results from current and parent
6398                    // profile), so we need filtering and sorting.
6399                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6400                            intent, flags, result, xpDomainInfo, userId);
6401                    sortResult = true;
6402                }
6403            } else {
6404                final PackageParser.Package pkg = mPackages.get(pkgName);
6405                result = null;
6406                if (pkg != null) {
6407                    result = filterIfNotSystemUser(
6408                            mActivities.queryIntentForPackage(
6409                                    intent, resolvedType, flags, pkg.activities, userId),
6410                            userId);
6411                }
6412                if (result == null || result.size() == 0) {
6413                    // the caller wants to resolve for a particular package; however, there
6414                    // were no installed results, so, try to find an ephemeral result
6415                    addEphemeral = !ephemeralDisabled
6416                            && isInstantAppAllowed(
6417                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6418                    if (result == null) {
6419                        result = new ArrayList<>();
6420                    }
6421                }
6422            }
6423        }
6424        if (addEphemeral) {
6425            result = maybeAddInstantAppInstaller(
6426                    result, intent, resolvedType, flags, userId, resolveForStart);
6427        }
6428        if (sortResult) {
6429            Collections.sort(result, mResolvePrioritySorter);
6430        }
6431        return applyPostResolutionFilter(
6432                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6433    }
6434
6435    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6436            String resolvedType, int flags, int userId, boolean resolveForStart) {
6437        // first, check to see if we've got an instant app already installed
6438        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6439        ResolveInfo localInstantApp = null;
6440        boolean blockResolution = false;
6441        if (!alreadyResolvedLocally) {
6442            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6443                    flags
6444                        | PackageManager.GET_RESOLVED_FILTER
6445                        | PackageManager.MATCH_INSTANT
6446                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6447                    userId);
6448            for (int i = instantApps.size() - 1; i >= 0; --i) {
6449                final ResolveInfo info = instantApps.get(i);
6450                final String packageName = info.activityInfo.packageName;
6451                final PackageSetting ps = mSettings.mPackages.get(packageName);
6452                if (ps.getInstantApp(userId)) {
6453                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6454                    final int status = (int)(packedStatus >> 32);
6455                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6456                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6457                        // there's a local instant application installed, but, the user has
6458                        // chosen to never use it; skip resolution and don't acknowledge
6459                        // an instant application is even available
6460                        if (DEBUG_EPHEMERAL) {
6461                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6462                        }
6463                        blockResolution = true;
6464                        break;
6465                    } else {
6466                        // we have a locally installed instant application; skip resolution
6467                        // but acknowledge there's an instant application available
6468                        if (DEBUG_EPHEMERAL) {
6469                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6470                        }
6471                        localInstantApp = info;
6472                        break;
6473                    }
6474                }
6475            }
6476        }
6477        // no app installed, let's see if one's available
6478        AuxiliaryResolveInfo auxiliaryResponse = null;
6479        if (!blockResolution) {
6480            if (localInstantApp == null) {
6481                // we don't have an instant app locally, resolve externally
6482                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6483                final InstantAppRequest requestObject = new InstantAppRequest(
6484                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6485                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6486                        resolveForStart);
6487                auxiliaryResponse =
6488                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6489                                mContext, mInstantAppResolverConnection, requestObject);
6490                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6491            } else {
6492                // we have an instant application locally, but, we can't admit that since
6493                // callers shouldn't be able to determine prior browsing. create a dummy
6494                // auxiliary response so the downstream code behaves as if there's an
6495                // instant application available externally. when it comes time to start
6496                // the instant application, we'll do the right thing.
6497                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6498                auxiliaryResponse = new AuxiliaryResolveInfo(
6499                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6500                        ai.versionCode, null /*failureIntent*/);
6501            }
6502        }
6503        if (auxiliaryResponse != null) {
6504            if (DEBUG_EPHEMERAL) {
6505                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6506            }
6507            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6508            final PackageSetting ps =
6509                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6510            if (ps != null) {
6511                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6512                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6513                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6514                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6515                // make sure this resolver is the default
6516                ephemeralInstaller.isDefault = true;
6517                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6518                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6519                // add a non-generic filter
6520                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6521                ephemeralInstaller.filter.addDataPath(
6522                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6523                ephemeralInstaller.isInstantAppAvailable = true;
6524                result.add(ephemeralInstaller);
6525            }
6526        }
6527        return result;
6528    }
6529
6530    private static class CrossProfileDomainInfo {
6531        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6532        ResolveInfo resolveInfo;
6533        /* Best domain verification status of the activities found in the other profile */
6534        int bestDomainVerificationStatus;
6535    }
6536
6537    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6538            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6539        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6540                sourceUserId)) {
6541            return null;
6542        }
6543        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6544                resolvedType, flags, parentUserId);
6545
6546        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6547            return null;
6548        }
6549        CrossProfileDomainInfo result = null;
6550        int size = resultTargetUser.size();
6551        for (int i = 0; i < size; i++) {
6552            ResolveInfo riTargetUser = resultTargetUser.get(i);
6553            // Intent filter verification is only for filters that specify a host. So don't return
6554            // those that handle all web uris.
6555            if (riTargetUser.handleAllWebDataURI) {
6556                continue;
6557            }
6558            String packageName = riTargetUser.activityInfo.packageName;
6559            PackageSetting ps = mSettings.mPackages.get(packageName);
6560            if (ps == null) {
6561                continue;
6562            }
6563            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6564            int status = (int)(verificationState >> 32);
6565            if (result == null) {
6566                result = new CrossProfileDomainInfo();
6567                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6568                        sourceUserId, parentUserId);
6569                result.bestDomainVerificationStatus = status;
6570            } else {
6571                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6572                        result.bestDomainVerificationStatus);
6573            }
6574        }
6575        // Don't consider matches with status NEVER across profiles.
6576        if (result != null && result.bestDomainVerificationStatus
6577                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6578            return null;
6579        }
6580        return result;
6581    }
6582
6583    /**
6584     * Verification statuses are ordered from the worse to the best, except for
6585     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6586     */
6587    private int bestDomainVerificationStatus(int status1, int status2) {
6588        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6589            return status2;
6590        }
6591        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6592            return status1;
6593        }
6594        return (int) MathUtils.max(status1, status2);
6595    }
6596
6597    private boolean isUserEnabled(int userId) {
6598        long callingId = Binder.clearCallingIdentity();
6599        try {
6600            UserInfo userInfo = sUserManager.getUserInfo(userId);
6601            return userInfo != null && userInfo.isEnabled();
6602        } finally {
6603            Binder.restoreCallingIdentity(callingId);
6604        }
6605    }
6606
6607    /**
6608     * Filter out activities with systemUserOnly flag set, when current user is not System.
6609     *
6610     * @return filtered list
6611     */
6612    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6613        if (userId == UserHandle.USER_SYSTEM) {
6614            return resolveInfos;
6615        }
6616        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6617            ResolveInfo info = resolveInfos.get(i);
6618            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6619                resolveInfos.remove(i);
6620            }
6621        }
6622        return resolveInfos;
6623    }
6624
6625    /**
6626     * Filters out ephemeral activities.
6627     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6628     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6629     *
6630     * @param resolveInfos The pre-filtered list of resolved activities
6631     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6632     *          is performed.
6633     * @return A filtered list of resolved activities.
6634     */
6635    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6636            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6637        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6638            final ResolveInfo info = resolveInfos.get(i);
6639            // allow activities that are defined in the provided package
6640            if (allowDynamicSplits
6641                    && info.activityInfo.splitName != null
6642                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6643                            info.activityInfo.splitName)) {
6644                if (mInstantAppInstallerInfo == null) {
6645                    if (DEBUG_INSTALL) {
6646                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6647                    }
6648                    resolveInfos.remove(i);
6649                    continue;
6650                }
6651                // requested activity is defined in a split that hasn't been installed yet.
6652                // add the installer to the resolve list
6653                if (DEBUG_INSTALL) {
6654                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6655                }
6656                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6657                final ComponentName installFailureActivity = findInstallFailureActivity(
6658                        info.activityInfo.packageName,  filterCallingUid, userId);
6659                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6660                        info.activityInfo.packageName, info.activityInfo.splitName,
6661                        installFailureActivity,
6662                        info.activityInfo.applicationInfo.versionCode,
6663                        null /*failureIntent*/);
6664                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6665                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6666                // add a non-generic filter
6667                installerInfo.filter = new IntentFilter();
6668
6669                // This resolve info may appear in the chooser UI, so let us make it
6670                // look as the one it replaces as far as the user is concerned which
6671                // requires loading the correct label and icon for the resolve info.
6672                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6673                installerInfo.labelRes = info.resolveLabelResId();
6674                installerInfo.icon = info.resolveIconResId();
6675
6676                // propagate priority/preferred order/default
6677                installerInfo.priority = info.priority;
6678                installerInfo.preferredOrder = info.preferredOrder;
6679                installerInfo.isDefault = info.isDefault;
6680                resolveInfos.set(i, installerInfo);
6681                continue;
6682            }
6683            // caller is a full app, don't need to apply any other filtering
6684            if (ephemeralPkgName == null) {
6685                continue;
6686            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6687                // caller is same app; don't need to apply any other filtering
6688                continue;
6689            }
6690            // allow activities that have been explicitly exposed to ephemeral apps
6691            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6692            if (!isEphemeralApp
6693                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6694                continue;
6695            }
6696            resolveInfos.remove(i);
6697        }
6698        return resolveInfos;
6699    }
6700
6701    /**
6702     * Returns the activity component that can handle install failures.
6703     * <p>By default, the instant application installer handles failures. However, an
6704     * application may want to handle failures on its own. Applications do this by
6705     * creating an activity with an intent filter that handles the action
6706     * {@link Intent#ACTION_INSTALL_FAILURE}.
6707     */
6708    private @Nullable ComponentName findInstallFailureActivity(
6709            String packageName, int filterCallingUid, int userId) {
6710        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6711        failureActivityIntent.setPackage(packageName);
6712        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6713        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6714                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6715                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6716        final int NR = result.size();
6717        if (NR > 0) {
6718            for (int i = 0; i < NR; i++) {
6719                final ResolveInfo info = result.get(i);
6720                if (info.activityInfo.splitName != null) {
6721                    continue;
6722                }
6723                return new ComponentName(packageName, info.activityInfo.name);
6724            }
6725        }
6726        return null;
6727    }
6728
6729    /**
6730     * @param resolveInfos list of resolve infos in descending priority order
6731     * @return if the list contains a resolve info with non-negative priority
6732     */
6733    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6734        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6735    }
6736
6737    private static boolean hasWebURI(Intent intent) {
6738        if (intent.getData() == null) {
6739            return false;
6740        }
6741        final String scheme = intent.getScheme();
6742        if (TextUtils.isEmpty(scheme)) {
6743            return false;
6744        }
6745        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6746    }
6747
6748    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6749            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6750            int userId) {
6751        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6752
6753        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6754            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6755                    candidates.size());
6756        }
6757
6758        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6759        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6760        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6761        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6762        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6763        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6764
6765        synchronized (mPackages) {
6766            final int count = candidates.size();
6767            // First, try to use linked apps. Partition the candidates into four lists:
6768            // one for the final results, one for the "do not use ever", one for "undefined status"
6769            // and finally one for "browser app type".
6770            for (int n=0; n<count; n++) {
6771                ResolveInfo info = candidates.get(n);
6772                String packageName = info.activityInfo.packageName;
6773                PackageSetting ps = mSettings.mPackages.get(packageName);
6774                if (ps != null) {
6775                    // Add to the special match all list (Browser use case)
6776                    if (info.handleAllWebDataURI) {
6777                        matchAllList.add(info);
6778                        continue;
6779                    }
6780                    // Try to get the status from User settings first
6781                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6782                    int status = (int)(packedStatus >> 32);
6783                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6784                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6785                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6786                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6787                                    + " : linkgen=" + linkGeneration);
6788                        }
6789                        // Use link-enabled generation as preferredOrder, i.e.
6790                        // prefer newly-enabled over earlier-enabled.
6791                        info.preferredOrder = linkGeneration;
6792                        alwaysList.add(info);
6793                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6794                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6795                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6796                        }
6797                        neverList.add(info);
6798                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6799                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6800                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6801                        }
6802                        alwaysAskList.add(info);
6803                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6804                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6805                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6806                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6807                        }
6808                        undefinedList.add(info);
6809                    }
6810                }
6811            }
6812
6813            // We'll want to include browser possibilities in a few cases
6814            boolean includeBrowser = false;
6815
6816            // First try to add the "always" resolution(s) for the current user, if any
6817            if (alwaysList.size() > 0) {
6818                result.addAll(alwaysList);
6819            } else {
6820                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6821                result.addAll(undefinedList);
6822                // Maybe add one for the other profile.
6823                if (xpDomainInfo != null && (
6824                        xpDomainInfo.bestDomainVerificationStatus
6825                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6826                    result.add(xpDomainInfo.resolveInfo);
6827                }
6828                includeBrowser = true;
6829            }
6830
6831            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6832            // If there were 'always' entries their preferred order has been set, so we also
6833            // back that off to make the alternatives equivalent
6834            if (alwaysAskList.size() > 0) {
6835                for (ResolveInfo i : result) {
6836                    i.preferredOrder = 0;
6837                }
6838                result.addAll(alwaysAskList);
6839                includeBrowser = true;
6840            }
6841
6842            if (includeBrowser) {
6843                // Also add browsers (all of them or only the default one)
6844                if (DEBUG_DOMAIN_VERIFICATION) {
6845                    Slog.v(TAG, "   ...including browsers in candidate set");
6846                }
6847                if ((matchFlags & MATCH_ALL) != 0) {
6848                    result.addAll(matchAllList);
6849                } else {
6850                    // Browser/generic handling case.  If there's a default browser, go straight
6851                    // to that (but only if there is no other higher-priority match).
6852                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6853                    int maxMatchPrio = 0;
6854                    ResolveInfo defaultBrowserMatch = null;
6855                    final int numCandidates = matchAllList.size();
6856                    for (int n = 0; n < numCandidates; n++) {
6857                        ResolveInfo info = matchAllList.get(n);
6858                        // track the highest overall match priority...
6859                        if (info.priority > maxMatchPrio) {
6860                            maxMatchPrio = info.priority;
6861                        }
6862                        // ...and the highest-priority default browser match
6863                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6864                            if (defaultBrowserMatch == null
6865                                    || (defaultBrowserMatch.priority < info.priority)) {
6866                                if (debug) {
6867                                    Slog.v(TAG, "Considering default browser match " + info);
6868                                }
6869                                defaultBrowserMatch = info;
6870                            }
6871                        }
6872                    }
6873                    if (defaultBrowserMatch != null
6874                            && defaultBrowserMatch.priority >= maxMatchPrio
6875                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6876                    {
6877                        if (debug) {
6878                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6879                        }
6880                        result.add(defaultBrowserMatch);
6881                    } else {
6882                        result.addAll(matchAllList);
6883                    }
6884                }
6885
6886                // If there is nothing selected, add all candidates and remove the ones that the user
6887                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6888                if (result.size() == 0) {
6889                    result.addAll(candidates);
6890                    result.removeAll(neverList);
6891                }
6892            }
6893        }
6894        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6895            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6896                    result.size());
6897            for (ResolveInfo info : result) {
6898                Slog.v(TAG, "  + " + info.activityInfo);
6899            }
6900        }
6901        return result;
6902    }
6903
6904    // Returns a packed value as a long:
6905    //
6906    // high 'int'-sized word: link status: undefined/ask/never/always.
6907    // low 'int'-sized word: relative priority among 'always' results.
6908    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6909        long result = ps.getDomainVerificationStatusForUser(userId);
6910        // if none available, get the master status
6911        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6912            if (ps.getIntentFilterVerificationInfo() != null) {
6913                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6914            }
6915        }
6916        return result;
6917    }
6918
6919    private ResolveInfo querySkipCurrentProfileIntents(
6920            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6921            int flags, int sourceUserId) {
6922        if (matchingFilters != null) {
6923            int size = matchingFilters.size();
6924            for (int i = 0; i < size; i ++) {
6925                CrossProfileIntentFilter filter = matchingFilters.get(i);
6926                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6927                    // Checking if there are activities in the target user that can handle the
6928                    // intent.
6929                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6930                            resolvedType, flags, sourceUserId);
6931                    if (resolveInfo != null) {
6932                        return resolveInfo;
6933                    }
6934                }
6935            }
6936        }
6937        return null;
6938    }
6939
6940    // Return matching ResolveInfo in target user if any.
6941    private ResolveInfo queryCrossProfileIntents(
6942            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6943            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6944        if (matchingFilters != null) {
6945            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6946            // match the same intent. For performance reasons, it is better not to
6947            // run queryIntent twice for the same userId
6948            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6949            int size = matchingFilters.size();
6950            for (int i = 0; i < size; i++) {
6951                CrossProfileIntentFilter filter = matchingFilters.get(i);
6952                int targetUserId = filter.getTargetUserId();
6953                boolean skipCurrentProfile =
6954                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6955                boolean skipCurrentProfileIfNoMatchFound =
6956                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6957                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6958                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6959                    // Checking if there are activities in the target user that can handle the
6960                    // intent.
6961                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6962                            resolvedType, flags, sourceUserId);
6963                    if (resolveInfo != null) return resolveInfo;
6964                    alreadyTriedUserIds.put(targetUserId, true);
6965                }
6966            }
6967        }
6968        return null;
6969    }
6970
6971    /**
6972     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6973     * will forward the intent to the filter's target user.
6974     * Otherwise, returns null.
6975     */
6976    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6977            String resolvedType, int flags, int sourceUserId) {
6978        int targetUserId = filter.getTargetUserId();
6979        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6980                resolvedType, flags, targetUserId);
6981        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6982            // If all the matches in the target profile are suspended, return null.
6983            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6984                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6985                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6986                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6987                            targetUserId);
6988                }
6989            }
6990        }
6991        return null;
6992    }
6993
6994    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6995            int sourceUserId, int targetUserId) {
6996        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6997        long ident = Binder.clearCallingIdentity();
6998        boolean targetIsProfile;
6999        try {
7000            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7001        } finally {
7002            Binder.restoreCallingIdentity(ident);
7003        }
7004        String className;
7005        if (targetIsProfile) {
7006            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7007        } else {
7008            className = FORWARD_INTENT_TO_PARENT;
7009        }
7010        ComponentName forwardingActivityComponentName = new ComponentName(
7011                mAndroidApplication.packageName, className);
7012        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7013                sourceUserId);
7014        if (!targetIsProfile) {
7015            forwardingActivityInfo.showUserIcon = targetUserId;
7016            forwardingResolveInfo.noResourceId = true;
7017        }
7018        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7019        forwardingResolveInfo.priority = 0;
7020        forwardingResolveInfo.preferredOrder = 0;
7021        forwardingResolveInfo.match = 0;
7022        forwardingResolveInfo.isDefault = true;
7023        forwardingResolveInfo.filter = filter;
7024        forwardingResolveInfo.targetUserId = targetUserId;
7025        return forwardingResolveInfo;
7026    }
7027
7028    @Override
7029    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7030            Intent[] specifics, String[] specificTypes, Intent intent,
7031            String resolvedType, int flags, int userId) {
7032        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7033                specificTypes, intent, resolvedType, flags, userId));
7034    }
7035
7036    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7037            Intent[] specifics, String[] specificTypes, Intent intent,
7038            String resolvedType, int flags, int userId) {
7039        if (!sUserManager.exists(userId)) return Collections.emptyList();
7040        final int callingUid = Binder.getCallingUid();
7041        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7042                false /*includeInstantApps*/);
7043        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7044                false /*requireFullPermission*/, false /*checkShell*/,
7045                "query intent activity options");
7046        final String resultsAction = intent.getAction();
7047
7048        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7049                | PackageManager.GET_RESOLVED_FILTER, userId);
7050
7051        if (DEBUG_INTENT_MATCHING) {
7052            Log.v(TAG, "Query " + intent + ": " + results);
7053        }
7054
7055        int specificsPos = 0;
7056        int N;
7057
7058        // todo: note that the algorithm used here is O(N^2).  This
7059        // isn't a problem in our current environment, but if we start running
7060        // into situations where we have more than 5 or 10 matches then this
7061        // should probably be changed to something smarter...
7062
7063        // First we go through and resolve each of the specific items
7064        // that were supplied, taking care of removing any corresponding
7065        // duplicate items in the generic resolve list.
7066        if (specifics != null) {
7067            for (int i=0; i<specifics.length; i++) {
7068                final Intent sintent = specifics[i];
7069                if (sintent == null) {
7070                    continue;
7071                }
7072
7073                if (DEBUG_INTENT_MATCHING) {
7074                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7075                }
7076
7077                String action = sintent.getAction();
7078                if (resultsAction != null && resultsAction.equals(action)) {
7079                    // If this action was explicitly requested, then don't
7080                    // remove things that have it.
7081                    action = null;
7082                }
7083
7084                ResolveInfo ri = null;
7085                ActivityInfo ai = null;
7086
7087                ComponentName comp = sintent.getComponent();
7088                if (comp == null) {
7089                    ri = resolveIntent(
7090                        sintent,
7091                        specificTypes != null ? specificTypes[i] : null,
7092                            flags, userId);
7093                    if (ri == null) {
7094                        continue;
7095                    }
7096                    if (ri == mResolveInfo) {
7097                        // ACK!  Must do something better with this.
7098                    }
7099                    ai = ri.activityInfo;
7100                    comp = new ComponentName(ai.applicationInfo.packageName,
7101                            ai.name);
7102                } else {
7103                    ai = getActivityInfo(comp, flags, userId);
7104                    if (ai == null) {
7105                        continue;
7106                    }
7107                }
7108
7109                // Look for any generic query activities that are duplicates
7110                // of this specific one, and remove them from the results.
7111                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7112                N = results.size();
7113                int j;
7114                for (j=specificsPos; j<N; j++) {
7115                    ResolveInfo sri = results.get(j);
7116                    if ((sri.activityInfo.name.equals(comp.getClassName())
7117                            && sri.activityInfo.applicationInfo.packageName.equals(
7118                                    comp.getPackageName()))
7119                        || (action != null && sri.filter.matchAction(action))) {
7120                        results.remove(j);
7121                        if (DEBUG_INTENT_MATCHING) Log.v(
7122                            TAG, "Removing duplicate item from " + j
7123                            + " due to specific " + specificsPos);
7124                        if (ri == null) {
7125                            ri = sri;
7126                        }
7127                        j--;
7128                        N--;
7129                    }
7130                }
7131
7132                // Add this specific item to its proper place.
7133                if (ri == null) {
7134                    ri = new ResolveInfo();
7135                    ri.activityInfo = ai;
7136                }
7137                results.add(specificsPos, ri);
7138                ri.specificIndex = i;
7139                specificsPos++;
7140            }
7141        }
7142
7143        // Now we go through the remaining generic results and remove any
7144        // duplicate actions that are found here.
7145        N = results.size();
7146        for (int i=specificsPos; i<N-1; i++) {
7147            final ResolveInfo rii = results.get(i);
7148            if (rii.filter == null) {
7149                continue;
7150            }
7151
7152            // Iterate over all of the actions of this result's intent
7153            // filter...  typically this should be just one.
7154            final Iterator<String> it = rii.filter.actionsIterator();
7155            if (it == null) {
7156                continue;
7157            }
7158            while (it.hasNext()) {
7159                final String action = it.next();
7160                if (resultsAction != null && resultsAction.equals(action)) {
7161                    // If this action was explicitly requested, then don't
7162                    // remove things that have it.
7163                    continue;
7164                }
7165                for (int j=i+1; j<N; j++) {
7166                    final ResolveInfo rij = results.get(j);
7167                    if (rij.filter != null && rij.filter.hasAction(action)) {
7168                        results.remove(j);
7169                        if (DEBUG_INTENT_MATCHING) Log.v(
7170                            TAG, "Removing duplicate item from " + j
7171                            + " due to action " + action + " at " + i);
7172                        j--;
7173                        N--;
7174                    }
7175                }
7176            }
7177
7178            // If the caller didn't request filter information, drop it now
7179            // so we don't have to marshall/unmarshall it.
7180            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7181                rii.filter = null;
7182            }
7183        }
7184
7185        // Filter out the caller activity if so requested.
7186        if (caller != null) {
7187            N = results.size();
7188            for (int i=0; i<N; i++) {
7189                ActivityInfo ainfo = results.get(i).activityInfo;
7190                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7191                        && caller.getClassName().equals(ainfo.name)) {
7192                    results.remove(i);
7193                    break;
7194                }
7195            }
7196        }
7197
7198        // If the caller didn't request filter information,
7199        // drop them now so we don't have to
7200        // marshall/unmarshall it.
7201        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7202            N = results.size();
7203            for (int i=0; i<N; i++) {
7204                results.get(i).filter = null;
7205            }
7206        }
7207
7208        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7209        return results;
7210    }
7211
7212    @Override
7213    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7214            String resolvedType, int flags, int userId) {
7215        return new ParceledListSlice<>(
7216                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7217                        false /*allowDynamicSplits*/));
7218    }
7219
7220    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7221            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7222        if (!sUserManager.exists(userId)) return Collections.emptyList();
7223        final int callingUid = Binder.getCallingUid();
7224        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7225                false /*requireFullPermission*/, false /*checkShell*/,
7226                "query intent receivers");
7227        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7228        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7229                false /*includeInstantApps*/);
7230        ComponentName comp = intent.getComponent();
7231        if (comp == null) {
7232            if (intent.getSelector() != null) {
7233                intent = intent.getSelector();
7234                comp = intent.getComponent();
7235            }
7236        }
7237        if (comp != null) {
7238            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7239            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7240            if (ai != null) {
7241                // When specifying an explicit component, we prevent the activity from being
7242                // used when either 1) the calling package is normal and the activity is within
7243                // an instant application or 2) the calling package is ephemeral and the
7244                // activity is not visible to instant applications.
7245                final boolean matchInstantApp =
7246                        (flags & PackageManager.MATCH_INSTANT) != 0;
7247                final boolean matchVisibleToInstantAppOnly =
7248                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7249                final boolean matchExplicitlyVisibleOnly =
7250                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7251                final boolean isCallerInstantApp =
7252                        instantAppPkgName != null;
7253                final boolean isTargetSameInstantApp =
7254                        comp.getPackageName().equals(instantAppPkgName);
7255                final boolean isTargetInstantApp =
7256                        (ai.applicationInfo.privateFlags
7257                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7258                final boolean isTargetVisibleToInstantApp =
7259                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7260                final boolean isTargetExplicitlyVisibleToInstantApp =
7261                        isTargetVisibleToInstantApp
7262                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7263                final boolean isTargetHiddenFromInstantApp =
7264                        !isTargetVisibleToInstantApp
7265                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7266                final boolean blockResolution =
7267                        !isTargetSameInstantApp
7268                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7269                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7270                                        && isTargetHiddenFromInstantApp));
7271                if (!blockResolution) {
7272                    ResolveInfo ri = new ResolveInfo();
7273                    ri.activityInfo = ai;
7274                    list.add(ri);
7275                }
7276            }
7277            return applyPostResolutionFilter(
7278                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7279        }
7280
7281        // reader
7282        synchronized (mPackages) {
7283            String pkgName = intent.getPackage();
7284            if (pkgName == null) {
7285                final List<ResolveInfo> result =
7286                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7287                return applyPostResolutionFilter(
7288                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7289            }
7290            final PackageParser.Package pkg = mPackages.get(pkgName);
7291            if (pkg != null) {
7292                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7293                        intent, resolvedType, flags, pkg.receivers, userId);
7294                return applyPostResolutionFilter(
7295                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7296            }
7297            return Collections.emptyList();
7298        }
7299    }
7300
7301    @Override
7302    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7303        final int callingUid = Binder.getCallingUid();
7304        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7305    }
7306
7307    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7308            int userId, int callingUid) {
7309        if (!sUserManager.exists(userId)) return null;
7310        flags = updateFlagsForResolve(
7311                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7312        List<ResolveInfo> query = queryIntentServicesInternal(
7313                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7314        if (query != null) {
7315            if (query.size() >= 1) {
7316                // If there is more than one service with the same priority,
7317                // just arbitrarily pick the first one.
7318                return query.get(0);
7319            }
7320        }
7321        return null;
7322    }
7323
7324    @Override
7325    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7326            String resolvedType, int flags, int userId) {
7327        final int callingUid = Binder.getCallingUid();
7328        return new ParceledListSlice<>(queryIntentServicesInternal(
7329                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7330    }
7331
7332    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7333            String resolvedType, int flags, int userId, int callingUid,
7334            boolean includeInstantApps) {
7335        if (!sUserManager.exists(userId)) return Collections.emptyList();
7336        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7337                false /*requireFullPermission*/, false /*checkShell*/,
7338                "query intent receivers");
7339        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7340        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7341        ComponentName comp = intent.getComponent();
7342        if (comp == null) {
7343            if (intent.getSelector() != null) {
7344                intent = intent.getSelector();
7345                comp = intent.getComponent();
7346            }
7347        }
7348        if (comp != null) {
7349            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7350            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7351            if (si != null) {
7352                // When specifying an explicit component, we prevent the service from being
7353                // used when either 1) the service is in an instant application and the
7354                // caller is not the same instant application or 2) the calling package is
7355                // ephemeral and the activity is not visible to ephemeral applications.
7356                final boolean matchInstantApp =
7357                        (flags & PackageManager.MATCH_INSTANT) != 0;
7358                final boolean matchVisibleToInstantAppOnly =
7359                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7360                final boolean isCallerInstantApp =
7361                        instantAppPkgName != null;
7362                final boolean isTargetSameInstantApp =
7363                        comp.getPackageName().equals(instantAppPkgName);
7364                final boolean isTargetInstantApp =
7365                        (si.applicationInfo.privateFlags
7366                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7367                final boolean isTargetHiddenFromInstantApp =
7368                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7369                final boolean blockResolution =
7370                        !isTargetSameInstantApp
7371                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7372                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7373                                        && isTargetHiddenFromInstantApp));
7374                if (!blockResolution) {
7375                    final ResolveInfo ri = new ResolveInfo();
7376                    ri.serviceInfo = si;
7377                    list.add(ri);
7378                }
7379            }
7380            return list;
7381        }
7382
7383        // reader
7384        synchronized (mPackages) {
7385            String pkgName = intent.getPackage();
7386            if (pkgName == null) {
7387                return applyPostServiceResolutionFilter(
7388                        mServices.queryIntent(intent, resolvedType, flags, userId),
7389                        instantAppPkgName);
7390            }
7391            final PackageParser.Package pkg = mPackages.get(pkgName);
7392            if (pkg != null) {
7393                return applyPostServiceResolutionFilter(
7394                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7395                                userId),
7396                        instantAppPkgName);
7397            }
7398            return Collections.emptyList();
7399        }
7400    }
7401
7402    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7403            String instantAppPkgName) {
7404        if (instantAppPkgName == null) {
7405            return resolveInfos;
7406        }
7407        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7408            final ResolveInfo info = resolveInfos.get(i);
7409            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7410            // allow services that are defined in the provided package
7411            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7412                if (info.serviceInfo.splitName != null
7413                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7414                                info.serviceInfo.splitName)) {
7415                    // requested service is defined in a split that hasn't been installed yet.
7416                    // add the installer to the resolve list
7417                    if (DEBUG_EPHEMERAL) {
7418                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7419                    }
7420                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7421                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7422                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7423                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7424                            null /*failureIntent*/);
7425                    // make sure this resolver is the default
7426                    installerInfo.isDefault = true;
7427                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7428                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7429                    // add a non-generic filter
7430                    installerInfo.filter = new IntentFilter();
7431                    // load resources from the correct package
7432                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7433                    resolveInfos.set(i, installerInfo);
7434                }
7435                continue;
7436            }
7437            // allow services that have been explicitly exposed to ephemeral apps
7438            if (!isEphemeralApp
7439                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7440                continue;
7441            }
7442            resolveInfos.remove(i);
7443        }
7444        return resolveInfos;
7445    }
7446
7447    @Override
7448    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7449            String resolvedType, int flags, int userId) {
7450        return new ParceledListSlice<>(
7451                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7452    }
7453
7454    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7455            Intent intent, String resolvedType, int flags, int userId) {
7456        if (!sUserManager.exists(userId)) return Collections.emptyList();
7457        final int callingUid = Binder.getCallingUid();
7458        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7459        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7460                false /*includeInstantApps*/);
7461        ComponentName comp = intent.getComponent();
7462        if (comp == null) {
7463            if (intent.getSelector() != null) {
7464                intent = intent.getSelector();
7465                comp = intent.getComponent();
7466            }
7467        }
7468        if (comp != null) {
7469            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7470            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7471            if (pi != null) {
7472                // When specifying an explicit component, we prevent the provider from being
7473                // used when either 1) the provider is in an instant application and the
7474                // caller is not the same instant application or 2) the calling package is an
7475                // instant application and the provider is not visible to instant applications.
7476                final boolean matchInstantApp =
7477                        (flags & PackageManager.MATCH_INSTANT) != 0;
7478                final boolean matchVisibleToInstantAppOnly =
7479                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7480                final boolean isCallerInstantApp =
7481                        instantAppPkgName != null;
7482                final boolean isTargetSameInstantApp =
7483                        comp.getPackageName().equals(instantAppPkgName);
7484                final boolean isTargetInstantApp =
7485                        (pi.applicationInfo.privateFlags
7486                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7487                final boolean isTargetHiddenFromInstantApp =
7488                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7489                final boolean blockResolution =
7490                        !isTargetSameInstantApp
7491                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7492                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7493                                        && isTargetHiddenFromInstantApp));
7494                if (!blockResolution) {
7495                    final ResolveInfo ri = new ResolveInfo();
7496                    ri.providerInfo = pi;
7497                    list.add(ri);
7498                }
7499            }
7500            return list;
7501        }
7502
7503        // reader
7504        synchronized (mPackages) {
7505            String pkgName = intent.getPackage();
7506            if (pkgName == null) {
7507                return applyPostContentProviderResolutionFilter(
7508                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7509                        instantAppPkgName);
7510            }
7511            final PackageParser.Package pkg = mPackages.get(pkgName);
7512            if (pkg != null) {
7513                return applyPostContentProviderResolutionFilter(
7514                        mProviders.queryIntentForPackage(
7515                        intent, resolvedType, flags, pkg.providers, userId),
7516                        instantAppPkgName);
7517            }
7518            return Collections.emptyList();
7519        }
7520    }
7521
7522    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7523            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7524        if (instantAppPkgName == null) {
7525            return resolveInfos;
7526        }
7527        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7528            final ResolveInfo info = resolveInfos.get(i);
7529            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7530            // allow providers that are defined in the provided package
7531            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7532                if (info.providerInfo.splitName != null
7533                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7534                                info.providerInfo.splitName)) {
7535                    // requested provider is defined in a split that hasn't been installed yet.
7536                    // add the installer to the resolve list
7537                    if (DEBUG_EPHEMERAL) {
7538                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7539                    }
7540                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7541                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7542                            info.providerInfo.packageName, info.providerInfo.splitName,
7543                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7544                            null /*failureIntent*/);
7545                    // make sure this resolver is the default
7546                    installerInfo.isDefault = true;
7547                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7548                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7549                    // add a non-generic filter
7550                    installerInfo.filter = new IntentFilter();
7551                    // load resources from the correct package
7552                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7553                    resolveInfos.set(i, installerInfo);
7554                }
7555                continue;
7556            }
7557            // allow providers that have been explicitly exposed to instant applications
7558            if (!isEphemeralApp
7559                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7560                continue;
7561            }
7562            resolveInfos.remove(i);
7563        }
7564        return resolveInfos;
7565    }
7566
7567    @Override
7568    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7569        final int callingUid = Binder.getCallingUid();
7570        if (getInstantAppPackageName(callingUid) != null) {
7571            return ParceledListSlice.emptyList();
7572        }
7573        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7574        flags = updateFlagsForPackage(flags, userId, null);
7575        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7576        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7577                true /* requireFullPermission */, false /* checkShell */,
7578                "get installed packages");
7579
7580        // writer
7581        synchronized (mPackages) {
7582            ArrayList<PackageInfo> list;
7583            if (listUninstalled) {
7584                list = new ArrayList<>(mSettings.mPackages.size());
7585                for (PackageSetting ps : mSettings.mPackages.values()) {
7586                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7587                        continue;
7588                    }
7589                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7590                        continue;
7591                    }
7592                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7593                    if (pi != null) {
7594                        list.add(pi);
7595                    }
7596                }
7597            } else {
7598                list = new ArrayList<>(mPackages.size());
7599                for (PackageParser.Package p : mPackages.values()) {
7600                    final PackageSetting ps = (PackageSetting) p.mExtras;
7601                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7602                        continue;
7603                    }
7604                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7605                        continue;
7606                    }
7607                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7608                            p.mExtras, flags, userId);
7609                    if (pi != null) {
7610                        list.add(pi);
7611                    }
7612                }
7613            }
7614
7615            return new ParceledListSlice<>(list);
7616        }
7617    }
7618
7619    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7620            String[] permissions, boolean[] tmp, int flags, int userId) {
7621        int numMatch = 0;
7622        final PermissionsState permissionsState = ps.getPermissionsState();
7623        for (int i=0; i<permissions.length; i++) {
7624            final String permission = permissions[i];
7625            if (permissionsState.hasPermission(permission, userId)) {
7626                tmp[i] = true;
7627                numMatch++;
7628            } else {
7629                tmp[i] = false;
7630            }
7631        }
7632        if (numMatch == 0) {
7633            return;
7634        }
7635        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7636
7637        // The above might return null in cases of uninstalled apps or install-state
7638        // skew across users/profiles.
7639        if (pi != null) {
7640            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7641                if (numMatch == permissions.length) {
7642                    pi.requestedPermissions = permissions;
7643                } else {
7644                    pi.requestedPermissions = new String[numMatch];
7645                    numMatch = 0;
7646                    for (int i=0; i<permissions.length; i++) {
7647                        if (tmp[i]) {
7648                            pi.requestedPermissions[numMatch] = permissions[i];
7649                            numMatch++;
7650                        }
7651                    }
7652                }
7653            }
7654            list.add(pi);
7655        }
7656    }
7657
7658    @Override
7659    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7660            String[] permissions, int flags, int userId) {
7661        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7662        flags = updateFlagsForPackage(flags, userId, permissions);
7663        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7664                true /* requireFullPermission */, false /* checkShell */,
7665                "get packages holding permissions");
7666        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7667
7668        // writer
7669        synchronized (mPackages) {
7670            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7671            boolean[] tmpBools = new boolean[permissions.length];
7672            if (listUninstalled) {
7673                for (PackageSetting ps : mSettings.mPackages.values()) {
7674                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7675                            userId);
7676                }
7677            } else {
7678                for (PackageParser.Package pkg : mPackages.values()) {
7679                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7680                    if (ps != null) {
7681                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7682                                userId);
7683                    }
7684                }
7685            }
7686
7687            return new ParceledListSlice<PackageInfo>(list);
7688        }
7689    }
7690
7691    @Override
7692    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7693        final int callingUid = Binder.getCallingUid();
7694        if (getInstantAppPackageName(callingUid) != null) {
7695            return ParceledListSlice.emptyList();
7696        }
7697        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7698        flags = updateFlagsForApplication(flags, userId, null);
7699        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7700
7701        // writer
7702        synchronized (mPackages) {
7703            ArrayList<ApplicationInfo> list;
7704            if (listUninstalled) {
7705                list = new ArrayList<>(mSettings.mPackages.size());
7706                for (PackageSetting ps : mSettings.mPackages.values()) {
7707                    ApplicationInfo ai;
7708                    int effectiveFlags = flags;
7709                    if (ps.isSystem()) {
7710                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7711                    }
7712                    if (ps.pkg != null) {
7713                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7714                            continue;
7715                        }
7716                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7717                            continue;
7718                        }
7719                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7720                                ps.readUserState(userId), userId);
7721                        if (ai != null) {
7722                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7723                        }
7724                    } else {
7725                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7726                        // and already converts to externally visible package name
7727                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7728                                callingUid, effectiveFlags, userId);
7729                    }
7730                    if (ai != null) {
7731                        list.add(ai);
7732                    }
7733                }
7734            } else {
7735                list = new ArrayList<>(mPackages.size());
7736                for (PackageParser.Package p : mPackages.values()) {
7737                    if (p.mExtras != null) {
7738                        PackageSetting ps = (PackageSetting) p.mExtras;
7739                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7740                            continue;
7741                        }
7742                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7743                            continue;
7744                        }
7745                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7746                                ps.readUserState(userId), userId);
7747                        if (ai != null) {
7748                            ai.packageName = resolveExternalPackageNameLPr(p);
7749                            list.add(ai);
7750                        }
7751                    }
7752                }
7753            }
7754
7755            return new ParceledListSlice<>(list);
7756        }
7757    }
7758
7759    @Override
7760    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7761        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7762            return null;
7763        }
7764        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7765            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7766                    "getEphemeralApplications");
7767        }
7768        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7769                true /* requireFullPermission */, false /* checkShell */,
7770                "getEphemeralApplications");
7771        synchronized (mPackages) {
7772            List<InstantAppInfo> instantApps = mInstantAppRegistry
7773                    .getInstantAppsLPr(userId);
7774            if (instantApps != null) {
7775                return new ParceledListSlice<>(instantApps);
7776            }
7777        }
7778        return null;
7779    }
7780
7781    @Override
7782    public boolean isInstantApp(String packageName, int userId) {
7783        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7784                true /* requireFullPermission */, false /* checkShell */,
7785                "isInstantApp");
7786        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7787            return false;
7788        }
7789
7790        synchronized (mPackages) {
7791            int callingUid = Binder.getCallingUid();
7792            if (Process.isIsolated(callingUid)) {
7793                callingUid = mIsolatedOwners.get(callingUid);
7794            }
7795            final PackageSetting ps = mSettings.mPackages.get(packageName);
7796            PackageParser.Package pkg = mPackages.get(packageName);
7797            final boolean returnAllowed =
7798                    ps != null
7799                    && (isCallerSameApp(packageName, callingUid)
7800                            || canViewInstantApps(callingUid, userId)
7801                            || mInstantAppRegistry.isInstantAccessGranted(
7802                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7803            if (returnAllowed) {
7804                return ps.getInstantApp(userId);
7805            }
7806        }
7807        return false;
7808    }
7809
7810    @Override
7811    public byte[] getInstantAppCookie(String packageName, int userId) {
7812        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7813            return null;
7814        }
7815
7816        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7817                true /* requireFullPermission */, false /* checkShell */,
7818                "getInstantAppCookie");
7819        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7820            return null;
7821        }
7822        synchronized (mPackages) {
7823            return mInstantAppRegistry.getInstantAppCookieLPw(
7824                    packageName, userId);
7825        }
7826    }
7827
7828    @Override
7829    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7830        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7831            return true;
7832        }
7833
7834        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7835                true /* requireFullPermission */, true /* checkShell */,
7836                "setInstantAppCookie");
7837        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7838            return false;
7839        }
7840        synchronized (mPackages) {
7841            return mInstantAppRegistry.setInstantAppCookieLPw(
7842                    packageName, cookie, userId);
7843        }
7844    }
7845
7846    @Override
7847    public Bitmap getInstantAppIcon(String packageName, int userId) {
7848        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7849            return null;
7850        }
7851
7852        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7853            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7854                    "getInstantAppIcon");
7855        }
7856        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7857                true /* requireFullPermission */, false /* checkShell */,
7858                "getInstantAppIcon");
7859
7860        synchronized (mPackages) {
7861            return mInstantAppRegistry.getInstantAppIconLPw(
7862                    packageName, userId);
7863        }
7864    }
7865
7866    private boolean isCallerSameApp(String packageName, int uid) {
7867        PackageParser.Package pkg = mPackages.get(packageName);
7868        return pkg != null
7869                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7870    }
7871
7872    @Override
7873    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7874        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7875            return ParceledListSlice.emptyList();
7876        }
7877        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7878    }
7879
7880    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7881        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7882
7883        // reader
7884        synchronized (mPackages) {
7885            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7886            final int userId = UserHandle.getCallingUserId();
7887            while (i.hasNext()) {
7888                final PackageParser.Package p = i.next();
7889                if (p.applicationInfo == null) continue;
7890
7891                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7892                        && !p.applicationInfo.isDirectBootAware();
7893                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7894                        && p.applicationInfo.isDirectBootAware();
7895
7896                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7897                        && (!mSafeMode || isSystemApp(p))
7898                        && (matchesUnaware || matchesAware)) {
7899                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7900                    if (ps != null) {
7901                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7902                                ps.readUserState(userId), userId);
7903                        if (ai != null) {
7904                            finalList.add(ai);
7905                        }
7906                    }
7907                }
7908            }
7909        }
7910
7911        return finalList;
7912    }
7913
7914    @Override
7915    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7916        return resolveContentProviderInternal(name, flags, userId);
7917    }
7918
7919    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7920        if (!sUserManager.exists(userId)) return null;
7921        flags = updateFlagsForComponent(flags, userId, name);
7922        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7923        // reader
7924        synchronized (mPackages) {
7925            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7926            PackageSetting ps = provider != null
7927                    ? mSettings.mPackages.get(provider.owner.packageName)
7928                    : null;
7929            if (ps != null) {
7930                final boolean isInstantApp = ps.getInstantApp(userId);
7931                // normal application; filter out instant application provider
7932                if (instantAppPkgName == null && isInstantApp) {
7933                    return null;
7934                }
7935                // instant application; filter out other instant applications
7936                if (instantAppPkgName != null
7937                        && isInstantApp
7938                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7939                    return null;
7940                }
7941                // instant application; filter out non-exposed provider
7942                if (instantAppPkgName != null
7943                        && !isInstantApp
7944                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7945                    return null;
7946                }
7947                // provider not enabled
7948                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7949                    return null;
7950                }
7951                return PackageParser.generateProviderInfo(
7952                        provider, flags, ps.readUserState(userId), userId);
7953            }
7954            return null;
7955        }
7956    }
7957
7958    /**
7959     * @deprecated
7960     */
7961    @Deprecated
7962    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7963        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7964            return;
7965        }
7966        // reader
7967        synchronized (mPackages) {
7968            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7969                    .entrySet().iterator();
7970            final int userId = UserHandle.getCallingUserId();
7971            while (i.hasNext()) {
7972                Map.Entry<String, PackageParser.Provider> entry = i.next();
7973                PackageParser.Provider p = entry.getValue();
7974                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7975
7976                if (ps != null && p.syncable
7977                        && (!mSafeMode || (p.info.applicationInfo.flags
7978                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7979                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7980                            ps.readUserState(userId), userId);
7981                    if (info != null) {
7982                        outNames.add(entry.getKey());
7983                        outInfo.add(info);
7984                    }
7985                }
7986            }
7987        }
7988    }
7989
7990    @Override
7991    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7992            int uid, int flags, String metaDataKey) {
7993        final int callingUid = Binder.getCallingUid();
7994        final int userId = processName != null ? UserHandle.getUserId(uid)
7995                : UserHandle.getCallingUserId();
7996        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7997        flags = updateFlagsForComponent(flags, userId, processName);
7998        ArrayList<ProviderInfo> finalList = null;
7999        // reader
8000        synchronized (mPackages) {
8001            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8002            while (i.hasNext()) {
8003                final PackageParser.Provider p = i.next();
8004                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8005                if (ps != null && p.info.authority != null
8006                        && (processName == null
8007                                || (p.info.processName.equals(processName)
8008                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8009                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8010
8011                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8012                    // parameter.
8013                    if (metaDataKey != null
8014                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8015                        continue;
8016                    }
8017                    final ComponentName component =
8018                            new ComponentName(p.info.packageName, p.info.name);
8019                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8020                        continue;
8021                    }
8022                    if (finalList == null) {
8023                        finalList = new ArrayList<ProviderInfo>(3);
8024                    }
8025                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8026                            ps.readUserState(userId), userId);
8027                    if (info != null) {
8028                        finalList.add(info);
8029                    }
8030                }
8031            }
8032        }
8033
8034        if (finalList != null) {
8035            Collections.sort(finalList, mProviderInitOrderSorter);
8036            return new ParceledListSlice<ProviderInfo>(finalList);
8037        }
8038
8039        return ParceledListSlice.emptyList();
8040    }
8041
8042    @Override
8043    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8044        // reader
8045        synchronized (mPackages) {
8046            final int callingUid = Binder.getCallingUid();
8047            final int callingUserId = UserHandle.getUserId(callingUid);
8048            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8049            if (ps == null) return null;
8050            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8051                return null;
8052            }
8053            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8054            return PackageParser.generateInstrumentationInfo(i, flags);
8055        }
8056    }
8057
8058    @Override
8059    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8060            String targetPackage, int flags) {
8061        final int callingUid = Binder.getCallingUid();
8062        final int callingUserId = UserHandle.getUserId(callingUid);
8063        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8064        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8065            return ParceledListSlice.emptyList();
8066        }
8067        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8068    }
8069
8070    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8071            int flags) {
8072        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8073
8074        // reader
8075        synchronized (mPackages) {
8076            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8077            while (i.hasNext()) {
8078                final PackageParser.Instrumentation p = i.next();
8079                if (targetPackage == null
8080                        || targetPackage.equals(p.info.targetPackage)) {
8081                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8082                            flags);
8083                    if (ii != null) {
8084                        finalList.add(ii);
8085                    }
8086                }
8087            }
8088        }
8089
8090        return finalList;
8091    }
8092
8093    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8094        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8095        try {
8096            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8097        } finally {
8098            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8099        }
8100    }
8101
8102    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8103        final File[] files = scanDir.listFiles();
8104        if (ArrayUtils.isEmpty(files)) {
8105            Log.d(TAG, "No files in app dir " + scanDir);
8106            return;
8107        }
8108
8109        if (DEBUG_PACKAGE_SCANNING) {
8110            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8111                    + " flags=0x" + Integer.toHexString(parseFlags));
8112        }
8113        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8114                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8115                mParallelPackageParserCallback)) {
8116            // Submit files for parsing in parallel
8117            int fileCount = 0;
8118            for (File file : files) {
8119                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8120                        && !PackageInstallerService.isStageName(file.getName());
8121                if (!isPackage) {
8122                    // Ignore entries which are not packages
8123                    continue;
8124                }
8125                parallelPackageParser.submit(file, parseFlags);
8126                fileCount++;
8127            }
8128
8129            // Process results one by one
8130            for (; fileCount > 0; fileCount--) {
8131                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8132                Throwable throwable = parseResult.throwable;
8133                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8134
8135                if (throwable == null) {
8136                    // TODO(toddke): move lower in the scan chain
8137                    // Static shared libraries have synthetic package names
8138                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8139                        renameStaticSharedLibraryPackage(parseResult.pkg);
8140                    }
8141                    try {
8142                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8143                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8144                                    currentTime, null);
8145                        }
8146                    } catch (PackageManagerException e) {
8147                        errorCode = e.error;
8148                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8149                    }
8150                } else if (throwable instanceof PackageParser.PackageParserException) {
8151                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8152                            throwable;
8153                    errorCode = e.error;
8154                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8155                } else {
8156                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8157                            + parseResult.scanFile, throwable);
8158                }
8159
8160                // Delete invalid userdata apps
8161                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8162                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8163                    logCriticalInfo(Log.WARN,
8164                            "Deleting invalid package at " + parseResult.scanFile);
8165                    removeCodePathLI(parseResult.scanFile);
8166                }
8167            }
8168        }
8169    }
8170
8171    public static void reportSettingsProblem(int priority, String msg) {
8172        logCriticalInfo(priority, msg);
8173    }
8174
8175    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8176            final @ParseFlags int parseFlags) throws PackageManagerException {
8177        // When upgrading from pre-N MR1, verify the package time stamp using the package
8178        // directory and not the APK file.
8179        final long lastModifiedTime = mIsPreNMR1Upgrade
8180                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8181        if (ps != null
8182                && ps.codePathString.equals(pkg.codePath)
8183                && ps.timeStamp == lastModifiedTime
8184                && !isCompatSignatureUpdateNeeded(pkg)
8185                && !isRecoverSignatureUpdateNeeded(pkg)) {
8186            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8187            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8188            ArraySet<PublicKey> signingKs;
8189            synchronized (mPackages) {
8190                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8191            }
8192            if (ps.signatures.mSignatures != null
8193                    && ps.signatures.mSignatures.length != 0
8194                    && signingKs != null) {
8195                // Optimization: reuse the existing cached certificates
8196                // if the package appears to be unchanged.
8197                pkg.mSignatures = ps.signatures.mSignatures;
8198                pkg.mSigningKeys = signingKs;
8199                return;
8200            }
8201
8202            Slog.w(TAG, "PackageSetting for " + ps.name
8203                    + " is missing signatures.  Collecting certs again to recover them.");
8204        } else {
8205            Slog.i(TAG, toString() + " changed; collecting certs");
8206        }
8207
8208        try {
8209            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8210            PackageParser.collectCertificates(pkg, parseFlags);
8211        } catch (PackageParserException e) {
8212            throw PackageManagerException.from(e);
8213        } finally {
8214            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8215        }
8216    }
8217
8218    /**
8219     *  Traces a package scan.
8220     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8221     */
8222    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8223            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8224        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8225        try {
8226            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8227        } finally {
8228            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8229        }
8230    }
8231
8232    /**
8233     *  Scans a package and returns the newly parsed package.
8234     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8235     */
8236    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8237            long currentTime, UserHandle user) throws PackageManagerException {
8238        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8239        PackageParser pp = new PackageParser();
8240        pp.setSeparateProcesses(mSeparateProcesses);
8241        pp.setOnlyCoreApps(mOnlyCore);
8242        pp.setDisplayMetrics(mMetrics);
8243        pp.setCallback(mPackageParserCallback);
8244
8245        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8246        final PackageParser.Package pkg;
8247        try {
8248            pkg = pp.parsePackage(scanFile, parseFlags);
8249        } catch (PackageParserException e) {
8250            throw PackageManagerException.from(e);
8251        } finally {
8252            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8253        }
8254
8255        // Static shared libraries have synthetic package names
8256        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8257            renameStaticSharedLibraryPackage(pkg);
8258        }
8259
8260        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8261    }
8262
8263    /**
8264     *  Scans a package and returns the newly parsed package.
8265     *  @throws PackageManagerException on a parse error.
8266     */
8267    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8268            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8269            @Nullable UserHandle user)
8270                    throws PackageManagerException {
8271        // If the package has children and this is the first dive in the function
8272        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8273        // packages (parent and children) would be successfully scanned before the
8274        // actual scan since scanning mutates internal state and we want to atomically
8275        // install the package and its children.
8276        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8277            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8278                scanFlags |= SCAN_CHECK_ONLY;
8279            }
8280        } else {
8281            scanFlags &= ~SCAN_CHECK_ONLY;
8282        }
8283
8284        // Scan the parent
8285        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags,
8286                scanFlags, currentTime, user);
8287
8288        // Scan the children
8289        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8290        for (int i = 0; i < childCount; i++) {
8291            PackageParser.Package childPackage = pkg.childPackages.get(i);
8292            scanPackageInternalLI(childPackage, parseFlags, scanFlags,
8293                    currentTime, user);
8294        }
8295
8296
8297        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8298            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8299        }
8300
8301        return scannedPkg;
8302    }
8303
8304    /**
8305     *  Scans a package and returns the newly parsed package.
8306     *  @throws PackageManagerException on a parse error.
8307     */
8308    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg,
8309            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8310            @Nullable UserHandle user)
8311                    throws PackageManagerException {
8312        PackageSetting ps = null;
8313        PackageSetting updatedPs;
8314        // reader
8315        synchronized (mPackages) {
8316            // Look to see if we already know about this package.
8317            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8318            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8319                // This package has been renamed to its original name.  Let's
8320                // use that.
8321                ps = mSettings.getPackageLPr(oldName);
8322            }
8323            // If there was no original package, see one for the real package name.
8324            if (ps == null) {
8325                ps = mSettings.getPackageLPr(pkg.packageName);
8326            }
8327            // Check to see if this package could be hiding/updating a system
8328            // package.  Must look for it either under the original or real
8329            // package name depending on our state.
8330            updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8331            if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs);
8332
8333            // If this is a package we don't know about on the system partition, we
8334            // may need to remove disabled child packages on the system partition
8335            // or may need to not add child packages if the parent apk is updated
8336            // on the data partition and no longer defines this child package.
8337            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8338                // If this is a parent package for an updated system app and this system
8339                // app got an OTA update which no longer defines some of the child packages
8340                // we have to prune them from the disabled system packages.
8341                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8342                if (disabledPs != null) {
8343                    final int scannedChildCount = (pkg.childPackages != null)
8344                            ? pkg.childPackages.size() : 0;
8345                    final int disabledChildCount = disabledPs.childPackageNames != null
8346                            ? disabledPs.childPackageNames.size() : 0;
8347                    for (int i = 0; i < disabledChildCount; i++) {
8348                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8349                        boolean disabledPackageAvailable = false;
8350                        for (int j = 0; j < scannedChildCount; j++) {
8351                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8352                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8353                                disabledPackageAvailable = true;
8354                                break;
8355                            }
8356                         }
8357                         if (!disabledPackageAvailable) {
8358                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8359                         }
8360                    }
8361                }
8362            }
8363        }
8364
8365        final boolean isUpdatedPkg = updatedPs != null;
8366        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8367        boolean isUpdatedPkgBetter = false;
8368        // First check if this is a system package that may involve an update
8369        if (isUpdatedSystemPkg) {
8370            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8371            // it needs to drop FLAG_PRIVILEGED.
8372            if (locationIsPrivileged(pkg.codePath)) {
8373                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8374            } else {
8375                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8376            }
8377            // If new package is not located in "/oem" (e.g. due to an OTA),
8378            // it needs to drop FLAG_OEM.
8379            if (locationIsOem(pkg.codePath)) {
8380                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8381            } else {
8382                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8383            }
8384            // If new package is not located in "/vendor" (e.g. due to an OTA),
8385            // it needs to drop FLAG_VENDOR.
8386            if (locationIsVendor(pkg.codePath)) {
8387                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
8388            } else {
8389                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_VENDOR;
8390            }
8391
8392            if (ps != null && !ps.codePathString.equals(pkg.codePath)) {
8393                // The path has changed from what was last scanned...  check the
8394                // version of the new path against what we have stored to determine
8395                // what to do.
8396                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8397                if (pkg.getLongVersionCode() <= ps.versionCode) {
8398                    // The system package has been updated and the code path does not match
8399                    // Ignore entry. Skip it.
8400                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath
8401                            + " ignored: updated version " + ps.versionCode
8402                            + " better than this " + pkg.getLongVersionCode());
8403                    if (!updatedPs.codePathString.equals(pkg.codePath)) {
8404                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8405                                + ps.name + " changing from " + updatedPs.codePathString
8406                                + " to " + pkg.codePath);
8407                        final File codePath = new File(pkg.codePath);
8408                        updatedPs.codePath = codePath;
8409                        updatedPs.codePathString = pkg.codePath;
8410                        updatedPs.resourcePath = codePath;
8411                        updatedPs.resourcePathString = pkg.codePath;
8412                    }
8413                    updatedPs.pkg = pkg;
8414                    updatedPs.versionCode = pkg.getLongVersionCode();
8415
8416                    // Update the disabled system child packages to point to the package too.
8417                    final int childCount = updatedPs.childPackageNames != null
8418                            ? updatedPs.childPackageNames.size() : 0;
8419                    for (int i = 0; i < childCount; i++) {
8420                        String childPackageName = updatedPs.childPackageNames.get(i);
8421                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8422                                childPackageName);
8423                        if (updatedChildPkg != null) {
8424                            updatedChildPkg.pkg = pkg;
8425                            updatedChildPkg.versionCode = pkg.getLongVersionCode();
8426                        }
8427                    }
8428                } else {
8429                    // The current app on the system partition is better than
8430                    // what we have updated to on the data partition; switch
8431                    // back to the system partition version.
8432                    // At this point, its safely assumed that package installation for
8433                    // apps in system partition will go through. If not there won't be a working
8434                    // version of the app
8435                    // writer
8436                    synchronized (mPackages) {
8437                        // Just remove the loaded entries from package lists.
8438                        mPackages.remove(ps.name);
8439                    }
8440
8441                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8442                            + " reverting from " + ps.codePathString
8443                            + ": new version " + pkg.getLongVersionCode()
8444                            + " better than installed " + ps.versionCode);
8445
8446                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8447                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8448                    synchronized (mInstallLock) {
8449                        args.cleanUpResourcesLI();
8450                    }
8451                    synchronized (mPackages) {
8452                        mSettings.enableSystemPackageLPw(ps.name);
8453                    }
8454                    isUpdatedPkgBetter = true;
8455                }
8456            }
8457        }
8458
8459        String resourcePath = null;
8460        String baseResourcePath = null;
8461        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8462            if (ps != null && ps.resourcePathString != null) {
8463                resourcePath = ps.resourcePathString;
8464                baseResourcePath = ps.resourcePathString;
8465            } else {
8466                // Should not happen at all. Just log an error.
8467                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8468            }
8469        } else {
8470            resourcePath = pkg.codePath;
8471            baseResourcePath = pkg.baseCodePath;
8472        }
8473
8474        // Set application objects path explicitly.
8475        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8476        pkg.setApplicationInfoCodePath(pkg.codePath);
8477        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8478        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8479        pkg.setApplicationInfoResourcePath(resourcePath);
8480        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8481        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8482
8483        // throw an exception if we have an update to a system application, but, it's not more
8484        // recent than the package we've already scanned
8485        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8486            // Set CPU Abis to application info.
8487            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8488                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs);
8489                derivePackageAbi(pkg, cpuAbiOverride, false);
8490            } else {
8491                pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString;
8492                pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString;
8493            }
8494            pkg.mExtras = updatedPs;
8495
8496            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8497                    + pkg.codePath + " ignored: updated version " + updatedPs.versionCode
8498                    + " better than this " + pkg.getLongVersionCode());
8499        }
8500
8501        if (isUpdatedPkg) {
8502            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8503            scanFlags |= SCAN_AS_SYSTEM;
8504
8505            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8506            // flag set initially
8507            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8508                scanFlags |= SCAN_AS_PRIVILEGED;
8509            }
8510
8511            // An updated OEM app will not have the SCAN_AS_OEM
8512            // flag set initially
8513            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8514                scanFlags |= SCAN_AS_OEM;
8515            }
8516
8517            // An updated vendor app will not have the SCAN_AS_VENDOR
8518            // flag set initially
8519            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
8520                scanFlags |= SCAN_AS_VENDOR;
8521            }
8522        }
8523
8524        // Verify certificates against what was last scanned
8525        collectCertificatesLI(ps, pkg, parseFlags);
8526
8527        /*
8528         * A new system app appeared, but we already had a non-system one of the
8529         * same name installed earlier.
8530         */
8531        boolean shouldHideSystemApp = false;
8532        if (!isUpdatedPkg && ps != null
8533                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8534            /*
8535             * Check to make sure the signatures match first. If they don't,
8536             * wipe the installed application and its data.
8537             */
8538            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8539                    != PackageManager.SIGNATURE_MATCH) {
8540                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8541                        + " signatures don't match existing userdata copy; removing");
8542                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8543                        "scanPackageInternalLI")) {
8544                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8545                }
8546                ps = null;
8547            } else {
8548                /*
8549                 * If the newly-added system app is an older version than the
8550                 * already installed version, hide it. It will be scanned later
8551                 * and re-added like an update.
8552                 */
8553                if (pkg.getLongVersionCode() <= ps.versionCode) {
8554                    shouldHideSystemApp = true;
8555                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + pkg.codePath
8556                            + " but new version " + pkg.getLongVersionCode()
8557                            + " better than installed " + ps.versionCode + "; hiding system");
8558                } else {
8559                    /*
8560                     * The newly found system app is a newer version that the
8561                     * one previously installed. Simply remove the
8562                     * already-installed application and replace it with our own
8563                     * while keeping the application data.
8564                     */
8565                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8566                            + " reverting from " + ps.codePathString + ": new version "
8567                            + pkg.getLongVersionCode() + " better than installed "
8568                            + ps.versionCode);
8569                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8570                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8571                    synchronized (mInstallLock) {
8572                        args.cleanUpResourcesLI();
8573                    }
8574                }
8575            }
8576        }
8577
8578        // The apk is forward locked (not public) if its code and resources
8579        // are kept in different files. (except for app in either system or
8580        // vendor path).
8581        // TODO grab this value from PackageSettings
8582        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8583            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8584                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
8585            }
8586        }
8587
8588        final int userId = ((user == null) ? 0 : user.getIdentifier());
8589        if (ps != null && ps.getInstantApp(userId)) {
8590            scanFlags |= SCAN_AS_INSTANT_APP;
8591        }
8592        if (ps != null && ps.getVirtulalPreload(userId)) {
8593            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8594        }
8595
8596        // Note that we invoke the following method only if we are about to unpack an application
8597        PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8598                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8599
8600        /*
8601         * If the system app should be overridden by a previously installed
8602         * data, hide the system app now and let the /data/app scan pick it up
8603         * again.
8604         */
8605        if (shouldHideSystemApp) {
8606            synchronized (mPackages) {
8607                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8608            }
8609        }
8610
8611        return scannedPkg;
8612    }
8613
8614    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8615        // Derive the new package synthetic package name
8616        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8617                + pkg.staticSharedLibVersion);
8618    }
8619
8620    private static String fixProcessName(String defProcessName,
8621            String processName) {
8622        if (processName == null) {
8623            return defProcessName;
8624        }
8625        return processName;
8626    }
8627
8628    /**
8629     * Enforces that only the system UID or root's UID can call a method exposed
8630     * via Binder.
8631     *
8632     * @param message used as message if SecurityException is thrown
8633     * @throws SecurityException if the caller is not system or root
8634     */
8635    private static final void enforceSystemOrRoot(String message) {
8636        final int uid = Binder.getCallingUid();
8637        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8638            throw new SecurityException(message);
8639        }
8640    }
8641
8642    @Override
8643    public void performFstrimIfNeeded() {
8644        enforceSystemOrRoot("Only the system can request fstrim");
8645
8646        // Before everything else, see whether we need to fstrim.
8647        try {
8648            IStorageManager sm = PackageHelper.getStorageManager();
8649            if (sm != null) {
8650                boolean doTrim = false;
8651                final long interval = android.provider.Settings.Global.getLong(
8652                        mContext.getContentResolver(),
8653                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8654                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8655                if (interval > 0) {
8656                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8657                    if (timeSinceLast > interval) {
8658                        doTrim = true;
8659                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8660                                + "; running immediately");
8661                    }
8662                }
8663                if (doTrim) {
8664                    final boolean dexOptDialogShown;
8665                    synchronized (mPackages) {
8666                        dexOptDialogShown = mDexOptDialogShown;
8667                    }
8668                    if (!isFirstBoot() && dexOptDialogShown) {
8669                        try {
8670                            ActivityManager.getService().showBootMessage(
8671                                    mContext.getResources().getString(
8672                                            R.string.android_upgrading_fstrim), true);
8673                        } catch (RemoteException e) {
8674                        }
8675                    }
8676                    sm.runMaintenance();
8677                }
8678            } else {
8679                Slog.e(TAG, "storageManager service unavailable!");
8680            }
8681        } catch (RemoteException e) {
8682            // Can't happen; StorageManagerService is local
8683        }
8684    }
8685
8686    @Override
8687    public void updatePackagesIfNeeded() {
8688        enforceSystemOrRoot("Only the system can request package update");
8689
8690        // We need to re-extract after an OTA.
8691        boolean causeUpgrade = isUpgrade();
8692
8693        // First boot or factory reset.
8694        // Note: we also handle devices that are upgrading to N right now as if it is their
8695        //       first boot, as they do not have profile data.
8696        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8697
8698        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8699        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8700
8701        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8702            return;
8703        }
8704
8705        List<PackageParser.Package> pkgs;
8706        synchronized (mPackages) {
8707            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8708        }
8709
8710        final long startTime = System.nanoTime();
8711        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8712                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8713                    false /* bootComplete */);
8714
8715        final int elapsedTimeSeconds =
8716                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8717
8718        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8719        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8720        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8721        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8722        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8723    }
8724
8725    /*
8726     * Return the prebuilt profile path given a package base code path.
8727     */
8728    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8729        return pkg.baseCodePath + ".prof";
8730    }
8731
8732    /**
8733     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8734     * containing statistics about the invocation. The array consists of three elements,
8735     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8736     * and {@code numberOfPackagesFailed}.
8737     */
8738    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8739            final String compilerFilter, boolean bootComplete) {
8740
8741        int numberOfPackagesVisited = 0;
8742        int numberOfPackagesOptimized = 0;
8743        int numberOfPackagesSkipped = 0;
8744        int numberOfPackagesFailed = 0;
8745        final int numberOfPackagesToDexopt = pkgs.size();
8746
8747        for (PackageParser.Package pkg : pkgs) {
8748            numberOfPackagesVisited++;
8749
8750            boolean useProfileForDexopt = false;
8751
8752            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8753                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8754                // that are already compiled.
8755                File profileFile = new File(getPrebuildProfilePath(pkg));
8756                // Copy profile if it exists.
8757                if (profileFile.exists()) {
8758                    try {
8759                        // We could also do this lazily before calling dexopt in
8760                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8761                        // is that we don't have a good way to say "do this only once".
8762                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8763                                pkg.applicationInfo.uid, pkg.packageName)) {
8764                            Log.e(TAG, "Installer failed to copy system profile!");
8765                        } else {
8766                            // Disabled as this causes speed-profile compilation during first boot
8767                            // even if things are already compiled.
8768                            // useProfileForDexopt = true;
8769                        }
8770                    } catch (Exception e) {
8771                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8772                                e);
8773                    }
8774                } else {
8775                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8776                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8777                    // minimize the number off apps being speed-profile compiled during first boot.
8778                    // The other paths will not change the filter.
8779                    if (disabledPs != null && disabledPs.pkg.isStub) {
8780                        // The package is the stub one, remove the stub suffix to get the normal
8781                        // package and APK names.
8782                        String systemProfilePath =
8783                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8784                        profileFile = new File(systemProfilePath);
8785                        // If we have a profile for a compressed APK, copy it to the reference
8786                        // location.
8787                        // Note that copying the profile here will cause it to override the
8788                        // reference profile every OTA even though the existing reference profile
8789                        // may have more data. We can't copy during decompression since the
8790                        // directories are not set up at that point.
8791                        if (profileFile.exists()) {
8792                            try {
8793                                // We could also do this lazily before calling dexopt in
8794                                // PackageDexOptimizer to prevent this happening on first boot. The
8795                                // issue is that we don't have a good way to say "do this only
8796                                // once".
8797                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8798                                        pkg.applicationInfo.uid, pkg.packageName)) {
8799                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8800                                } else {
8801                                    useProfileForDexopt = true;
8802                                }
8803                            } catch (Exception e) {
8804                                Log.e(TAG, "Failed to copy profile " +
8805                                        profileFile.getAbsolutePath() + " ", e);
8806                            }
8807                        }
8808                    }
8809                }
8810            }
8811
8812            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8813                if (DEBUG_DEXOPT) {
8814                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8815                }
8816                numberOfPackagesSkipped++;
8817                continue;
8818            }
8819
8820            if (DEBUG_DEXOPT) {
8821                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8822                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8823            }
8824
8825            if (showDialog) {
8826                try {
8827                    ActivityManager.getService().showBootMessage(
8828                            mContext.getResources().getString(R.string.android_upgrading_apk,
8829                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8830                } catch (RemoteException e) {
8831                }
8832                synchronized (mPackages) {
8833                    mDexOptDialogShown = true;
8834                }
8835            }
8836
8837            String pkgCompilerFilter = compilerFilter;
8838            if (useProfileForDexopt) {
8839                // Use background dexopt mode to try and use the profile. Note that this does not
8840                // guarantee usage of the profile.
8841                pkgCompilerFilter =
8842                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8843                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8844            }
8845
8846            // checkProfiles is false to avoid merging profiles during boot which
8847            // might interfere with background compilation (b/28612421).
8848            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8849            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8850            // trade-off worth doing to save boot time work.
8851            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8852            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8853                    pkg.packageName,
8854                    pkgCompilerFilter,
8855                    dexoptFlags));
8856
8857            switch (primaryDexOptStaus) {
8858                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8859                    numberOfPackagesOptimized++;
8860                    break;
8861                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8862                    numberOfPackagesSkipped++;
8863                    break;
8864                case PackageDexOptimizer.DEX_OPT_FAILED:
8865                    numberOfPackagesFailed++;
8866                    break;
8867                default:
8868                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8869                    break;
8870            }
8871        }
8872
8873        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8874                numberOfPackagesFailed };
8875    }
8876
8877    @Override
8878    public void notifyPackageUse(String packageName, int reason) {
8879        synchronized (mPackages) {
8880            final int callingUid = Binder.getCallingUid();
8881            final int callingUserId = UserHandle.getUserId(callingUid);
8882            if (getInstantAppPackageName(callingUid) != null) {
8883                if (!isCallerSameApp(packageName, callingUid)) {
8884                    return;
8885                }
8886            } else {
8887                if (isInstantApp(packageName, callingUserId)) {
8888                    return;
8889                }
8890            }
8891            notifyPackageUseLocked(packageName, reason);
8892        }
8893    }
8894
8895    private void notifyPackageUseLocked(String packageName, int reason) {
8896        final PackageParser.Package p = mPackages.get(packageName);
8897        if (p == null) {
8898            return;
8899        }
8900        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8901    }
8902
8903    @Override
8904    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8905            List<String> classPaths, String loaderIsa) {
8906        int userId = UserHandle.getCallingUserId();
8907        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8908        if (ai == null) {
8909            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8910                + loadingPackageName + ", user=" + userId);
8911            return;
8912        }
8913        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8914    }
8915
8916    @Override
8917    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8918            IDexModuleRegisterCallback callback) {
8919        int userId = UserHandle.getCallingUserId();
8920        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8921        DexManager.RegisterDexModuleResult result;
8922        if (ai == null) {
8923            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8924                     " calling user. package=" + packageName + ", user=" + userId);
8925            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8926        } else {
8927            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8928        }
8929
8930        if (callback != null) {
8931            mHandler.post(() -> {
8932                try {
8933                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8934                } catch (RemoteException e) {
8935                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8936                }
8937            });
8938        }
8939    }
8940
8941    /**
8942     * Ask the package manager to perform a dex-opt with the given compiler filter.
8943     *
8944     * Note: exposed only for the shell command to allow moving packages explicitly to a
8945     *       definite state.
8946     */
8947    @Override
8948    public boolean performDexOptMode(String packageName,
8949            boolean checkProfiles, String targetCompilerFilter, boolean force,
8950            boolean bootComplete, String splitName) {
8951        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8952                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8953                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8954        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8955                splitName, flags));
8956    }
8957
8958    /**
8959     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8960     * secondary dex files belonging to the given package.
8961     *
8962     * Note: exposed only for the shell command to allow moving packages explicitly to a
8963     *       definite state.
8964     */
8965    @Override
8966    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8967            boolean force) {
8968        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8969                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8970                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8971                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8972        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8973    }
8974
8975    /*package*/ boolean performDexOpt(DexoptOptions options) {
8976        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8977            return false;
8978        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8979            return false;
8980        }
8981
8982        if (options.isDexoptOnlySecondaryDex()) {
8983            return mDexManager.dexoptSecondaryDex(options);
8984        } else {
8985            int dexoptStatus = performDexOptWithStatus(options);
8986            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8987        }
8988    }
8989
8990    /**
8991     * Perform dexopt on the given package and return one of following result:
8992     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8993     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8994     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8995     */
8996    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8997        return performDexOptTraced(options);
8998    }
8999
9000    private int performDexOptTraced(DexoptOptions options) {
9001        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9002        try {
9003            return performDexOptInternal(options);
9004        } finally {
9005            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9006        }
9007    }
9008
9009    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9010    // if the package can now be considered up to date for the given filter.
9011    private int performDexOptInternal(DexoptOptions options) {
9012        PackageParser.Package p;
9013        synchronized (mPackages) {
9014            p = mPackages.get(options.getPackageName());
9015            if (p == null) {
9016                // Package could not be found. Report failure.
9017                return PackageDexOptimizer.DEX_OPT_FAILED;
9018            }
9019            mPackageUsage.maybeWriteAsync(mPackages);
9020            mCompilerStats.maybeWriteAsync();
9021        }
9022        long callingId = Binder.clearCallingIdentity();
9023        try {
9024            synchronized (mInstallLock) {
9025                return performDexOptInternalWithDependenciesLI(p, options);
9026            }
9027        } finally {
9028            Binder.restoreCallingIdentity(callingId);
9029        }
9030    }
9031
9032    public ArraySet<String> getOptimizablePackages() {
9033        ArraySet<String> pkgs = new ArraySet<String>();
9034        synchronized (mPackages) {
9035            for (PackageParser.Package p : mPackages.values()) {
9036                if (PackageDexOptimizer.canOptimizePackage(p)) {
9037                    pkgs.add(p.packageName);
9038                }
9039            }
9040        }
9041        return pkgs;
9042    }
9043
9044    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9045            DexoptOptions options) {
9046        // Select the dex optimizer based on the force parameter.
9047        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9048        //       allocate an object here.
9049        PackageDexOptimizer pdo = options.isForce()
9050                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9051                : mPackageDexOptimizer;
9052
9053        // Dexopt all dependencies first. Note: we ignore the return value and march on
9054        // on errors.
9055        // Note that we are going to call performDexOpt on those libraries as many times as
9056        // they are referenced in packages. When we do a batch of performDexOpt (for example
9057        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9058        // and the first package that uses the library will dexopt it. The
9059        // others will see that the compiled code for the library is up to date.
9060        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9061        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9062        if (!deps.isEmpty()) {
9063            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9064                    options.getCompilerFilter(), options.getSplitName(),
9065                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9066            for (PackageParser.Package depPackage : deps) {
9067                // TODO: Analyze and investigate if we (should) profile libraries.
9068                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9069                        getOrCreateCompilerPackageStats(depPackage),
9070                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9071            }
9072        }
9073        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9074                getOrCreateCompilerPackageStats(p),
9075                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9076    }
9077
9078    /**
9079     * Reconcile the information we have about the secondary dex files belonging to
9080     * {@code packagName} and the actual dex files. For all dex files that were
9081     * deleted, update the internal records and delete the generated oat files.
9082     */
9083    @Override
9084    public void reconcileSecondaryDexFiles(String packageName) {
9085        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9086            return;
9087        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9088            return;
9089        }
9090        mDexManager.reconcileSecondaryDexFiles(packageName);
9091    }
9092
9093    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9094    // a reference there.
9095    /*package*/ DexManager getDexManager() {
9096        return mDexManager;
9097    }
9098
9099    /**
9100     * Execute the background dexopt job immediately.
9101     */
9102    @Override
9103    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9104        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9105            return false;
9106        }
9107        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9108    }
9109
9110    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9111        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9112                || p.usesStaticLibraries != null) {
9113            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9114            Set<String> collectedNames = new HashSet<>();
9115            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9116
9117            retValue.remove(p);
9118
9119            return retValue;
9120        } else {
9121            return Collections.emptyList();
9122        }
9123    }
9124
9125    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9126            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9127        if (!collectedNames.contains(p.packageName)) {
9128            collectedNames.add(p.packageName);
9129            collected.add(p);
9130
9131            if (p.usesLibraries != null) {
9132                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9133                        null, collected, collectedNames);
9134            }
9135            if (p.usesOptionalLibraries != null) {
9136                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9137                        null, collected, collectedNames);
9138            }
9139            if (p.usesStaticLibraries != null) {
9140                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9141                        p.usesStaticLibrariesVersions, collected, collectedNames);
9142            }
9143        }
9144    }
9145
9146    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9147            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9148        final int libNameCount = libs.size();
9149        for (int i = 0; i < libNameCount; i++) {
9150            String libName = libs.get(i);
9151            long version = (versions != null && versions.length == libNameCount)
9152                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9153            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9154            if (libPkg != null) {
9155                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9156            }
9157        }
9158    }
9159
9160    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9161        synchronized (mPackages) {
9162            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9163            if (libEntry != null) {
9164                return mPackages.get(libEntry.apk);
9165            }
9166            return null;
9167        }
9168    }
9169
9170    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9171        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9172        if (versionedLib == null) {
9173            return null;
9174        }
9175        return versionedLib.get(version);
9176    }
9177
9178    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9179        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9180                pkg.staticSharedLibName);
9181        if (versionedLib == null) {
9182            return null;
9183        }
9184        long previousLibVersion = -1;
9185        final int versionCount = versionedLib.size();
9186        for (int i = 0; i < versionCount; i++) {
9187            final long libVersion = versionedLib.keyAt(i);
9188            if (libVersion < pkg.staticSharedLibVersion) {
9189                previousLibVersion = Math.max(previousLibVersion, libVersion);
9190            }
9191        }
9192        if (previousLibVersion >= 0) {
9193            return versionedLib.get(previousLibVersion);
9194        }
9195        return null;
9196    }
9197
9198    public void shutdown() {
9199        mPackageUsage.writeNow(mPackages);
9200        mCompilerStats.writeNow();
9201        mDexManager.writePackageDexUsageNow();
9202    }
9203
9204    @Override
9205    public void dumpProfiles(String packageName) {
9206        PackageParser.Package pkg;
9207        synchronized (mPackages) {
9208            pkg = mPackages.get(packageName);
9209            if (pkg == null) {
9210                throw new IllegalArgumentException("Unknown package: " + packageName);
9211            }
9212        }
9213        /* Only the shell, root, or the app user should be able to dump profiles. */
9214        int callingUid = Binder.getCallingUid();
9215        if (callingUid != Process.SHELL_UID &&
9216            callingUid != Process.ROOT_UID &&
9217            callingUid != pkg.applicationInfo.uid) {
9218            throw new SecurityException("dumpProfiles");
9219        }
9220
9221        synchronized (mInstallLock) {
9222            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9223            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9224            try {
9225                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9226                String codePaths = TextUtils.join(";", allCodePaths);
9227                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9228            } catch (InstallerException e) {
9229                Slog.w(TAG, "Failed to dump profiles", e);
9230            }
9231            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9232        }
9233    }
9234
9235    @Override
9236    public void forceDexOpt(String packageName) {
9237        enforceSystemOrRoot("forceDexOpt");
9238
9239        PackageParser.Package pkg;
9240        synchronized (mPackages) {
9241            pkg = mPackages.get(packageName);
9242            if (pkg == null) {
9243                throw new IllegalArgumentException("Unknown package: " + packageName);
9244            }
9245        }
9246
9247        synchronized (mInstallLock) {
9248            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9249
9250            // Whoever is calling forceDexOpt wants a compiled package.
9251            // Don't use profiles since that may cause compilation to be skipped.
9252            final int res = performDexOptInternalWithDependenciesLI(
9253                    pkg,
9254                    new DexoptOptions(packageName,
9255                            getDefaultCompilerFilter(),
9256                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9257
9258            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9259            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9260                throw new IllegalStateException("Failed to dexopt: " + res);
9261            }
9262        }
9263    }
9264
9265    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9266        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9267            Slog.w(TAG, "Unable to update from " + oldPkg.name
9268                    + " to " + newPkg.packageName
9269                    + ": old package not in system partition");
9270            return false;
9271        } else if (mPackages.get(oldPkg.name) != null) {
9272            Slog.w(TAG, "Unable to update from " + oldPkg.name
9273                    + " to " + newPkg.packageName
9274                    + ": old package still exists");
9275            return false;
9276        }
9277        return true;
9278    }
9279
9280    void removeCodePathLI(File codePath) {
9281        if (codePath.isDirectory()) {
9282            try {
9283                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9284            } catch (InstallerException e) {
9285                Slog.w(TAG, "Failed to remove code path", e);
9286            }
9287        } else {
9288            codePath.delete();
9289        }
9290    }
9291
9292    private int[] resolveUserIds(int userId) {
9293        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9294    }
9295
9296    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9297        if (pkg == null) {
9298            Slog.wtf(TAG, "Package was null!", new Throwable());
9299            return;
9300        }
9301        clearAppDataLeafLIF(pkg, userId, flags);
9302        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9303        for (int i = 0; i < childCount; i++) {
9304            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9305        }
9306    }
9307
9308    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9309        final PackageSetting ps;
9310        synchronized (mPackages) {
9311            ps = mSettings.mPackages.get(pkg.packageName);
9312        }
9313        for (int realUserId : resolveUserIds(userId)) {
9314            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9315            try {
9316                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9317                        ceDataInode);
9318            } catch (InstallerException e) {
9319                Slog.w(TAG, String.valueOf(e));
9320            }
9321        }
9322    }
9323
9324    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9325        if (pkg == null) {
9326            Slog.wtf(TAG, "Package was null!", new Throwable());
9327            return;
9328        }
9329        destroyAppDataLeafLIF(pkg, userId, flags);
9330        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9331        for (int i = 0; i < childCount; i++) {
9332            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9333        }
9334    }
9335
9336    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9337        final PackageSetting ps;
9338        synchronized (mPackages) {
9339            ps = mSettings.mPackages.get(pkg.packageName);
9340        }
9341        for (int realUserId : resolveUserIds(userId)) {
9342            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9343            try {
9344                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9345                        ceDataInode);
9346            } catch (InstallerException e) {
9347                Slog.w(TAG, String.valueOf(e));
9348            }
9349            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9350        }
9351    }
9352
9353    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9354        if (pkg == null) {
9355            Slog.wtf(TAG, "Package was null!", new Throwable());
9356            return;
9357        }
9358        destroyAppProfilesLeafLIF(pkg);
9359        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9360        for (int i = 0; i < childCount; i++) {
9361            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9362        }
9363    }
9364
9365    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9366        try {
9367            mInstaller.destroyAppProfiles(pkg.packageName);
9368        } catch (InstallerException e) {
9369            Slog.w(TAG, String.valueOf(e));
9370        }
9371    }
9372
9373    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9374        if (pkg == null) {
9375            Slog.wtf(TAG, "Package was null!", new Throwable());
9376            return;
9377        }
9378        clearAppProfilesLeafLIF(pkg);
9379        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9380        for (int i = 0; i < childCount; i++) {
9381            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9382        }
9383    }
9384
9385    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9386        try {
9387            mInstaller.clearAppProfiles(pkg.packageName);
9388        } catch (InstallerException e) {
9389            Slog.w(TAG, String.valueOf(e));
9390        }
9391    }
9392
9393    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9394            long lastUpdateTime) {
9395        // Set parent install/update time
9396        PackageSetting ps = (PackageSetting) pkg.mExtras;
9397        if (ps != null) {
9398            ps.firstInstallTime = firstInstallTime;
9399            ps.lastUpdateTime = lastUpdateTime;
9400        }
9401        // Set children install/update time
9402        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9403        for (int i = 0; i < childCount; i++) {
9404            PackageParser.Package childPkg = pkg.childPackages.get(i);
9405            ps = (PackageSetting) childPkg.mExtras;
9406            if (ps != null) {
9407                ps.firstInstallTime = firstInstallTime;
9408                ps.lastUpdateTime = lastUpdateTime;
9409            }
9410        }
9411    }
9412
9413    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9414            SharedLibraryEntry file,
9415            PackageParser.Package changingLib) {
9416        if (file.path != null) {
9417            usesLibraryFiles.add(file.path);
9418            return;
9419        }
9420        PackageParser.Package p = mPackages.get(file.apk);
9421        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9422            // If we are doing this while in the middle of updating a library apk,
9423            // then we need to make sure to use that new apk for determining the
9424            // dependencies here.  (We haven't yet finished committing the new apk
9425            // to the package manager state.)
9426            if (p == null || p.packageName.equals(changingLib.packageName)) {
9427                p = changingLib;
9428            }
9429        }
9430        if (p != null) {
9431            usesLibraryFiles.addAll(p.getAllCodePaths());
9432            if (p.usesLibraryFiles != null) {
9433                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9434            }
9435        }
9436    }
9437
9438    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9439            PackageParser.Package changingLib) throws PackageManagerException {
9440        if (pkg == null) {
9441            return;
9442        }
9443        // The collection used here must maintain the order of addition (so
9444        // that libraries are searched in the correct order) and must have no
9445        // duplicates.
9446        Set<String> usesLibraryFiles = null;
9447        if (pkg.usesLibraries != null) {
9448            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9449                    null, null, pkg.packageName, changingLib, true,
9450                    pkg.applicationInfo.targetSdkVersion, null);
9451        }
9452        if (pkg.usesStaticLibraries != null) {
9453            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9454                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9455                    pkg.packageName, changingLib, true,
9456                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9457        }
9458        if (pkg.usesOptionalLibraries != null) {
9459            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9460                    null, null, pkg.packageName, changingLib, false,
9461                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9462        }
9463        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9464            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9465        } else {
9466            pkg.usesLibraryFiles = null;
9467        }
9468    }
9469
9470    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9471            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9472            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9473            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9474            throws PackageManagerException {
9475        final int libCount = requestedLibraries.size();
9476        for (int i = 0; i < libCount; i++) {
9477            final String libName = requestedLibraries.get(i);
9478            final long libVersion = requiredVersions != null ? requiredVersions[i]
9479                    : SharedLibraryInfo.VERSION_UNDEFINED;
9480            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9481            if (libEntry == null) {
9482                if (required) {
9483                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9484                            "Package " + packageName + " requires unavailable shared library "
9485                                    + libName + "; failing!");
9486                } else if (DEBUG_SHARED_LIBRARIES) {
9487                    Slog.i(TAG, "Package " + packageName
9488                            + " desires unavailable shared library "
9489                            + libName + "; ignoring!");
9490                }
9491            } else {
9492                if (requiredVersions != null && requiredCertDigests != null) {
9493                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9494                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9495                            "Package " + packageName + " requires unavailable static shared"
9496                                    + " library " + libName + " version "
9497                                    + libEntry.info.getLongVersion() + "; failing!");
9498                    }
9499
9500                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9501                    if (libPkg == null) {
9502                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9503                                "Package " + packageName + " requires unavailable static shared"
9504                                        + " library; failing!");
9505                    }
9506
9507                    final String[] expectedCertDigests = requiredCertDigests[i];
9508                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9509                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9510                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9511                            : PackageUtils.computeSignaturesSha256Digests(
9512                                    new Signature[]{libPkg.mSignatures[0]});
9513
9514                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9515                    // target O we don't parse the "additional-certificate" tags similarly
9516                    // how we only consider all certs only for apps targeting O (see above).
9517                    // Therefore, the size check is safe to make.
9518                    if (expectedCertDigests.length != libCertDigests.length) {
9519                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9520                                "Package " + packageName + " requires differently signed" +
9521                                        " static shared library; failing!");
9522                    }
9523
9524                    // Use a predictable order as signature order may vary
9525                    Arrays.sort(libCertDigests);
9526                    Arrays.sort(expectedCertDigests);
9527
9528                    final int certCount = libCertDigests.length;
9529                    for (int j = 0; j < certCount; j++) {
9530                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9531                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9532                                    "Package " + packageName + " requires differently signed" +
9533                                            " static shared library; failing!");
9534                        }
9535                    }
9536                }
9537
9538                if (outUsedLibraries == null) {
9539                    // Use LinkedHashSet to preserve the order of files added to
9540                    // usesLibraryFiles while eliminating duplicates.
9541                    outUsedLibraries = new LinkedHashSet<>();
9542                }
9543                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9544            }
9545        }
9546        return outUsedLibraries;
9547    }
9548
9549    private static boolean hasString(List<String> list, List<String> which) {
9550        if (list == null) {
9551            return false;
9552        }
9553        for (int i=list.size()-1; i>=0; i--) {
9554            for (int j=which.size()-1; j>=0; j--) {
9555                if (which.get(j).equals(list.get(i))) {
9556                    return true;
9557                }
9558            }
9559        }
9560        return false;
9561    }
9562
9563    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9564            PackageParser.Package changingPkg) {
9565        ArrayList<PackageParser.Package> res = null;
9566        for (PackageParser.Package pkg : mPackages.values()) {
9567            if (changingPkg != null
9568                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9569                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9570                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9571                            changingPkg.staticSharedLibName)) {
9572                return null;
9573            }
9574            if (res == null) {
9575                res = new ArrayList<>();
9576            }
9577            res.add(pkg);
9578            try {
9579                updateSharedLibrariesLPr(pkg, changingPkg);
9580            } catch (PackageManagerException e) {
9581                // If a system app update or an app and a required lib missing we
9582                // delete the package and for updated system apps keep the data as
9583                // it is better for the user to reinstall than to be in an limbo
9584                // state. Also libs disappearing under an app should never happen
9585                // - just in case.
9586                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9587                    final int flags = pkg.isUpdatedSystemApp()
9588                            ? PackageManager.DELETE_KEEP_DATA : 0;
9589                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9590                            flags , null, true, null);
9591                }
9592                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9593            }
9594        }
9595        return res;
9596    }
9597
9598    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9599            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9600            @Nullable UserHandle user) throws PackageManagerException {
9601        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9602        // If the package has children and this is the first dive in the function
9603        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9604        // whether all packages (parent and children) would be successfully scanned
9605        // before the actual scan since scanning mutates internal state and we want
9606        // to atomically install the package and its children.
9607        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9608            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9609                scanFlags |= SCAN_CHECK_ONLY;
9610            }
9611        } else {
9612            scanFlags &= ~SCAN_CHECK_ONLY;
9613        }
9614
9615        final PackageParser.Package scannedPkg;
9616        try {
9617            // Scan the parent
9618            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9619            // Scan the children
9620            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9621            for (int i = 0; i < childCount; i++) {
9622                PackageParser.Package childPkg = pkg.childPackages.get(i);
9623                scanPackageNewLI(childPkg, parseFlags,
9624                        scanFlags, currentTime, user);
9625            }
9626        } finally {
9627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9628        }
9629
9630        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9631            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9632        }
9633
9634        return scannedPkg;
9635    }
9636
9637    /** The result of a package scan. */
9638    private static class ScanResult {
9639        /** Whether or not the package scan was successful */
9640        public final boolean success;
9641        /**
9642         * The final package settings. This may be the same object passed in
9643         * the {@link ScanRequest}, but, with modified values.
9644         */
9645        @Nullable public final PackageSetting pkgSetting;
9646        /** ABI code paths that have changed in the package scan */
9647        @Nullable public final List<String> changedAbiCodePath;
9648        public ScanResult(
9649                boolean success,
9650                @Nullable PackageSetting pkgSetting,
9651                @Nullable List<String> changedAbiCodePath) {
9652            this.success = success;
9653            this.pkgSetting = pkgSetting;
9654            this.changedAbiCodePath = changedAbiCodePath;
9655        }
9656    }
9657
9658    /** A package to be scanned */
9659    private static class ScanRequest {
9660        /** The parsed package */
9661        @NonNull public final PackageParser.Package pkg;
9662        /** Shared user settings, if the package has a shared user */
9663        @Nullable public final SharedUserSetting sharedUserSetting;
9664        /**
9665         * Package settings of the currently installed version.
9666         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9667         * during scan.
9668         */
9669        @Nullable public final PackageSetting pkgSetting;
9670        /** A copy of the settings for the currently installed version */
9671        @Nullable public final PackageSetting oldPkgSetting;
9672        /** Package settings for the disabled version on the /system partition */
9673        @Nullable public final PackageSetting disabledPkgSetting;
9674        /** Package settings for the installed version under its original package name */
9675        @Nullable public final PackageSetting originalPkgSetting;
9676        /** The real package name of a renamed application */
9677        @Nullable public final String realPkgName;
9678        public final @ParseFlags int parseFlags;
9679        public final @ScanFlags int scanFlags;
9680        /** The user for which the package is being scanned */
9681        @Nullable public final UserHandle user;
9682        /** Whether or not the platform package is being scanned */
9683        public final boolean isPlatformPackage;
9684        public ScanRequest(
9685                @NonNull PackageParser.Package pkg,
9686                @Nullable SharedUserSetting sharedUserSetting,
9687                @Nullable PackageSetting pkgSetting,
9688                @Nullable PackageSetting disabledPkgSetting,
9689                @Nullable PackageSetting originalPkgSetting,
9690                @Nullable String realPkgName,
9691                @ParseFlags int parseFlags,
9692                @ScanFlags int scanFlags,
9693                boolean isPlatformPackage,
9694                @Nullable UserHandle user) {
9695            this.pkg = pkg;
9696            this.pkgSetting = pkgSetting;
9697            this.sharedUserSetting = sharedUserSetting;
9698            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9699            this.disabledPkgSetting = disabledPkgSetting;
9700            this.originalPkgSetting = originalPkgSetting;
9701            this.realPkgName = realPkgName;
9702            this.parseFlags = parseFlags;
9703            this.scanFlags = scanFlags;
9704            this.isPlatformPackage = isPlatformPackage;
9705            this.user = user;
9706        }
9707    }
9708
9709    @GuardedBy("mInstallLock")
9710    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9711            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9712            @Nullable UserHandle user) throws PackageManagerException {
9713
9714        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9715        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9716        if (realPkgName != null) {
9717            ensurePackageRenamed(pkg, renamedPkgName);
9718        }
9719        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9720        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9721        final PackageSetting disabledPkgSetting =
9722                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9723
9724        if (mTransferedPackages.contains(pkg.packageName)) {
9725            Slog.w(TAG, "Package " + pkg.packageName
9726                    + " was transferred to another, but its .apk remains");
9727        }
9728
9729        synchronized (mPackages) {
9730            applyPolicy(pkg, parseFlags, scanFlags);
9731            assertPackageIsValid(pkg, parseFlags, scanFlags);
9732
9733            SharedUserSetting sharedUserSetting = null;
9734            if (pkg.mSharedUserId != null) {
9735                // SIDE EFFECTS; may potentially allocate a new shared user
9736                sharedUserSetting = mSettings.getSharedUserLPw(
9737                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9738                if (DEBUG_PACKAGE_SCANNING) {
9739                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9740                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9741                                + " (uid=" + sharedUserSetting.userId + "):"
9742                                + " packages=" + sharedUserSetting.packages);
9743                }
9744            }
9745
9746            boolean scanSucceeded = false;
9747            try {
9748                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9749                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9750                        (pkg == mPlatformPackage), user);
9751                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9752                if (result.success) {
9753                    commitScanResultsLocked(request, result);
9754                }
9755                scanSucceeded = true;
9756            } finally {
9757                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9758                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9759                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9760                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9761                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9762                  }
9763            }
9764        }
9765        return pkg;
9766    }
9767
9768    /**
9769     * Commits the package scan and modifies system state.
9770     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9771     * of committing the package, leaving the system in an inconsistent state.
9772     * This needs to be fixed so, once we get to this point, no errors are
9773     * possible and the system is not left in an inconsistent state.
9774     */
9775    @GuardedBy("mPackages")
9776    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9777            throws PackageManagerException {
9778        final PackageParser.Package pkg = request.pkg;
9779        final @ParseFlags int parseFlags = request.parseFlags;
9780        final @ScanFlags int scanFlags = request.scanFlags;
9781        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9782        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9783        final UserHandle user = request.user;
9784        final String realPkgName = request.realPkgName;
9785        final PackageSetting pkgSetting = result.pkgSetting;
9786        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9787        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9788
9789        if (newPkgSettingCreated) {
9790            if (originalPkgSetting != null) {
9791                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9792            }
9793            // THROWS: when we can't allocate a user id. add call to check if there's
9794            // enough space to ensure we won't throw; otherwise, don't modify state
9795            mSettings.addUserToSettingLPw(pkgSetting);
9796
9797            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
9798                mTransferedPackages.add(originalPkgSetting.name);
9799            }
9800        }
9801        // TODO(toddke): Consider a method specifically for modifying the Package object
9802        // post scan; or, moving this stuff out of the Package object since it has nothing
9803        // to do with the package on disk.
9804        // We need to have this here because addUserToSettingLPw() is sometimes responsible
9805        // for creating the application ID. If we did this earlier, we would be saving the
9806        // correct ID.
9807        pkg.applicationInfo.uid = pkgSetting.appId;
9808
9809        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9810
9811        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
9812            mTransferedPackages.add(pkg.packageName);
9813        }
9814
9815        // THROWS: when requested libraries that can't be found. it only changes
9816        // the state of the passed in pkg object, so, move to the top of the method
9817        // and allow it to abort
9818        if ((scanFlags & SCAN_BOOTING) == 0
9819                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9820            // Check all shared libraries and map to their actual file path.
9821            // We only do this here for apps not on a system dir, because those
9822            // are the only ones that can fail an install due to this.  We
9823            // will take care of the system apps by updating all of their
9824            // library paths after the scan is done. Also during the initial
9825            // scan don't update any libs as we do this wholesale after all
9826            // apps are scanned to avoid dependency based scanning.
9827            updateSharedLibrariesLPr(pkg, null);
9828        }
9829
9830        // All versions of a static shared library are referenced with the same
9831        // package name. Internally, we use a synthetic package name to allow
9832        // multiple versions of the same shared library to be installed. So,
9833        // we need to generate the synthetic package name of the latest shared
9834        // library in order to compare signatures.
9835        PackageSetting signatureCheckPs = pkgSetting;
9836        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9837            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9838            if (libraryEntry != null) {
9839                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9840            }
9841        }
9842
9843        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9844        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9845            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9846                // We just determined the app is signed correctly, so bring
9847                // over the latest parsed certs.
9848                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9849            } else {
9850                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9851                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9852                            "Package " + pkg.packageName + " upgrade keys do not match the "
9853                                    + "previously installed version");
9854                } else {
9855                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9856                    String msg = "System package " + pkg.packageName
9857                            + " signature changed; retaining data.";
9858                    reportSettingsProblem(Log.WARN, msg);
9859                }
9860            }
9861        } else {
9862            try {
9863                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9864                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9865                final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9866                        compareCompat, compareRecover);
9867                // The new KeySets will be re-added later in the scanning process.
9868                if (compatMatch) {
9869                    synchronized (mPackages) {
9870                        ksms.removeAppKeySetDataLPw(pkg.packageName);
9871                    }
9872                }
9873                // We just determined the app is signed correctly, so bring
9874                // over the latest parsed certs.
9875                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9876            } catch (PackageManagerException e) {
9877                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9878                    throw e;
9879                }
9880                // The signature has changed, but this package is in the system
9881                // image...  let's recover!
9882                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9883                // However...  if this package is part of a shared user, but it
9884                // doesn't match the signature of the shared user, let's fail.
9885                // What this means is that you can't change the signatures
9886                // associated with an overall shared user, which doesn't seem all
9887                // that unreasonable.
9888                if (signatureCheckPs.sharedUser != null) {
9889                    if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9890                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9891                        throw new PackageManagerException(
9892                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9893                                "Signature mismatch for shared user: "
9894                                        + pkgSetting.sharedUser);
9895                    }
9896                }
9897                // File a report about this.
9898                String msg = "System package " + pkg.packageName
9899                        + " signature changed; retaining data.";
9900                reportSettingsProblem(Log.WARN, msg);
9901            }
9902        }
9903
9904        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9905            // This package wants to adopt ownership of permissions from
9906            // another package.
9907            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9908                final String origName = pkg.mAdoptPermissions.get(i);
9909                final PackageSetting orig = mSettings.getPackageLPr(origName);
9910                if (orig != null) {
9911                    if (verifyPackageUpdateLPr(orig, pkg)) {
9912                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
9913                                + pkg.packageName);
9914                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9915                    }
9916                }
9917            }
9918        }
9919
9920        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
9921            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
9922                final String codePathString = changedAbiCodePath.get(i);
9923                try {
9924                    mInstaller.rmdex(codePathString,
9925                            getDexCodeInstructionSet(getPreferredInstructionSet()));
9926                } catch (InstallerException ignored) {
9927                }
9928            }
9929        }
9930
9931        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9932            if (oldPkgSetting != null) {
9933                synchronized (mPackages) {
9934                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
9935                }
9936            }
9937        } else {
9938            final int userId = user == null ? 0 : user.getIdentifier();
9939            // Modify state for the given package setting
9940            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9941                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9942            if (pkgSetting.getInstantApp(userId)) {
9943                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9944            }
9945        }
9946    }
9947
9948    /**
9949     * Returns the "real" name of the package.
9950     * <p>This may differ from the package's actual name if the application has already
9951     * been installed under one of this package's original names.
9952     */
9953    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
9954            @Nullable String renamedPkgName) {
9955        if (pkg.mOriginalPackages == null || !pkg.mOriginalPackages.contains(renamedPkgName)) {
9956            return null;
9957        }
9958        return pkg.mRealPackage;
9959    }
9960
9961    /**
9962     * Returns the original package setting.
9963     * <p>A package can migrate its name during an update. In this scenario, a package
9964     * designates a set of names that it considers as one of its original names.
9965     * <p>An original package must be signed identically and it must have the same
9966     * shared user [if any].
9967     */
9968    @GuardedBy("mPackages")
9969    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
9970            @Nullable String renamedPkgName) {
9971        if (pkg.mOriginalPackages == null || pkg.mOriginalPackages.contains(renamedPkgName)) {
9972            return null;
9973        }
9974        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
9975            final PackageSetting originalPs =
9976                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
9977            if (originalPs != null) {
9978                // the package is already installed under its original name...
9979                // but, should we use it?
9980                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
9981                    // the new package is incompatible with the original
9982                    continue;
9983                } else if (originalPs.sharedUser != null) {
9984                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
9985                        // the shared user id is incompatible with the original
9986                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
9987                                + " to " + pkg.packageName + ": old uid "
9988                                + originalPs.sharedUser.name
9989                                + " differs from " + pkg.mSharedUserId);
9990                        continue;
9991                    }
9992                    // TODO: Add case when shared user id is added [b/28144775]
9993                } else {
9994                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9995                            + pkg.packageName + " to old name " + originalPs.name);
9996                }
9997                return originalPs;
9998            }
9999        }
10000        return null;
10001    }
10002
10003    /**
10004     * Renames the package if it was installed under a different name.
10005     * <p>When we've already installed the package under an original name, update
10006     * the new package so we can continue to have the old name.
10007     */
10008    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10009            @NonNull String renamedPackageName) {
10010        if (pkg.mOriginalPackages == null
10011                || !pkg.mOriginalPackages.contains(renamedPackageName)
10012                || pkg.packageName.equals(renamedPackageName)) {
10013            return;
10014        }
10015        pkg.setPackageName(renamedPackageName);
10016    }
10017
10018    /**
10019     * Just scans the package without any side effects.
10020     * <p>Not entirely true at the moment. There is still one side effect -- this
10021     * method potentially modifies a live {@link PackageSetting} object representing
10022     * the package being scanned. This will be resolved in the future.
10023     *
10024     * @param request Information about the package to be scanned
10025     * @param isUnderFactoryTest Whether or not the device is under factory test
10026     * @param currentTime The current time, in millis
10027     * @return The results of the scan
10028     */
10029    @GuardedBy("mInstallLock")
10030    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10031            boolean isUnderFactoryTest, long currentTime)
10032                    throws PackageManagerException {
10033        final PackageParser.Package pkg = request.pkg;
10034        PackageSetting pkgSetting = request.pkgSetting;
10035        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10036        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10037        final @ParseFlags int parseFlags = request.parseFlags;
10038        final @ScanFlags int scanFlags = request.scanFlags;
10039        final String realPkgName = request.realPkgName;
10040        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10041        final UserHandle user = request.user;
10042        final boolean isPlatformPackage = request.isPlatformPackage;
10043
10044        List<String> changedAbiCodePath = null;
10045
10046        if (DEBUG_PACKAGE_SCANNING) {
10047            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10048                Log.d(TAG, "Scanning package " + pkg.packageName);
10049        }
10050
10051        if (Build.IS_DEBUGGABLE &&
10052                pkg.isPrivileged() &&
10053                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10054            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10055        }
10056
10057        // Initialize package source and resource directories
10058        final File scanFile = new File(pkg.codePath);
10059        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10060        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10061
10062        // We keep references to the derived CPU Abis from settings in oder to reuse
10063        // them in the case where we're not upgrading or booting for the first time.
10064        String primaryCpuAbiFromSettings = null;
10065        String secondaryCpuAbiFromSettings = null;
10066        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10067
10068        if (!needToDeriveAbi) {
10069            if (pkgSetting != null) {
10070                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10071                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10072            } else {
10073                // Re-scanning a system package after uninstalling updates; need to derive ABI
10074                needToDeriveAbi = true;
10075            }
10076        }
10077
10078        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10079            PackageManagerService.reportSettingsProblem(Log.WARN,
10080                    "Package " + pkg.packageName + " shared user changed from "
10081                            + (pkgSetting.sharedUser != null
10082                            ? pkgSetting.sharedUser.name : "<nothing>")
10083                            + " to "
10084                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10085                            + "; replacing with new");
10086            pkgSetting = null;
10087        }
10088
10089        String[] usesStaticLibraries = null;
10090        if (pkg.usesStaticLibraries != null) {
10091            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10092            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10093        }
10094
10095        final boolean createNewPackage = (pkgSetting == null);
10096        if (createNewPackage) {
10097            final String parentPackageName = (pkg.parentPackage != null)
10098                    ? pkg.parentPackage.packageName : null;
10099            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10100            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10101            // REMOVE SharedUserSetting from method; update in a separate call
10102            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10103                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10104                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10105                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10106                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10107                    user, true /*allowInstall*/, instantApp, virtualPreload,
10108                    parentPackageName, pkg.getChildPackageNames(),
10109                    UserManagerService.getInstance(), usesStaticLibraries,
10110                    pkg.usesStaticLibrariesVersions);
10111        } else {
10112            // REMOVE SharedUserSetting from method; update in a separate call.
10113            //
10114            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10115            // secondaryCpuAbi are not known at this point so we always update them
10116            // to null here, only to reset them at a later point.
10117            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10118                    destCodeFile, pkg.applicationInfo.nativeLibraryDir,
10119                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10120                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10121                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10122                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10123        }
10124        if (createNewPackage && originalPkgSetting != null) {
10125            // If we are first transitioning from an original package,
10126            // fix up the new package's name now.  We need to do this after
10127            // looking up the package under its new name, so getPackageLP
10128            // can take care of fiddling things correctly.
10129            pkg.setPackageName(originalPkgSetting.name);
10130
10131            // File a report about this.
10132            String msg = "New package " + pkgSetting.realName
10133                    + " renamed to replace old package " + pkgSetting.name;
10134            reportSettingsProblem(Log.WARN, msg);
10135        }
10136
10137        if (disabledPkgSetting != null) {
10138            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10139        }
10140
10141        SELinuxMMAC.assignSeInfoValue(pkg);
10142
10143        pkg.mExtras = pkgSetting;
10144        pkg.applicationInfo.processName = fixProcessName(
10145                pkg.applicationInfo.packageName,
10146                pkg.applicationInfo.processName);
10147
10148        if (!isPlatformPackage) {
10149            // Get all of our default paths setup
10150            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10151        }
10152
10153        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10154
10155        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10156            if (needToDeriveAbi) {
10157                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10158                final boolean extractNativeLibs = !pkg.isLibrary();
10159                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10160                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10161
10162                // Some system apps still use directory structure for native libraries
10163                // in which case we might end up not detecting abi solely based on apk
10164                // structure. Try to detect abi based on directory structure.
10165                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10166                        pkg.applicationInfo.primaryCpuAbi == null) {
10167                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10168                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10169                }
10170            } else {
10171                // This is not a first boot or an upgrade, don't bother deriving the
10172                // ABI during the scan. Instead, trust the value that was stored in the
10173                // package setting.
10174                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10175                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10176
10177                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10178
10179                if (DEBUG_ABI_SELECTION) {
10180                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10181                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10182                            pkg.applicationInfo.secondaryCpuAbi);
10183                }
10184            }
10185        } else {
10186            if ((scanFlags & SCAN_MOVE) != 0) {
10187                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10188                // but we already have this packages package info in the PackageSetting. We just
10189                // use that and derive the native library path based on the new codepath.
10190                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10191                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10192            }
10193
10194            // Set native library paths again. For moves, the path will be updated based on the
10195            // ABIs we've determined above. For non-moves, the path will be updated based on the
10196            // ABIs we determined during compilation, but the path will depend on the final
10197            // package path (after the rename away from the stage path).
10198            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10199        }
10200
10201        // This is a special case for the "system" package, where the ABI is
10202        // dictated by the zygote configuration (and init.rc). We should keep track
10203        // of this ABI so that we can deal with "normal" applications that run under
10204        // the same UID correctly.
10205        if (isPlatformPackage) {
10206            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10207                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10208        }
10209
10210        // If there's a mismatch between the abi-override in the package setting
10211        // and the abiOverride specified for the install. Warn about this because we
10212        // would've already compiled the app without taking the package setting into
10213        // account.
10214        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10215            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10216                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10217                        " for package " + pkg.packageName);
10218            }
10219        }
10220
10221        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10222        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10223        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10224
10225        // Copy the derived override back to the parsed package, so that we can
10226        // update the package settings accordingly.
10227        pkg.cpuAbiOverride = cpuAbiOverride;
10228
10229        if (DEBUG_ABI_SELECTION) {
10230            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10231                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10232                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10233        }
10234
10235        // Push the derived path down into PackageSettings so we know what to
10236        // clean up at uninstall time.
10237        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10238
10239        if (DEBUG_ABI_SELECTION) {
10240            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10241                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10242                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10243        }
10244
10245        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10246            // We don't do this here during boot because we can do it all
10247            // at once after scanning all existing packages.
10248            //
10249            // We also do this *before* we perform dexopt on this package, so that
10250            // we can avoid redundant dexopts, and also to make sure we've got the
10251            // code and package path correct.
10252            changedAbiCodePath =
10253                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10254        }
10255
10256        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10257                android.Manifest.permission.FACTORY_TEST)) {
10258            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10259        }
10260
10261        if (isSystemApp(pkg)) {
10262            pkgSetting.isOrphaned = true;
10263        }
10264
10265        // Take care of first install / last update times.
10266        final long scanFileTime = getLastModifiedTime(pkg);
10267        if (currentTime != 0) {
10268            if (pkgSetting.firstInstallTime == 0) {
10269                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10270            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10271                pkgSetting.lastUpdateTime = currentTime;
10272            }
10273        } else if (pkgSetting.firstInstallTime == 0) {
10274            // We need *something*.  Take time time stamp of the file.
10275            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10276        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10277            if (scanFileTime != pkgSetting.timeStamp) {
10278                // A package on the system image has changed; consider this
10279                // to be an update.
10280                pkgSetting.lastUpdateTime = scanFileTime;
10281            }
10282        }
10283        pkgSetting.setTimeStamp(scanFileTime);
10284
10285        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10286    }
10287
10288    /**
10289     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10290     */
10291    private static boolean apkHasCode(String fileName) {
10292        StrictJarFile jarFile = null;
10293        try {
10294            jarFile = new StrictJarFile(fileName,
10295                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10296            return jarFile.findEntry("classes.dex") != null;
10297        } catch (IOException ignore) {
10298        } finally {
10299            try {
10300                if (jarFile != null) {
10301                    jarFile.close();
10302                }
10303            } catch (IOException ignore) {}
10304        }
10305        return false;
10306    }
10307
10308    /**
10309     * Enforces code policy for the package. This ensures that if an APK has
10310     * declared hasCode="true" in its manifest that the APK actually contains
10311     * code.
10312     *
10313     * @throws PackageManagerException If bytecode could not be found when it should exist
10314     */
10315    private static void assertCodePolicy(PackageParser.Package pkg)
10316            throws PackageManagerException {
10317        final boolean shouldHaveCode =
10318                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10319        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10320            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10321                    "Package " + pkg.baseCodePath + " code is missing");
10322        }
10323
10324        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10325            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10326                final boolean splitShouldHaveCode =
10327                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10328                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10329                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10330                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10331                }
10332            }
10333        }
10334    }
10335
10336    /**
10337     * Applies policy to the parsed package based upon the given policy flags.
10338     * Ensures the package is in a good state.
10339     * <p>
10340     * Implementation detail: This method must NOT have any side effect. It would
10341     * ideally be static, but, it requires locks to read system state.
10342     */
10343    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10344            final @ScanFlags int scanFlags) {
10345        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10346            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10347            if (pkg.applicationInfo.isDirectBootAware()) {
10348                // we're direct boot aware; set for all components
10349                for (PackageParser.Service s : pkg.services) {
10350                    s.info.encryptionAware = s.info.directBootAware = true;
10351                }
10352                for (PackageParser.Provider p : pkg.providers) {
10353                    p.info.encryptionAware = p.info.directBootAware = true;
10354                }
10355                for (PackageParser.Activity a : pkg.activities) {
10356                    a.info.encryptionAware = a.info.directBootAware = true;
10357                }
10358                for (PackageParser.Activity r : pkg.receivers) {
10359                    r.info.encryptionAware = r.info.directBootAware = true;
10360                }
10361            }
10362            if (compressedFileExists(pkg.codePath)) {
10363                pkg.isStub = true;
10364            }
10365        } else {
10366            // non system apps can't be flagged as core
10367            pkg.coreApp = false;
10368            // clear flags not applicable to regular apps
10369            pkg.applicationInfo.flags &=
10370                    ~ApplicationInfo.FLAG_PERSISTENT;
10371            pkg.applicationInfo.privateFlags &=
10372                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10373            pkg.applicationInfo.privateFlags &=
10374                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10375            // clear protected broadcasts
10376            pkg.protectedBroadcasts = null;
10377            // cap permission priorities
10378            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10379                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10380                    pkg.permissionGroups.get(i).info.priority = 0;
10381                }
10382            }
10383        }
10384        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10385            // ignore export request for single user receivers
10386            if (pkg.receivers != null) {
10387                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10388                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10389                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10390                        receiver.info.exported = false;
10391                    }
10392                }
10393            }
10394            // ignore export request for single user services
10395            if (pkg.services != null) {
10396                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10397                    final PackageParser.Service service = pkg.services.get(i);
10398                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10399                        service.info.exported = false;
10400                    }
10401                }
10402            }
10403            // ignore export request for single user providers
10404            if (pkg.providers != null) {
10405                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10406                    final PackageParser.Provider provider = pkg.providers.get(i);
10407                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10408                        provider.info.exported = false;
10409                    }
10410                }
10411            }
10412        }
10413        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10414
10415        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10416            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10417        }
10418
10419        if ((scanFlags & SCAN_AS_OEM) != 0) {
10420            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10421        }
10422
10423        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10424            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10425        }
10426
10427        if (!isSystemApp(pkg)) {
10428            // Only system apps can use these features.
10429            pkg.mOriginalPackages = null;
10430            pkg.mRealPackage = null;
10431            pkg.mAdoptPermissions = null;
10432        }
10433    }
10434
10435    /**
10436     * Asserts the parsed package is valid according to the given policy. If the
10437     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10438     * <p>
10439     * Implementation detail: This method must NOT have any side effects. It would
10440     * ideally be static, but, it requires locks to read system state.
10441     *
10442     * @throws PackageManagerException If the package fails any of the validation checks
10443     */
10444    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10445            final @ScanFlags int scanFlags)
10446                    throws PackageManagerException {
10447        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10448            assertCodePolicy(pkg);
10449        }
10450
10451        if (pkg.applicationInfo.getCodePath() == null ||
10452                pkg.applicationInfo.getResourcePath() == null) {
10453            // Bail out. The resource and code paths haven't been set.
10454            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10455                    "Code and resource paths haven't been set correctly");
10456        }
10457
10458        // Make sure we're not adding any bogus keyset info
10459        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10460        ksms.assertScannedPackageValid(pkg);
10461
10462        synchronized (mPackages) {
10463            // The special "android" package can only be defined once
10464            if (pkg.packageName.equals("android")) {
10465                if (mAndroidApplication != null) {
10466                    Slog.w(TAG, "*************************************************");
10467                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10468                    Slog.w(TAG, " codePath=" + pkg.codePath);
10469                    Slog.w(TAG, "*************************************************");
10470                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10471                            "Core android package being redefined.  Skipping.");
10472                }
10473            }
10474
10475            // A package name must be unique; don't allow duplicates
10476            if (mPackages.containsKey(pkg.packageName)) {
10477                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10478                        "Application package " + pkg.packageName
10479                        + " already installed.  Skipping duplicate.");
10480            }
10481
10482            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10483                // Static libs have a synthetic package name containing the version
10484                // but we still want the base name to be unique.
10485                if (mPackages.containsKey(pkg.manifestPackageName)) {
10486                    throw new PackageManagerException(
10487                            "Duplicate static shared lib provider package");
10488                }
10489
10490                // Static shared libraries should have at least O target SDK
10491                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10492                    throw new PackageManagerException(
10493                            "Packages declaring static-shared libs must target O SDK or higher");
10494                }
10495
10496                // Package declaring static a shared lib cannot be instant apps
10497                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10498                    throw new PackageManagerException(
10499                            "Packages declaring static-shared libs cannot be instant apps");
10500                }
10501
10502                // Package declaring static a shared lib cannot be renamed since the package
10503                // name is synthetic and apps can't code around package manager internals.
10504                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10505                    throw new PackageManagerException(
10506                            "Packages declaring static-shared libs cannot be renamed");
10507                }
10508
10509                // Package declaring static a shared lib cannot declare child packages
10510                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10511                    throw new PackageManagerException(
10512                            "Packages declaring static-shared libs cannot have child packages");
10513                }
10514
10515                // Package declaring static a shared lib cannot declare dynamic libs
10516                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10517                    throw new PackageManagerException(
10518                            "Packages declaring static-shared libs cannot declare dynamic libs");
10519                }
10520
10521                // Package declaring static a shared lib cannot declare shared users
10522                if (pkg.mSharedUserId != null) {
10523                    throw new PackageManagerException(
10524                            "Packages declaring static-shared libs cannot declare shared users");
10525                }
10526
10527                // Static shared libs cannot declare activities
10528                if (!pkg.activities.isEmpty()) {
10529                    throw new PackageManagerException(
10530                            "Static shared libs cannot declare activities");
10531                }
10532
10533                // Static shared libs cannot declare services
10534                if (!pkg.services.isEmpty()) {
10535                    throw new PackageManagerException(
10536                            "Static shared libs cannot declare services");
10537                }
10538
10539                // Static shared libs cannot declare providers
10540                if (!pkg.providers.isEmpty()) {
10541                    throw new PackageManagerException(
10542                            "Static shared libs cannot declare content providers");
10543                }
10544
10545                // Static shared libs cannot declare receivers
10546                if (!pkg.receivers.isEmpty()) {
10547                    throw new PackageManagerException(
10548                            "Static shared libs cannot declare broadcast receivers");
10549                }
10550
10551                // Static shared libs cannot declare permission groups
10552                if (!pkg.permissionGroups.isEmpty()) {
10553                    throw new PackageManagerException(
10554                            "Static shared libs cannot declare permission groups");
10555                }
10556
10557                // Static shared libs cannot declare permissions
10558                if (!pkg.permissions.isEmpty()) {
10559                    throw new PackageManagerException(
10560                            "Static shared libs cannot declare permissions");
10561                }
10562
10563                // Static shared libs cannot declare protected broadcasts
10564                if (pkg.protectedBroadcasts != null) {
10565                    throw new PackageManagerException(
10566                            "Static shared libs cannot declare protected broadcasts");
10567                }
10568
10569                // Static shared libs cannot be overlay targets
10570                if (pkg.mOverlayTarget != null) {
10571                    throw new PackageManagerException(
10572                            "Static shared libs cannot be overlay targets");
10573                }
10574
10575                // The version codes must be ordered as lib versions
10576                long minVersionCode = Long.MIN_VALUE;
10577                long maxVersionCode = Long.MAX_VALUE;
10578
10579                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10580                        pkg.staticSharedLibName);
10581                if (versionedLib != null) {
10582                    final int versionCount = versionedLib.size();
10583                    for (int i = 0; i < versionCount; i++) {
10584                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10585                        final long libVersionCode = libInfo.getDeclaringPackage()
10586                                .getLongVersionCode();
10587                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10588                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10589                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10590                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10591                        } else {
10592                            minVersionCode = maxVersionCode = libVersionCode;
10593                            break;
10594                        }
10595                    }
10596                }
10597                if (pkg.getLongVersionCode() < minVersionCode
10598                        || pkg.getLongVersionCode() > maxVersionCode) {
10599                    throw new PackageManagerException("Static shared"
10600                            + " lib version codes must be ordered as lib versions");
10601                }
10602            }
10603
10604            // Only privileged apps and updated privileged apps can add child packages.
10605            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10606                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10607                    throw new PackageManagerException("Only privileged apps can add child "
10608                            + "packages. Ignoring package " + pkg.packageName);
10609                }
10610                final int childCount = pkg.childPackages.size();
10611                for (int i = 0; i < childCount; i++) {
10612                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10613                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10614                            childPkg.packageName)) {
10615                        throw new PackageManagerException("Can't override child of "
10616                                + "another disabled app. Ignoring package " + pkg.packageName);
10617                    }
10618                }
10619            }
10620
10621            // If we're only installing presumed-existing packages, require that the
10622            // scanned APK is both already known and at the path previously established
10623            // for it.  Previously unknown packages we pick up normally, but if we have an
10624            // a priori expectation about this package's install presence, enforce it.
10625            // With a singular exception for new system packages. When an OTA contains
10626            // a new system package, we allow the codepath to change from a system location
10627            // to the user-installed location. If we don't allow this change, any newer,
10628            // user-installed version of the application will be ignored.
10629            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10630                if (mExpectingBetter.containsKey(pkg.packageName)) {
10631                    logCriticalInfo(Log.WARN,
10632                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10633                } else {
10634                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10635                    if (known != null) {
10636                        if (DEBUG_PACKAGE_SCANNING) {
10637                            Log.d(TAG, "Examining " + pkg.codePath
10638                                    + " and requiring known paths " + known.codePathString
10639                                    + " & " + known.resourcePathString);
10640                        }
10641                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10642                                || !pkg.applicationInfo.getResourcePath().equals(
10643                                        known.resourcePathString)) {
10644                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10645                                    "Application package " + pkg.packageName
10646                                    + " found at " + pkg.applicationInfo.getCodePath()
10647                                    + " but expected at " + known.codePathString
10648                                    + "; ignoring.");
10649                        }
10650                    } else {
10651                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10652                                "Application package " + pkg.packageName
10653                                + " not found; ignoring.");
10654                    }
10655                }
10656            }
10657
10658            // Verify that this new package doesn't have any content providers
10659            // that conflict with existing packages.  Only do this if the
10660            // package isn't already installed, since we don't want to break
10661            // things that are installed.
10662            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10663                final int N = pkg.providers.size();
10664                int i;
10665                for (i=0; i<N; i++) {
10666                    PackageParser.Provider p = pkg.providers.get(i);
10667                    if (p.info.authority != null) {
10668                        String names[] = p.info.authority.split(";");
10669                        for (int j = 0; j < names.length; j++) {
10670                            if (mProvidersByAuthority.containsKey(names[j])) {
10671                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10672                                final String otherPackageName =
10673                                        ((other != null && other.getComponentName() != null) ?
10674                                                other.getComponentName().getPackageName() : "?");
10675                                throw new PackageManagerException(
10676                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10677                                        "Can't install because provider name " + names[j]
10678                                                + " (in package " + pkg.applicationInfo.packageName
10679                                                + ") is already used by " + otherPackageName);
10680                            }
10681                        }
10682                    }
10683                }
10684            }
10685        }
10686    }
10687
10688    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
10689            int type, String declaringPackageName, long declaringVersionCode) {
10690        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10691        if (versionedLib == null) {
10692            versionedLib = new LongSparseArray<>();
10693            mSharedLibraries.put(name, versionedLib);
10694            if (type == SharedLibraryInfo.TYPE_STATIC) {
10695                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10696            }
10697        } else if (versionedLib.indexOfKey(version) >= 0) {
10698            return false;
10699        }
10700        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10701                version, type, declaringPackageName, declaringVersionCode);
10702        versionedLib.put(version, libEntry);
10703        return true;
10704    }
10705
10706    private boolean removeSharedLibraryLPw(String name, long version) {
10707        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10708        if (versionedLib == null) {
10709            return false;
10710        }
10711        final int libIdx = versionedLib.indexOfKey(version);
10712        if (libIdx < 0) {
10713            return false;
10714        }
10715        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10716        versionedLib.remove(version);
10717        if (versionedLib.size() <= 0) {
10718            mSharedLibraries.remove(name);
10719            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10720                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10721                        .getPackageName());
10722            }
10723        }
10724        return true;
10725    }
10726
10727    /**
10728     * Adds a scanned package to the system. When this method is finished, the package will
10729     * be available for query, resolution, etc...
10730     */
10731    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10732            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
10733        final String pkgName = pkg.packageName;
10734        if (mCustomResolverComponentName != null &&
10735                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10736            setUpCustomResolverActivity(pkg);
10737        }
10738
10739        if (pkg.packageName.equals("android")) {
10740            synchronized (mPackages) {
10741                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10742                    // Set up information for our fall-back user intent resolution activity.
10743                    mPlatformPackage = pkg;
10744                    pkg.mVersionCode = mSdkVersion;
10745                    pkg.mVersionCodeMajor = 0;
10746                    mAndroidApplication = pkg.applicationInfo;
10747                    if (!mResolverReplaced) {
10748                        mResolveActivity.applicationInfo = mAndroidApplication;
10749                        mResolveActivity.name = ResolverActivity.class.getName();
10750                        mResolveActivity.packageName = mAndroidApplication.packageName;
10751                        mResolveActivity.processName = "system:ui";
10752                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10753                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10754                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10755                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10756                        mResolveActivity.exported = true;
10757                        mResolveActivity.enabled = true;
10758                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10759                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10760                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10761                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10762                                | ActivityInfo.CONFIG_ORIENTATION
10763                                | ActivityInfo.CONFIG_KEYBOARD
10764                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10765                        mResolveInfo.activityInfo = mResolveActivity;
10766                        mResolveInfo.priority = 0;
10767                        mResolveInfo.preferredOrder = 0;
10768                        mResolveInfo.match = 0;
10769                        mResolveComponentName = new ComponentName(
10770                                mAndroidApplication.packageName, mResolveActivity.name);
10771                    }
10772                }
10773            }
10774        }
10775
10776        ArrayList<PackageParser.Package> clientLibPkgs = null;
10777        // writer
10778        synchronized (mPackages) {
10779            boolean hasStaticSharedLibs = false;
10780
10781            // Any app can add new static shared libraries
10782            if (pkg.staticSharedLibName != null) {
10783                // Static shared libs don't allow renaming as they have synthetic package
10784                // names to allow install of multiple versions, so use name from manifest.
10785                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10786                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10787                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
10788                    hasStaticSharedLibs = true;
10789                } else {
10790                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10791                                + pkg.staticSharedLibName + " already exists; skipping");
10792                }
10793                // Static shared libs cannot be updated once installed since they
10794                // use synthetic package name which includes the version code, so
10795                // not need to update other packages's shared lib dependencies.
10796            }
10797
10798            if (!hasStaticSharedLibs
10799                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10800                // Only system apps can add new dynamic shared libraries.
10801                if (pkg.libraryNames != null) {
10802                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10803                        String name = pkg.libraryNames.get(i);
10804                        boolean allowed = false;
10805                        if (pkg.isUpdatedSystemApp()) {
10806                            // New library entries can only be added through the
10807                            // system image.  This is important to get rid of a lot
10808                            // of nasty edge cases: for example if we allowed a non-
10809                            // system update of the app to add a library, then uninstalling
10810                            // the update would make the library go away, and assumptions
10811                            // we made such as through app install filtering would now
10812                            // have allowed apps on the device which aren't compatible
10813                            // with it.  Better to just have the restriction here, be
10814                            // conservative, and create many fewer cases that can negatively
10815                            // impact the user experience.
10816                            final PackageSetting sysPs = mSettings
10817                                    .getDisabledSystemPkgLPr(pkg.packageName);
10818                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10819                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10820                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10821                                        allowed = true;
10822                                        break;
10823                                    }
10824                                }
10825                            }
10826                        } else {
10827                            allowed = true;
10828                        }
10829                        if (allowed) {
10830                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10831                                    SharedLibraryInfo.VERSION_UNDEFINED,
10832                                    SharedLibraryInfo.TYPE_DYNAMIC,
10833                                    pkg.packageName, pkg.getLongVersionCode())) {
10834                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10835                                        + name + " already exists; skipping");
10836                            }
10837                        } else {
10838                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10839                                    + name + " that is not declared on system image; skipping");
10840                        }
10841                    }
10842
10843                    if ((scanFlags & SCAN_BOOTING) == 0) {
10844                        // If we are not booting, we need to update any applications
10845                        // that are clients of our shared library.  If we are booting,
10846                        // this will all be done once the scan is complete.
10847                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10848                    }
10849                }
10850            }
10851        }
10852
10853        if ((scanFlags & SCAN_BOOTING) != 0) {
10854            // No apps can run during boot scan, so they don't need to be frozen
10855        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10856            // Caller asked to not kill app, so it's probably not frozen
10857        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10858            // Caller asked us to ignore frozen check for some reason; they
10859            // probably didn't know the package name
10860        } else {
10861            // We're doing major surgery on this package, so it better be frozen
10862            // right now to keep it from launching
10863            checkPackageFrozen(pkgName);
10864        }
10865
10866        // Also need to kill any apps that are dependent on the library.
10867        if (clientLibPkgs != null) {
10868            for (int i=0; i<clientLibPkgs.size(); i++) {
10869                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10870                killApplication(clientPkg.applicationInfo.packageName,
10871                        clientPkg.applicationInfo.uid, "update lib");
10872            }
10873        }
10874
10875        // writer
10876        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10877
10878        synchronized (mPackages) {
10879            // We don't expect installation to fail beyond this point
10880
10881            // Add the new setting to mSettings
10882            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10883            // Add the new setting to mPackages
10884            mPackages.put(pkg.applicationInfo.packageName, pkg);
10885            // Make sure we don't accidentally delete its data.
10886            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10887            while (iter.hasNext()) {
10888                PackageCleanItem item = iter.next();
10889                if (pkgName.equals(item.packageName)) {
10890                    iter.remove();
10891                }
10892            }
10893
10894            // Add the package's KeySets to the global KeySetManagerService
10895            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10896            ksms.addScannedPackageLPw(pkg);
10897
10898            int N = pkg.providers.size();
10899            StringBuilder r = null;
10900            int i;
10901            for (i=0; i<N; i++) {
10902                PackageParser.Provider p = pkg.providers.get(i);
10903                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10904                        p.info.processName);
10905                mProviders.addProvider(p);
10906                p.syncable = p.info.isSyncable;
10907                if (p.info.authority != null) {
10908                    String names[] = p.info.authority.split(";");
10909                    p.info.authority = null;
10910                    for (int j = 0; j < names.length; j++) {
10911                        if (j == 1 && p.syncable) {
10912                            // We only want the first authority for a provider to possibly be
10913                            // syncable, so if we already added this provider using a different
10914                            // authority clear the syncable flag. We copy the provider before
10915                            // changing it because the mProviders object contains a reference
10916                            // to a provider that we don't want to change.
10917                            // Only do this for the second authority since the resulting provider
10918                            // object can be the same for all future authorities for this provider.
10919                            p = new PackageParser.Provider(p);
10920                            p.syncable = false;
10921                        }
10922                        if (!mProvidersByAuthority.containsKey(names[j])) {
10923                            mProvidersByAuthority.put(names[j], p);
10924                            if (p.info.authority == null) {
10925                                p.info.authority = names[j];
10926                            } else {
10927                                p.info.authority = p.info.authority + ";" + names[j];
10928                            }
10929                            if (DEBUG_PACKAGE_SCANNING) {
10930                                if (chatty)
10931                                    Log.d(TAG, "Registered content provider: " + names[j]
10932                                            + ", className = " + p.info.name + ", isSyncable = "
10933                                            + p.info.isSyncable);
10934                            }
10935                        } else {
10936                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10937                            Slog.w(TAG, "Skipping provider name " + names[j] +
10938                                    " (in package " + pkg.applicationInfo.packageName +
10939                                    "): name already used by "
10940                                    + ((other != null && other.getComponentName() != null)
10941                                            ? other.getComponentName().getPackageName() : "?"));
10942                        }
10943                    }
10944                }
10945                if (chatty) {
10946                    if (r == null) {
10947                        r = new StringBuilder(256);
10948                    } else {
10949                        r.append(' ');
10950                    }
10951                    r.append(p.info.name);
10952                }
10953            }
10954            if (r != null) {
10955                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10956            }
10957
10958            N = pkg.services.size();
10959            r = null;
10960            for (i=0; i<N; i++) {
10961                PackageParser.Service s = pkg.services.get(i);
10962                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10963                        s.info.processName);
10964                mServices.addService(s);
10965                if (chatty) {
10966                    if (r == null) {
10967                        r = new StringBuilder(256);
10968                    } else {
10969                        r.append(' ');
10970                    }
10971                    r.append(s.info.name);
10972                }
10973            }
10974            if (r != null) {
10975                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10976            }
10977
10978            N = pkg.receivers.size();
10979            r = null;
10980            for (i=0; i<N; i++) {
10981                PackageParser.Activity a = pkg.receivers.get(i);
10982                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10983                        a.info.processName);
10984                mReceivers.addActivity(a, "receiver");
10985                if (chatty) {
10986                    if (r == null) {
10987                        r = new StringBuilder(256);
10988                    } else {
10989                        r.append(' ');
10990                    }
10991                    r.append(a.info.name);
10992                }
10993            }
10994            if (r != null) {
10995                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10996            }
10997
10998            N = pkg.activities.size();
10999            r = null;
11000            for (i=0; i<N; i++) {
11001                PackageParser.Activity a = pkg.activities.get(i);
11002                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11003                        a.info.processName);
11004                mActivities.addActivity(a, "activity");
11005                if (chatty) {
11006                    if (r == null) {
11007                        r = new StringBuilder(256);
11008                    } else {
11009                        r.append(' ');
11010                    }
11011                    r.append(a.info.name);
11012                }
11013            }
11014            if (r != null) {
11015                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11016            }
11017
11018            // Don't allow ephemeral applications to define new permissions groups.
11019            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11020                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11021                        + " ignored: instant apps cannot define new permission groups.");
11022            } else {
11023                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11024            }
11025
11026            // Don't allow ephemeral applications to define new permissions.
11027            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11028                Slog.w(TAG, "Permissions from package " + pkg.packageName
11029                        + " ignored: instant apps cannot define new permissions.");
11030            } else {
11031                mPermissionManager.addAllPermissions(pkg, chatty);
11032            }
11033
11034            N = pkg.instrumentation.size();
11035            r = null;
11036            for (i=0; i<N; i++) {
11037                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11038                a.info.packageName = pkg.applicationInfo.packageName;
11039                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11040                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11041                a.info.splitNames = pkg.splitNames;
11042                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11043                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11044                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11045                a.info.dataDir = pkg.applicationInfo.dataDir;
11046                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11047                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11048                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11049                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11050                mInstrumentation.put(a.getComponentName(), a);
11051                if (chatty) {
11052                    if (r == null) {
11053                        r = new StringBuilder(256);
11054                    } else {
11055                        r.append(' ');
11056                    }
11057                    r.append(a.info.name);
11058                }
11059            }
11060            if (r != null) {
11061                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11062            }
11063
11064            if (pkg.protectedBroadcasts != null) {
11065                N = pkg.protectedBroadcasts.size();
11066                synchronized (mProtectedBroadcasts) {
11067                    for (i = 0; i < N; i++) {
11068                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11069                    }
11070                }
11071            }
11072        }
11073
11074        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11075    }
11076
11077    /**
11078     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11079     * is derived purely on the basis of the contents of {@code scanFile} and
11080     * {@code cpuAbiOverride}.
11081     *
11082     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11083     */
11084    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11085            boolean extractLibs)
11086                    throws PackageManagerException {
11087        // Give ourselves some initial paths; we'll come back for another
11088        // pass once we've determined ABI below.
11089        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11090
11091        // We would never need to extract libs for forward-locked and external packages,
11092        // since the container service will do it for us. We shouldn't attempt to
11093        // extract libs from system app when it was not updated.
11094        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11095                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11096            extractLibs = false;
11097        }
11098
11099        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11100        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11101
11102        NativeLibraryHelper.Handle handle = null;
11103        try {
11104            handle = NativeLibraryHelper.Handle.create(pkg);
11105            // TODO(multiArch): This can be null for apps that didn't go through the
11106            // usual installation process. We can calculate it again, like we
11107            // do during install time.
11108            //
11109            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11110            // unnecessary.
11111            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11112
11113            // Null out the abis so that they can be recalculated.
11114            pkg.applicationInfo.primaryCpuAbi = null;
11115            pkg.applicationInfo.secondaryCpuAbi = null;
11116            if (isMultiArch(pkg.applicationInfo)) {
11117                // Warn if we've set an abiOverride for multi-lib packages..
11118                // By definition, we need to copy both 32 and 64 bit libraries for
11119                // such packages.
11120                if (pkg.cpuAbiOverride != null
11121                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11122                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11123                }
11124
11125                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11126                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11127                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11128                    if (extractLibs) {
11129                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11130                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11131                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11132                                useIsaSpecificSubdirs);
11133                    } else {
11134                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11135                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11136                    }
11137                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11138                }
11139
11140                // Shared library native code should be in the APK zip aligned
11141                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11142                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11143                            "Shared library native lib extraction not supported");
11144                }
11145
11146                maybeThrowExceptionForMultiArchCopy(
11147                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11148
11149                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11150                    if (extractLibs) {
11151                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11152                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11153                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11154                                useIsaSpecificSubdirs);
11155                    } else {
11156                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11157                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11158                    }
11159                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11160                }
11161
11162                maybeThrowExceptionForMultiArchCopy(
11163                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11164
11165                if (abi64 >= 0) {
11166                    // Shared library native libs should be in the APK zip aligned
11167                    if (extractLibs && pkg.isLibrary()) {
11168                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11169                                "Shared library native lib extraction not supported");
11170                    }
11171                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11172                }
11173
11174                if (abi32 >= 0) {
11175                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11176                    if (abi64 >= 0) {
11177                        if (pkg.use32bitAbi) {
11178                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11179                            pkg.applicationInfo.primaryCpuAbi = abi;
11180                        } else {
11181                            pkg.applicationInfo.secondaryCpuAbi = abi;
11182                        }
11183                    } else {
11184                        pkg.applicationInfo.primaryCpuAbi = abi;
11185                    }
11186                }
11187            } else {
11188                String[] abiList = (cpuAbiOverride != null) ?
11189                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11190
11191                // Enable gross and lame hacks for apps that are built with old
11192                // SDK tools. We must scan their APKs for renderscript bitcode and
11193                // not launch them if it's present. Don't bother checking on devices
11194                // that don't have 64 bit support.
11195                boolean needsRenderScriptOverride = false;
11196                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11197                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11198                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11199                    needsRenderScriptOverride = true;
11200                }
11201
11202                final int copyRet;
11203                if (extractLibs) {
11204                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11205                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11206                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11207                } else {
11208                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11209                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11210                }
11211                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11212
11213                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11214                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11215                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11216                }
11217
11218                if (copyRet >= 0) {
11219                    // Shared libraries that have native libs must be multi-architecture
11220                    if (pkg.isLibrary()) {
11221                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11222                                "Shared library with native libs must be multiarch");
11223                    }
11224                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11225                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11226                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11227                } else if (needsRenderScriptOverride) {
11228                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11229                }
11230            }
11231        } catch (IOException ioe) {
11232            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11233        } finally {
11234            IoUtils.closeQuietly(handle);
11235        }
11236
11237        // Now that we've calculated the ABIs and determined if it's an internal app,
11238        // we will go ahead and populate the nativeLibraryPath.
11239        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11240    }
11241
11242    /**
11243     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11244     * i.e, so that all packages can be run inside a single process if required.
11245     *
11246     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11247     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11248     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11249     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11250     * updating a package that belongs to a shared user.
11251     *
11252     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11253     * adds unnecessary complexity.
11254     */
11255    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11256            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11257        List<String> changedAbiCodePath = null;
11258        String requiredInstructionSet = null;
11259        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11260            requiredInstructionSet = VMRuntime.getInstructionSet(
11261                     scannedPackage.applicationInfo.primaryCpuAbi);
11262        }
11263
11264        PackageSetting requirer = null;
11265        for (PackageSetting ps : packagesForUser) {
11266            // If packagesForUser contains scannedPackage, we skip it. This will happen
11267            // when scannedPackage is an update of an existing package. Without this check,
11268            // we will never be able to change the ABI of any package belonging to a shared
11269            // user, even if it's compatible with other packages.
11270            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11271                if (ps.primaryCpuAbiString == null) {
11272                    continue;
11273                }
11274
11275                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11276                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11277                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11278                    // this but there's not much we can do.
11279                    String errorMessage = "Instruction set mismatch, "
11280                            + ((requirer == null) ? "[caller]" : requirer)
11281                            + " requires " + requiredInstructionSet + " whereas " + ps
11282                            + " requires " + instructionSet;
11283                    Slog.w(TAG, errorMessage);
11284                }
11285
11286                if (requiredInstructionSet == null) {
11287                    requiredInstructionSet = instructionSet;
11288                    requirer = ps;
11289                }
11290            }
11291        }
11292
11293        if (requiredInstructionSet != null) {
11294            String adjustedAbi;
11295            if (requirer != null) {
11296                // requirer != null implies that either scannedPackage was null or that scannedPackage
11297                // did not require an ABI, in which case we have to adjust scannedPackage to match
11298                // the ABI of the set (which is the same as requirer's ABI)
11299                adjustedAbi = requirer.primaryCpuAbiString;
11300                if (scannedPackage != null) {
11301                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11302                }
11303            } else {
11304                // requirer == null implies that we're updating all ABIs in the set to
11305                // match scannedPackage.
11306                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11307            }
11308
11309            for (PackageSetting ps : packagesForUser) {
11310                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11311                    if (ps.primaryCpuAbiString != null) {
11312                        continue;
11313                    }
11314
11315                    ps.primaryCpuAbiString = adjustedAbi;
11316                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11317                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11318                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11319                        if (DEBUG_ABI_SELECTION) {
11320                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11321                                    + " (requirer="
11322                                    + (requirer != null ? requirer.pkg : "null")
11323                                    + ", scannedPackage="
11324                                    + (scannedPackage != null ? scannedPackage : "null")
11325                                    + ")");
11326                        }
11327                        if (changedAbiCodePath == null) {
11328                            changedAbiCodePath = new ArrayList<>();
11329                        }
11330                        changedAbiCodePath.add(ps.codePathString);
11331                    }
11332                }
11333            }
11334        }
11335        return changedAbiCodePath;
11336    }
11337
11338    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11339        synchronized (mPackages) {
11340            mResolverReplaced = true;
11341            // Set up information for custom user intent resolution activity.
11342            mResolveActivity.applicationInfo = pkg.applicationInfo;
11343            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11344            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11345            mResolveActivity.processName = pkg.applicationInfo.packageName;
11346            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11347            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11348                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11349            mResolveActivity.theme = 0;
11350            mResolveActivity.exported = true;
11351            mResolveActivity.enabled = true;
11352            mResolveInfo.activityInfo = mResolveActivity;
11353            mResolveInfo.priority = 0;
11354            mResolveInfo.preferredOrder = 0;
11355            mResolveInfo.match = 0;
11356            mResolveComponentName = mCustomResolverComponentName;
11357            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11358                    mResolveComponentName);
11359        }
11360    }
11361
11362    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11363        if (installerActivity == null) {
11364            if (DEBUG_EPHEMERAL) {
11365                Slog.d(TAG, "Clear ephemeral installer activity");
11366            }
11367            mInstantAppInstallerActivity = null;
11368            return;
11369        }
11370
11371        if (DEBUG_EPHEMERAL) {
11372            Slog.d(TAG, "Set ephemeral installer activity: "
11373                    + installerActivity.getComponentName());
11374        }
11375        // Set up information for ephemeral installer activity
11376        mInstantAppInstallerActivity = installerActivity;
11377        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11378                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11379        mInstantAppInstallerActivity.exported = true;
11380        mInstantAppInstallerActivity.enabled = true;
11381        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11382        mInstantAppInstallerInfo.priority = 0;
11383        mInstantAppInstallerInfo.preferredOrder = 1;
11384        mInstantAppInstallerInfo.isDefault = true;
11385        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11386                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11387    }
11388
11389    private static String calculateBundledApkRoot(final String codePathString) {
11390        final File codePath = new File(codePathString);
11391        final File codeRoot;
11392        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11393            codeRoot = Environment.getRootDirectory();
11394        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11395            codeRoot = Environment.getOemDirectory();
11396        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11397            codeRoot = Environment.getVendorDirectory();
11398        } else {
11399            // Unrecognized code path; take its top real segment as the apk root:
11400            // e.g. /something/app/blah.apk => /something
11401            try {
11402                File f = codePath.getCanonicalFile();
11403                File parent = f.getParentFile();    // non-null because codePath is a file
11404                File tmp;
11405                while ((tmp = parent.getParentFile()) != null) {
11406                    f = parent;
11407                    parent = tmp;
11408                }
11409                codeRoot = f;
11410                Slog.w(TAG, "Unrecognized code path "
11411                        + codePath + " - using " + codeRoot);
11412            } catch (IOException e) {
11413                // Can't canonicalize the code path -- shenanigans?
11414                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11415                return Environment.getRootDirectory().getPath();
11416            }
11417        }
11418        return codeRoot.getPath();
11419    }
11420
11421    /**
11422     * Derive and set the location of native libraries for the given package,
11423     * which varies depending on where and how the package was installed.
11424     */
11425    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11426        final ApplicationInfo info = pkg.applicationInfo;
11427        final String codePath = pkg.codePath;
11428        final File codeFile = new File(codePath);
11429        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11430        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11431
11432        info.nativeLibraryRootDir = null;
11433        info.nativeLibraryRootRequiresIsa = false;
11434        info.nativeLibraryDir = null;
11435        info.secondaryNativeLibraryDir = null;
11436
11437        if (isApkFile(codeFile)) {
11438            // Monolithic install
11439            if (bundledApp) {
11440                // If "/system/lib64/apkname" exists, assume that is the per-package
11441                // native library directory to use; otherwise use "/system/lib/apkname".
11442                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11443                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11444                        getPrimaryInstructionSet(info));
11445
11446                // This is a bundled system app so choose the path based on the ABI.
11447                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11448                // is just the default path.
11449                final String apkName = deriveCodePathName(codePath);
11450                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11451                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11452                        apkName).getAbsolutePath();
11453
11454                if (info.secondaryCpuAbi != null) {
11455                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11456                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11457                            secondaryLibDir, apkName).getAbsolutePath();
11458                }
11459            } else if (asecApp) {
11460                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11461                        .getAbsolutePath();
11462            } else {
11463                final String apkName = deriveCodePathName(codePath);
11464                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11465                        .getAbsolutePath();
11466            }
11467
11468            info.nativeLibraryRootRequiresIsa = false;
11469            info.nativeLibraryDir = info.nativeLibraryRootDir;
11470        } else {
11471            // Cluster install
11472            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11473            info.nativeLibraryRootRequiresIsa = true;
11474
11475            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11476                    getPrimaryInstructionSet(info)).getAbsolutePath();
11477
11478            if (info.secondaryCpuAbi != null) {
11479                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11480                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11481            }
11482        }
11483    }
11484
11485    /**
11486     * Calculate the abis and roots for a bundled app. These can uniquely
11487     * be determined from the contents of the system partition, i.e whether
11488     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11489     * of this information, and instead assume that the system was built
11490     * sensibly.
11491     */
11492    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11493                                           PackageSetting pkgSetting) {
11494        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11495
11496        // If "/system/lib64/apkname" exists, assume that is the per-package
11497        // native library directory to use; otherwise use "/system/lib/apkname".
11498        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11499        setBundledAppAbi(pkg, apkRoot, apkName);
11500        // pkgSetting might be null during rescan following uninstall of updates
11501        // to a bundled app, so accommodate that possibility.  The settings in
11502        // that case will be established later from the parsed package.
11503        //
11504        // If the settings aren't null, sync them up with what we've just derived.
11505        // note that apkRoot isn't stored in the package settings.
11506        if (pkgSetting != null) {
11507            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11508            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11509        }
11510    }
11511
11512    /**
11513     * Deduces the ABI of a bundled app and sets the relevant fields on the
11514     * parsed pkg object.
11515     *
11516     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11517     *        under which system libraries are installed.
11518     * @param apkName the name of the installed package.
11519     */
11520    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11521        final File codeFile = new File(pkg.codePath);
11522
11523        final boolean has64BitLibs;
11524        final boolean has32BitLibs;
11525        if (isApkFile(codeFile)) {
11526            // Monolithic install
11527            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11528            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11529        } else {
11530            // Cluster install
11531            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11532            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11533                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11534                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11535                has64BitLibs = (new File(rootDir, isa)).exists();
11536            } else {
11537                has64BitLibs = false;
11538            }
11539            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11540                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11541                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11542                has32BitLibs = (new File(rootDir, isa)).exists();
11543            } else {
11544                has32BitLibs = false;
11545            }
11546        }
11547
11548        if (has64BitLibs && !has32BitLibs) {
11549            // The package has 64 bit libs, but not 32 bit libs. Its primary
11550            // ABI should be 64 bit. We can safely assume here that the bundled
11551            // native libraries correspond to the most preferred ABI in the list.
11552
11553            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11554            pkg.applicationInfo.secondaryCpuAbi = null;
11555        } else if (has32BitLibs && !has64BitLibs) {
11556            // The package has 32 bit libs but not 64 bit libs. Its primary
11557            // ABI should be 32 bit.
11558
11559            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11560            pkg.applicationInfo.secondaryCpuAbi = null;
11561        } else if (has32BitLibs && has64BitLibs) {
11562            // The application has both 64 and 32 bit bundled libraries. We check
11563            // here that the app declares multiArch support, and warn if it doesn't.
11564            //
11565            // We will be lenient here and record both ABIs. The primary will be the
11566            // ABI that's higher on the list, i.e, a device that's configured to prefer
11567            // 64 bit apps will see a 64 bit primary ABI,
11568
11569            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11570                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11571            }
11572
11573            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11574                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11575                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11576            } else {
11577                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11578                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11579            }
11580        } else {
11581            pkg.applicationInfo.primaryCpuAbi = null;
11582            pkg.applicationInfo.secondaryCpuAbi = null;
11583        }
11584    }
11585
11586    private void killApplication(String pkgName, int appId, String reason) {
11587        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11588    }
11589
11590    private void killApplication(String pkgName, int appId, int userId, String reason) {
11591        // Request the ActivityManager to kill the process(only for existing packages)
11592        // so that we do not end up in a confused state while the user is still using the older
11593        // version of the application while the new one gets installed.
11594        final long token = Binder.clearCallingIdentity();
11595        try {
11596            IActivityManager am = ActivityManager.getService();
11597            if (am != null) {
11598                try {
11599                    am.killApplication(pkgName, appId, userId, reason);
11600                } catch (RemoteException e) {
11601                }
11602            }
11603        } finally {
11604            Binder.restoreCallingIdentity(token);
11605        }
11606    }
11607
11608    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11609        // Remove the parent package setting
11610        PackageSetting ps = (PackageSetting) pkg.mExtras;
11611        if (ps != null) {
11612            removePackageLI(ps, chatty);
11613        }
11614        // Remove the child package setting
11615        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11616        for (int i = 0; i < childCount; i++) {
11617            PackageParser.Package childPkg = pkg.childPackages.get(i);
11618            ps = (PackageSetting) childPkg.mExtras;
11619            if (ps != null) {
11620                removePackageLI(ps, chatty);
11621            }
11622        }
11623    }
11624
11625    void removePackageLI(PackageSetting ps, boolean chatty) {
11626        if (DEBUG_INSTALL) {
11627            if (chatty)
11628                Log.d(TAG, "Removing package " + ps.name);
11629        }
11630
11631        // writer
11632        synchronized (mPackages) {
11633            mPackages.remove(ps.name);
11634            final PackageParser.Package pkg = ps.pkg;
11635            if (pkg != null) {
11636                cleanPackageDataStructuresLILPw(pkg, chatty);
11637            }
11638        }
11639    }
11640
11641    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11642        if (DEBUG_INSTALL) {
11643            if (chatty)
11644                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11645        }
11646
11647        // writer
11648        synchronized (mPackages) {
11649            // Remove the parent package
11650            mPackages.remove(pkg.applicationInfo.packageName);
11651            cleanPackageDataStructuresLILPw(pkg, chatty);
11652
11653            // Remove the child packages
11654            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11655            for (int i = 0; i < childCount; i++) {
11656                PackageParser.Package childPkg = pkg.childPackages.get(i);
11657                mPackages.remove(childPkg.applicationInfo.packageName);
11658                cleanPackageDataStructuresLILPw(childPkg, chatty);
11659            }
11660        }
11661    }
11662
11663    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11664        int N = pkg.providers.size();
11665        StringBuilder r = null;
11666        int i;
11667        for (i=0; i<N; i++) {
11668            PackageParser.Provider p = pkg.providers.get(i);
11669            mProviders.removeProvider(p);
11670            if (p.info.authority == null) {
11671
11672                /* There was another ContentProvider with this authority when
11673                 * this app was installed so this authority is null,
11674                 * Ignore it as we don't have to unregister the provider.
11675                 */
11676                continue;
11677            }
11678            String names[] = p.info.authority.split(";");
11679            for (int j = 0; j < names.length; j++) {
11680                if (mProvidersByAuthority.get(names[j]) == p) {
11681                    mProvidersByAuthority.remove(names[j]);
11682                    if (DEBUG_REMOVE) {
11683                        if (chatty)
11684                            Log.d(TAG, "Unregistered content provider: " + names[j]
11685                                    + ", className = " + p.info.name + ", isSyncable = "
11686                                    + p.info.isSyncable);
11687                    }
11688                }
11689            }
11690            if (DEBUG_REMOVE && chatty) {
11691                if (r == null) {
11692                    r = new StringBuilder(256);
11693                } else {
11694                    r.append(' ');
11695                }
11696                r.append(p.info.name);
11697            }
11698        }
11699        if (r != null) {
11700            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11701        }
11702
11703        N = pkg.services.size();
11704        r = null;
11705        for (i=0; i<N; i++) {
11706            PackageParser.Service s = pkg.services.get(i);
11707            mServices.removeService(s);
11708            if (chatty) {
11709                if (r == null) {
11710                    r = new StringBuilder(256);
11711                } else {
11712                    r.append(' ');
11713                }
11714                r.append(s.info.name);
11715            }
11716        }
11717        if (r != null) {
11718            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11719        }
11720
11721        N = pkg.receivers.size();
11722        r = null;
11723        for (i=0; i<N; i++) {
11724            PackageParser.Activity a = pkg.receivers.get(i);
11725            mReceivers.removeActivity(a, "receiver");
11726            if (DEBUG_REMOVE && chatty) {
11727                if (r == null) {
11728                    r = new StringBuilder(256);
11729                } else {
11730                    r.append(' ');
11731                }
11732                r.append(a.info.name);
11733            }
11734        }
11735        if (r != null) {
11736            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11737        }
11738
11739        N = pkg.activities.size();
11740        r = null;
11741        for (i=0; i<N; i++) {
11742            PackageParser.Activity a = pkg.activities.get(i);
11743            mActivities.removeActivity(a, "activity");
11744            if (DEBUG_REMOVE && chatty) {
11745                if (r == null) {
11746                    r = new StringBuilder(256);
11747                } else {
11748                    r.append(' ');
11749                }
11750                r.append(a.info.name);
11751            }
11752        }
11753        if (r != null) {
11754            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11755        }
11756
11757        mPermissionManager.removeAllPermissions(pkg, chatty);
11758
11759        N = pkg.instrumentation.size();
11760        r = null;
11761        for (i=0; i<N; i++) {
11762            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11763            mInstrumentation.remove(a.getComponentName());
11764            if (DEBUG_REMOVE && chatty) {
11765                if (r == null) {
11766                    r = new StringBuilder(256);
11767                } else {
11768                    r.append(' ');
11769                }
11770                r.append(a.info.name);
11771            }
11772        }
11773        if (r != null) {
11774            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11775        }
11776
11777        r = null;
11778        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11779            // Only system apps can hold shared libraries.
11780            if (pkg.libraryNames != null) {
11781                for (i = 0; i < pkg.libraryNames.size(); i++) {
11782                    String name = pkg.libraryNames.get(i);
11783                    if (removeSharedLibraryLPw(name, 0)) {
11784                        if (DEBUG_REMOVE && chatty) {
11785                            if (r == null) {
11786                                r = new StringBuilder(256);
11787                            } else {
11788                                r.append(' ');
11789                            }
11790                            r.append(name);
11791                        }
11792                    }
11793                }
11794            }
11795        }
11796
11797        r = null;
11798
11799        // Any package can hold static shared libraries.
11800        if (pkg.staticSharedLibName != null) {
11801            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11802                if (DEBUG_REMOVE && chatty) {
11803                    if (r == null) {
11804                        r = new StringBuilder(256);
11805                    } else {
11806                        r.append(' ');
11807                    }
11808                    r.append(pkg.staticSharedLibName);
11809                }
11810            }
11811        }
11812
11813        if (r != null) {
11814            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11815        }
11816    }
11817
11818
11819    final class ActivityIntentResolver
11820            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11821        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11822                boolean defaultOnly, int userId) {
11823            if (!sUserManager.exists(userId)) return null;
11824            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11825            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11826        }
11827
11828        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11829                int userId) {
11830            if (!sUserManager.exists(userId)) return null;
11831            mFlags = flags;
11832            return super.queryIntent(intent, resolvedType,
11833                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11834                    userId);
11835        }
11836
11837        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11838                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11839            if (!sUserManager.exists(userId)) return null;
11840            if (packageActivities == null) {
11841                return null;
11842            }
11843            mFlags = flags;
11844            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11845            final int N = packageActivities.size();
11846            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11847                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11848
11849            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11850            for (int i = 0; i < N; ++i) {
11851                intentFilters = packageActivities.get(i).intents;
11852                if (intentFilters != null && intentFilters.size() > 0) {
11853                    PackageParser.ActivityIntentInfo[] array =
11854                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11855                    intentFilters.toArray(array);
11856                    listCut.add(array);
11857                }
11858            }
11859            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11860        }
11861
11862        /**
11863         * Finds a privileged activity that matches the specified activity names.
11864         */
11865        private PackageParser.Activity findMatchingActivity(
11866                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11867            for (PackageParser.Activity sysActivity : activityList) {
11868                if (sysActivity.info.name.equals(activityInfo.name)) {
11869                    return sysActivity;
11870                }
11871                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11872                    return sysActivity;
11873                }
11874                if (sysActivity.info.targetActivity != null) {
11875                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11876                        return sysActivity;
11877                    }
11878                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11879                        return sysActivity;
11880                    }
11881                }
11882            }
11883            return null;
11884        }
11885
11886        public class IterGenerator<E> {
11887            public Iterator<E> generate(ActivityIntentInfo info) {
11888                return null;
11889            }
11890        }
11891
11892        public class ActionIterGenerator extends IterGenerator<String> {
11893            @Override
11894            public Iterator<String> generate(ActivityIntentInfo info) {
11895                return info.actionsIterator();
11896            }
11897        }
11898
11899        public class CategoriesIterGenerator extends IterGenerator<String> {
11900            @Override
11901            public Iterator<String> generate(ActivityIntentInfo info) {
11902                return info.categoriesIterator();
11903            }
11904        }
11905
11906        public class SchemesIterGenerator extends IterGenerator<String> {
11907            @Override
11908            public Iterator<String> generate(ActivityIntentInfo info) {
11909                return info.schemesIterator();
11910            }
11911        }
11912
11913        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11914            @Override
11915            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11916                return info.authoritiesIterator();
11917            }
11918        }
11919
11920        /**
11921         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11922         * MODIFIED. Do not pass in a list that should not be changed.
11923         */
11924        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11925                IterGenerator<T> generator, Iterator<T> searchIterator) {
11926            // loop through the set of actions; every one must be found in the intent filter
11927            while (searchIterator.hasNext()) {
11928                // we must have at least one filter in the list to consider a match
11929                if (intentList.size() == 0) {
11930                    break;
11931                }
11932
11933                final T searchAction = searchIterator.next();
11934
11935                // loop through the set of intent filters
11936                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11937                while (intentIter.hasNext()) {
11938                    final ActivityIntentInfo intentInfo = intentIter.next();
11939                    boolean selectionFound = false;
11940
11941                    // loop through the intent filter's selection criteria; at least one
11942                    // of them must match the searched criteria
11943                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11944                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11945                        final T intentSelection = intentSelectionIter.next();
11946                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11947                            selectionFound = true;
11948                            break;
11949                        }
11950                    }
11951
11952                    // the selection criteria wasn't found in this filter's set; this filter
11953                    // is not a potential match
11954                    if (!selectionFound) {
11955                        intentIter.remove();
11956                    }
11957                }
11958            }
11959        }
11960
11961        private boolean isProtectedAction(ActivityIntentInfo filter) {
11962            final Iterator<String> actionsIter = filter.actionsIterator();
11963            while (actionsIter != null && actionsIter.hasNext()) {
11964                final String filterAction = actionsIter.next();
11965                if (PROTECTED_ACTIONS.contains(filterAction)) {
11966                    return true;
11967                }
11968            }
11969            return false;
11970        }
11971
11972        /**
11973         * Adjusts the priority of the given intent filter according to policy.
11974         * <p>
11975         * <ul>
11976         * <li>The priority for non privileged applications is capped to '0'</li>
11977         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11978         * <li>The priority for unbundled updates to privileged applications is capped to the
11979         *      priority defined on the system partition</li>
11980         * </ul>
11981         * <p>
11982         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11983         * allowed to obtain any priority on any action.
11984         */
11985        private void adjustPriority(
11986                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11987            // nothing to do; priority is fine as-is
11988            if (intent.getPriority() <= 0) {
11989                return;
11990            }
11991
11992            final ActivityInfo activityInfo = intent.activity.info;
11993            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11994
11995            final boolean privilegedApp =
11996                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11997            if (!privilegedApp) {
11998                // non-privileged applications can never define a priority >0
11999                if (DEBUG_FILTERS) {
12000                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12001                            + " package: " + applicationInfo.packageName
12002                            + " activity: " + intent.activity.className
12003                            + " origPrio: " + intent.getPriority());
12004                }
12005                intent.setPriority(0);
12006                return;
12007            }
12008
12009            if (systemActivities == null) {
12010                // the system package is not disabled; we're parsing the system partition
12011                if (isProtectedAction(intent)) {
12012                    if (mDeferProtectedFilters) {
12013                        // We can't deal with these just yet. No component should ever obtain a
12014                        // >0 priority for a protected actions, with ONE exception -- the setup
12015                        // wizard. The setup wizard, however, cannot be known until we're able to
12016                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12017                        // until all intent filters have been processed. Chicken, meet egg.
12018                        // Let the filter temporarily have a high priority and rectify the
12019                        // priorities after all system packages have been scanned.
12020                        mProtectedFilters.add(intent);
12021                        if (DEBUG_FILTERS) {
12022                            Slog.i(TAG, "Protected action; save for later;"
12023                                    + " package: " + applicationInfo.packageName
12024                                    + " activity: " + intent.activity.className
12025                                    + " origPrio: " + intent.getPriority());
12026                        }
12027                        return;
12028                    } else {
12029                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12030                            Slog.i(TAG, "No setup wizard;"
12031                                + " All protected intents capped to priority 0");
12032                        }
12033                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12034                            if (DEBUG_FILTERS) {
12035                                Slog.i(TAG, "Found setup wizard;"
12036                                    + " allow priority " + intent.getPriority() + ";"
12037                                    + " package: " + intent.activity.info.packageName
12038                                    + " activity: " + intent.activity.className
12039                                    + " priority: " + intent.getPriority());
12040                            }
12041                            // setup wizard gets whatever it wants
12042                            return;
12043                        }
12044                        if (DEBUG_FILTERS) {
12045                            Slog.i(TAG, "Protected action; cap priority to 0;"
12046                                    + " package: " + intent.activity.info.packageName
12047                                    + " activity: " + intent.activity.className
12048                                    + " origPrio: " + intent.getPriority());
12049                        }
12050                        intent.setPriority(0);
12051                        return;
12052                    }
12053                }
12054                // privileged apps on the system image get whatever priority they request
12055                return;
12056            }
12057
12058            // privileged app unbundled update ... try to find the same activity
12059            final PackageParser.Activity foundActivity =
12060                    findMatchingActivity(systemActivities, activityInfo);
12061            if (foundActivity == null) {
12062                // this is a new activity; it cannot obtain >0 priority
12063                if (DEBUG_FILTERS) {
12064                    Slog.i(TAG, "New activity; cap priority to 0;"
12065                            + " package: " + applicationInfo.packageName
12066                            + " activity: " + intent.activity.className
12067                            + " origPrio: " + intent.getPriority());
12068                }
12069                intent.setPriority(0);
12070                return;
12071            }
12072
12073            // found activity, now check for filter equivalence
12074
12075            // a shallow copy is enough; we modify the list, not its contents
12076            final List<ActivityIntentInfo> intentListCopy =
12077                    new ArrayList<>(foundActivity.intents);
12078            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12079
12080            // find matching action subsets
12081            final Iterator<String> actionsIterator = intent.actionsIterator();
12082            if (actionsIterator != null) {
12083                getIntentListSubset(
12084                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12085                if (intentListCopy.size() == 0) {
12086                    // no more intents to match; we're not equivalent
12087                    if (DEBUG_FILTERS) {
12088                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12089                                + " package: " + applicationInfo.packageName
12090                                + " activity: " + intent.activity.className
12091                                + " origPrio: " + intent.getPriority());
12092                    }
12093                    intent.setPriority(0);
12094                    return;
12095                }
12096            }
12097
12098            // find matching category subsets
12099            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12100            if (categoriesIterator != null) {
12101                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12102                        categoriesIterator);
12103                if (intentListCopy.size() == 0) {
12104                    // no more intents to match; we're not equivalent
12105                    if (DEBUG_FILTERS) {
12106                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12107                                + " package: " + applicationInfo.packageName
12108                                + " activity: " + intent.activity.className
12109                                + " origPrio: " + intent.getPriority());
12110                    }
12111                    intent.setPriority(0);
12112                    return;
12113                }
12114            }
12115
12116            // find matching schemes subsets
12117            final Iterator<String> schemesIterator = intent.schemesIterator();
12118            if (schemesIterator != null) {
12119                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12120                        schemesIterator);
12121                if (intentListCopy.size() == 0) {
12122                    // no more intents to match; we're not equivalent
12123                    if (DEBUG_FILTERS) {
12124                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12125                                + " package: " + applicationInfo.packageName
12126                                + " activity: " + intent.activity.className
12127                                + " origPrio: " + intent.getPriority());
12128                    }
12129                    intent.setPriority(0);
12130                    return;
12131                }
12132            }
12133
12134            // find matching authorities subsets
12135            final Iterator<IntentFilter.AuthorityEntry>
12136                    authoritiesIterator = intent.authoritiesIterator();
12137            if (authoritiesIterator != null) {
12138                getIntentListSubset(intentListCopy,
12139                        new AuthoritiesIterGenerator(),
12140                        authoritiesIterator);
12141                if (intentListCopy.size() == 0) {
12142                    // no more intents to match; we're not equivalent
12143                    if (DEBUG_FILTERS) {
12144                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12145                                + " package: " + applicationInfo.packageName
12146                                + " activity: " + intent.activity.className
12147                                + " origPrio: " + intent.getPriority());
12148                    }
12149                    intent.setPriority(0);
12150                    return;
12151                }
12152            }
12153
12154            // we found matching filter(s); app gets the max priority of all intents
12155            int cappedPriority = 0;
12156            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12157                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12158            }
12159            if (intent.getPriority() > cappedPriority) {
12160                if (DEBUG_FILTERS) {
12161                    Slog.i(TAG, "Found matching filter(s);"
12162                            + " cap priority to " + cappedPriority + ";"
12163                            + " package: " + applicationInfo.packageName
12164                            + " activity: " + intent.activity.className
12165                            + " origPrio: " + intent.getPriority());
12166                }
12167                intent.setPriority(cappedPriority);
12168                return;
12169            }
12170            // all this for nothing; the requested priority was <= what was on the system
12171        }
12172
12173        public final void addActivity(PackageParser.Activity a, String type) {
12174            mActivities.put(a.getComponentName(), a);
12175            if (DEBUG_SHOW_INFO)
12176                Log.v(
12177                TAG, "  " + type + " " +
12178                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12179            if (DEBUG_SHOW_INFO)
12180                Log.v(TAG, "    Class=" + a.info.name);
12181            final int NI = a.intents.size();
12182            for (int j=0; j<NI; j++) {
12183                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12184                if ("activity".equals(type)) {
12185                    final PackageSetting ps =
12186                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12187                    final List<PackageParser.Activity> systemActivities =
12188                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12189                    adjustPriority(systemActivities, intent);
12190                }
12191                if (DEBUG_SHOW_INFO) {
12192                    Log.v(TAG, "    IntentFilter:");
12193                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12194                }
12195                if (!intent.debugCheck()) {
12196                    Log.w(TAG, "==> For Activity " + a.info.name);
12197                }
12198                addFilter(intent);
12199            }
12200        }
12201
12202        public final void removeActivity(PackageParser.Activity a, String type) {
12203            mActivities.remove(a.getComponentName());
12204            if (DEBUG_SHOW_INFO) {
12205                Log.v(TAG, "  " + type + " "
12206                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12207                                : a.info.name) + ":");
12208                Log.v(TAG, "    Class=" + a.info.name);
12209            }
12210            final int NI = a.intents.size();
12211            for (int j=0; j<NI; j++) {
12212                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12213                if (DEBUG_SHOW_INFO) {
12214                    Log.v(TAG, "    IntentFilter:");
12215                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12216                }
12217                removeFilter(intent);
12218            }
12219        }
12220
12221        @Override
12222        protected boolean allowFilterResult(
12223                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12224            ActivityInfo filterAi = filter.activity.info;
12225            for (int i=dest.size()-1; i>=0; i--) {
12226                ActivityInfo destAi = dest.get(i).activityInfo;
12227                if (destAi.name == filterAi.name
12228                        && destAi.packageName == filterAi.packageName) {
12229                    return false;
12230                }
12231            }
12232            return true;
12233        }
12234
12235        @Override
12236        protected ActivityIntentInfo[] newArray(int size) {
12237            return new ActivityIntentInfo[size];
12238        }
12239
12240        @Override
12241        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12242            if (!sUserManager.exists(userId)) return true;
12243            PackageParser.Package p = filter.activity.owner;
12244            if (p != null) {
12245                PackageSetting ps = (PackageSetting)p.mExtras;
12246                if (ps != null) {
12247                    // System apps are never considered stopped for purposes of
12248                    // filtering, because there may be no way for the user to
12249                    // actually re-launch them.
12250                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12251                            && ps.getStopped(userId);
12252                }
12253            }
12254            return false;
12255        }
12256
12257        @Override
12258        protected boolean isPackageForFilter(String packageName,
12259                PackageParser.ActivityIntentInfo info) {
12260            return packageName.equals(info.activity.owner.packageName);
12261        }
12262
12263        @Override
12264        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12265                int match, int userId) {
12266            if (!sUserManager.exists(userId)) return null;
12267            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12268                return null;
12269            }
12270            final PackageParser.Activity activity = info.activity;
12271            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12272            if (ps == null) {
12273                return null;
12274            }
12275            final PackageUserState userState = ps.readUserState(userId);
12276            ActivityInfo ai =
12277                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12278            if (ai == null) {
12279                return null;
12280            }
12281            final boolean matchExplicitlyVisibleOnly =
12282                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12283            final boolean matchVisibleToInstantApp =
12284                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12285            final boolean componentVisible =
12286                    matchVisibleToInstantApp
12287                    && info.isVisibleToInstantApp()
12288                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12289            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12290            // throw out filters that aren't visible to ephemeral apps
12291            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12292                return null;
12293            }
12294            // throw out instant app filters if we're not explicitly requesting them
12295            if (!matchInstantApp && userState.instantApp) {
12296                return null;
12297            }
12298            // throw out instant app filters if updates are available; will trigger
12299            // instant app resolution
12300            if (userState.instantApp && ps.isUpdateAvailable()) {
12301                return null;
12302            }
12303            final ResolveInfo res = new ResolveInfo();
12304            res.activityInfo = ai;
12305            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12306                res.filter = info;
12307            }
12308            if (info != null) {
12309                res.handleAllWebDataURI = info.handleAllWebDataURI();
12310            }
12311            res.priority = info.getPriority();
12312            res.preferredOrder = activity.owner.mPreferredOrder;
12313            //System.out.println("Result: " + res.activityInfo.className +
12314            //                   " = " + res.priority);
12315            res.match = match;
12316            res.isDefault = info.hasDefault;
12317            res.labelRes = info.labelRes;
12318            res.nonLocalizedLabel = info.nonLocalizedLabel;
12319            if (userNeedsBadging(userId)) {
12320                res.noResourceId = true;
12321            } else {
12322                res.icon = info.icon;
12323            }
12324            res.iconResourceId = info.icon;
12325            res.system = res.activityInfo.applicationInfo.isSystemApp();
12326            res.isInstantAppAvailable = userState.instantApp;
12327            return res;
12328        }
12329
12330        @Override
12331        protected void sortResults(List<ResolveInfo> results) {
12332            Collections.sort(results, mResolvePrioritySorter);
12333        }
12334
12335        @Override
12336        protected void dumpFilter(PrintWriter out, String prefix,
12337                PackageParser.ActivityIntentInfo filter) {
12338            out.print(prefix); out.print(
12339                    Integer.toHexString(System.identityHashCode(filter.activity)));
12340                    out.print(' ');
12341                    filter.activity.printComponentShortName(out);
12342                    out.print(" filter ");
12343                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12344        }
12345
12346        @Override
12347        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12348            return filter.activity;
12349        }
12350
12351        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12352            PackageParser.Activity activity = (PackageParser.Activity)label;
12353            out.print(prefix); out.print(
12354                    Integer.toHexString(System.identityHashCode(activity)));
12355                    out.print(' ');
12356                    activity.printComponentShortName(out);
12357            if (count > 1) {
12358                out.print(" ("); out.print(count); out.print(" filters)");
12359            }
12360            out.println();
12361        }
12362
12363        // Keys are String (activity class name), values are Activity.
12364        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12365                = new ArrayMap<ComponentName, PackageParser.Activity>();
12366        private int mFlags;
12367    }
12368
12369    private final class ServiceIntentResolver
12370            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12371        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12372                boolean defaultOnly, int userId) {
12373            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12374            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12375        }
12376
12377        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12378                int userId) {
12379            if (!sUserManager.exists(userId)) return null;
12380            mFlags = flags;
12381            return super.queryIntent(intent, resolvedType,
12382                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12383                    userId);
12384        }
12385
12386        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12387                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12388            if (!sUserManager.exists(userId)) return null;
12389            if (packageServices == null) {
12390                return null;
12391            }
12392            mFlags = flags;
12393            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12394            final int N = packageServices.size();
12395            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12396                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12397
12398            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12399            for (int i = 0; i < N; ++i) {
12400                intentFilters = packageServices.get(i).intents;
12401                if (intentFilters != null && intentFilters.size() > 0) {
12402                    PackageParser.ServiceIntentInfo[] array =
12403                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12404                    intentFilters.toArray(array);
12405                    listCut.add(array);
12406                }
12407            }
12408            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12409        }
12410
12411        public final void addService(PackageParser.Service s) {
12412            mServices.put(s.getComponentName(), s);
12413            if (DEBUG_SHOW_INFO) {
12414                Log.v(TAG, "  "
12415                        + (s.info.nonLocalizedLabel != null
12416                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12417                Log.v(TAG, "    Class=" + s.info.name);
12418            }
12419            final int NI = s.intents.size();
12420            int j;
12421            for (j=0; j<NI; j++) {
12422                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12423                if (DEBUG_SHOW_INFO) {
12424                    Log.v(TAG, "    IntentFilter:");
12425                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12426                }
12427                if (!intent.debugCheck()) {
12428                    Log.w(TAG, "==> For Service " + s.info.name);
12429                }
12430                addFilter(intent);
12431            }
12432        }
12433
12434        public final void removeService(PackageParser.Service s) {
12435            mServices.remove(s.getComponentName());
12436            if (DEBUG_SHOW_INFO) {
12437                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12438                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12439                Log.v(TAG, "    Class=" + s.info.name);
12440            }
12441            final int NI = s.intents.size();
12442            int j;
12443            for (j=0; j<NI; j++) {
12444                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12445                if (DEBUG_SHOW_INFO) {
12446                    Log.v(TAG, "    IntentFilter:");
12447                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12448                }
12449                removeFilter(intent);
12450            }
12451        }
12452
12453        @Override
12454        protected boolean allowFilterResult(
12455                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12456            ServiceInfo filterSi = filter.service.info;
12457            for (int i=dest.size()-1; i>=0; i--) {
12458                ServiceInfo destAi = dest.get(i).serviceInfo;
12459                if (destAi.name == filterSi.name
12460                        && destAi.packageName == filterSi.packageName) {
12461                    return false;
12462                }
12463            }
12464            return true;
12465        }
12466
12467        @Override
12468        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12469            return new PackageParser.ServiceIntentInfo[size];
12470        }
12471
12472        @Override
12473        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12474            if (!sUserManager.exists(userId)) return true;
12475            PackageParser.Package p = filter.service.owner;
12476            if (p != null) {
12477                PackageSetting ps = (PackageSetting)p.mExtras;
12478                if (ps != null) {
12479                    // System apps are never considered stopped for purposes of
12480                    // filtering, because there may be no way for the user to
12481                    // actually re-launch them.
12482                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12483                            && ps.getStopped(userId);
12484                }
12485            }
12486            return false;
12487        }
12488
12489        @Override
12490        protected boolean isPackageForFilter(String packageName,
12491                PackageParser.ServiceIntentInfo info) {
12492            return packageName.equals(info.service.owner.packageName);
12493        }
12494
12495        @Override
12496        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12497                int match, int userId) {
12498            if (!sUserManager.exists(userId)) return null;
12499            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12500            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12501                return null;
12502            }
12503            final PackageParser.Service service = info.service;
12504            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12505            if (ps == null) {
12506                return null;
12507            }
12508            final PackageUserState userState = ps.readUserState(userId);
12509            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12510                    userState, userId);
12511            if (si == null) {
12512                return null;
12513            }
12514            final boolean matchVisibleToInstantApp =
12515                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12516            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12517            // throw out filters that aren't visible to ephemeral apps
12518            if (matchVisibleToInstantApp
12519                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12520                return null;
12521            }
12522            // throw out ephemeral filters if we're not explicitly requesting them
12523            if (!isInstantApp && userState.instantApp) {
12524                return null;
12525            }
12526            // throw out instant app filters if updates are available; will trigger
12527            // instant app resolution
12528            if (userState.instantApp && ps.isUpdateAvailable()) {
12529                return null;
12530            }
12531            final ResolveInfo res = new ResolveInfo();
12532            res.serviceInfo = si;
12533            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12534                res.filter = filter;
12535            }
12536            res.priority = info.getPriority();
12537            res.preferredOrder = service.owner.mPreferredOrder;
12538            res.match = match;
12539            res.isDefault = info.hasDefault;
12540            res.labelRes = info.labelRes;
12541            res.nonLocalizedLabel = info.nonLocalizedLabel;
12542            res.icon = info.icon;
12543            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12544            return res;
12545        }
12546
12547        @Override
12548        protected void sortResults(List<ResolveInfo> results) {
12549            Collections.sort(results, mResolvePrioritySorter);
12550        }
12551
12552        @Override
12553        protected void dumpFilter(PrintWriter out, String prefix,
12554                PackageParser.ServiceIntentInfo filter) {
12555            out.print(prefix); out.print(
12556                    Integer.toHexString(System.identityHashCode(filter.service)));
12557                    out.print(' ');
12558                    filter.service.printComponentShortName(out);
12559                    out.print(" filter ");
12560                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12561        }
12562
12563        @Override
12564        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12565            return filter.service;
12566        }
12567
12568        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12569            PackageParser.Service service = (PackageParser.Service)label;
12570            out.print(prefix); out.print(
12571                    Integer.toHexString(System.identityHashCode(service)));
12572                    out.print(' ');
12573                    service.printComponentShortName(out);
12574            if (count > 1) {
12575                out.print(" ("); out.print(count); out.print(" filters)");
12576            }
12577            out.println();
12578        }
12579
12580//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12581//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12582//            final List<ResolveInfo> retList = Lists.newArrayList();
12583//            while (i.hasNext()) {
12584//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12585//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12586//                    retList.add(resolveInfo);
12587//                }
12588//            }
12589//            return retList;
12590//        }
12591
12592        // Keys are String (activity class name), values are Activity.
12593        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12594                = new ArrayMap<ComponentName, PackageParser.Service>();
12595        private int mFlags;
12596    }
12597
12598    private final class ProviderIntentResolver
12599            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12601                boolean defaultOnly, int userId) {
12602            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12603            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12604        }
12605
12606        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12607                int userId) {
12608            if (!sUserManager.exists(userId))
12609                return null;
12610            mFlags = flags;
12611            return super.queryIntent(intent, resolvedType,
12612                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12613                    userId);
12614        }
12615
12616        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12617                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12618            if (!sUserManager.exists(userId))
12619                return null;
12620            if (packageProviders == null) {
12621                return null;
12622            }
12623            mFlags = flags;
12624            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12625            final int N = packageProviders.size();
12626            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12627                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12628
12629            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12630            for (int i = 0; i < N; ++i) {
12631                intentFilters = packageProviders.get(i).intents;
12632                if (intentFilters != null && intentFilters.size() > 0) {
12633                    PackageParser.ProviderIntentInfo[] array =
12634                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12635                    intentFilters.toArray(array);
12636                    listCut.add(array);
12637                }
12638            }
12639            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12640        }
12641
12642        public final void addProvider(PackageParser.Provider p) {
12643            if (mProviders.containsKey(p.getComponentName())) {
12644                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12645                return;
12646            }
12647
12648            mProviders.put(p.getComponentName(), p);
12649            if (DEBUG_SHOW_INFO) {
12650                Log.v(TAG, "  "
12651                        + (p.info.nonLocalizedLabel != null
12652                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12653                Log.v(TAG, "    Class=" + p.info.name);
12654            }
12655            final int NI = p.intents.size();
12656            int j;
12657            for (j = 0; j < NI; j++) {
12658                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12659                if (DEBUG_SHOW_INFO) {
12660                    Log.v(TAG, "    IntentFilter:");
12661                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12662                }
12663                if (!intent.debugCheck()) {
12664                    Log.w(TAG, "==> For Provider " + p.info.name);
12665                }
12666                addFilter(intent);
12667            }
12668        }
12669
12670        public final void removeProvider(PackageParser.Provider p) {
12671            mProviders.remove(p.getComponentName());
12672            if (DEBUG_SHOW_INFO) {
12673                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12674                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12675                Log.v(TAG, "    Class=" + p.info.name);
12676            }
12677            final int NI = p.intents.size();
12678            int j;
12679            for (j = 0; j < NI; j++) {
12680                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12681                if (DEBUG_SHOW_INFO) {
12682                    Log.v(TAG, "    IntentFilter:");
12683                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12684                }
12685                removeFilter(intent);
12686            }
12687        }
12688
12689        @Override
12690        protected boolean allowFilterResult(
12691                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12692            ProviderInfo filterPi = filter.provider.info;
12693            for (int i = dest.size() - 1; i >= 0; i--) {
12694                ProviderInfo destPi = dest.get(i).providerInfo;
12695                if (destPi.name == filterPi.name
12696                        && destPi.packageName == filterPi.packageName) {
12697                    return false;
12698                }
12699            }
12700            return true;
12701        }
12702
12703        @Override
12704        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12705            return new PackageParser.ProviderIntentInfo[size];
12706        }
12707
12708        @Override
12709        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12710            if (!sUserManager.exists(userId))
12711                return true;
12712            PackageParser.Package p = filter.provider.owner;
12713            if (p != null) {
12714                PackageSetting ps = (PackageSetting) p.mExtras;
12715                if (ps != null) {
12716                    // System apps are never considered stopped for purposes of
12717                    // filtering, because there may be no way for the user to
12718                    // actually re-launch them.
12719                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12720                            && ps.getStopped(userId);
12721                }
12722            }
12723            return false;
12724        }
12725
12726        @Override
12727        protected boolean isPackageForFilter(String packageName,
12728                PackageParser.ProviderIntentInfo info) {
12729            return packageName.equals(info.provider.owner.packageName);
12730        }
12731
12732        @Override
12733        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12734                int match, int userId) {
12735            if (!sUserManager.exists(userId))
12736                return null;
12737            final PackageParser.ProviderIntentInfo info = filter;
12738            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12739                return null;
12740            }
12741            final PackageParser.Provider provider = info.provider;
12742            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12743            if (ps == null) {
12744                return null;
12745            }
12746            final PackageUserState userState = ps.readUserState(userId);
12747            final boolean matchVisibleToInstantApp =
12748                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12749            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12750            // throw out filters that aren't visible to instant applications
12751            if (matchVisibleToInstantApp
12752                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12753                return null;
12754            }
12755            // throw out instant application filters if we're not explicitly requesting them
12756            if (!isInstantApp && userState.instantApp) {
12757                return null;
12758            }
12759            // throw out instant application filters if updates are available; will trigger
12760            // instant application resolution
12761            if (userState.instantApp && ps.isUpdateAvailable()) {
12762                return null;
12763            }
12764            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12765                    userState, userId);
12766            if (pi == null) {
12767                return null;
12768            }
12769            final ResolveInfo res = new ResolveInfo();
12770            res.providerInfo = pi;
12771            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12772                res.filter = filter;
12773            }
12774            res.priority = info.getPriority();
12775            res.preferredOrder = provider.owner.mPreferredOrder;
12776            res.match = match;
12777            res.isDefault = info.hasDefault;
12778            res.labelRes = info.labelRes;
12779            res.nonLocalizedLabel = info.nonLocalizedLabel;
12780            res.icon = info.icon;
12781            res.system = res.providerInfo.applicationInfo.isSystemApp();
12782            return res;
12783        }
12784
12785        @Override
12786        protected void sortResults(List<ResolveInfo> results) {
12787            Collections.sort(results, mResolvePrioritySorter);
12788        }
12789
12790        @Override
12791        protected void dumpFilter(PrintWriter out, String prefix,
12792                PackageParser.ProviderIntentInfo filter) {
12793            out.print(prefix);
12794            out.print(
12795                    Integer.toHexString(System.identityHashCode(filter.provider)));
12796            out.print(' ');
12797            filter.provider.printComponentShortName(out);
12798            out.print(" filter ");
12799            out.println(Integer.toHexString(System.identityHashCode(filter)));
12800        }
12801
12802        @Override
12803        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12804            return filter.provider;
12805        }
12806
12807        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12808            PackageParser.Provider provider = (PackageParser.Provider)label;
12809            out.print(prefix); out.print(
12810                    Integer.toHexString(System.identityHashCode(provider)));
12811                    out.print(' ');
12812                    provider.printComponentShortName(out);
12813            if (count > 1) {
12814                out.print(" ("); out.print(count); out.print(" filters)");
12815            }
12816            out.println();
12817        }
12818
12819        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12820                = new ArrayMap<ComponentName, PackageParser.Provider>();
12821        private int mFlags;
12822    }
12823
12824    static final class EphemeralIntentResolver
12825            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12826        /**
12827         * The result that has the highest defined order. Ordering applies on a
12828         * per-package basis. Mapping is from package name to Pair of order and
12829         * EphemeralResolveInfo.
12830         * <p>
12831         * NOTE: This is implemented as a field variable for convenience and efficiency.
12832         * By having a field variable, we're able to track filter ordering as soon as
12833         * a non-zero order is defined. Otherwise, multiple loops across the result set
12834         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12835         * this needs to be contained entirely within {@link #filterResults}.
12836         */
12837        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12838
12839        @Override
12840        protected AuxiliaryResolveInfo[] newArray(int size) {
12841            return new AuxiliaryResolveInfo[size];
12842        }
12843
12844        @Override
12845        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12846            return true;
12847        }
12848
12849        @Override
12850        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12851                int userId) {
12852            if (!sUserManager.exists(userId)) {
12853                return null;
12854            }
12855            final String packageName = responseObj.resolveInfo.getPackageName();
12856            final Integer order = responseObj.getOrder();
12857            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12858                    mOrderResult.get(packageName);
12859            // ordering is enabled and this item's order isn't high enough
12860            if (lastOrderResult != null && lastOrderResult.first >= order) {
12861                return null;
12862            }
12863            final InstantAppResolveInfo res = responseObj.resolveInfo;
12864            if (order > 0) {
12865                // non-zero order, enable ordering
12866                mOrderResult.put(packageName, new Pair<>(order, res));
12867            }
12868            return responseObj;
12869        }
12870
12871        @Override
12872        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12873            // only do work if ordering is enabled [most of the time it won't be]
12874            if (mOrderResult.size() == 0) {
12875                return;
12876            }
12877            int resultSize = results.size();
12878            for (int i = 0; i < resultSize; i++) {
12879                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12880                final String packageName = info.getPackageName();
12881                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12882                if (savedInfo == null) {
12883                    // package doesn't having ordering
12884                    continue;
12885                }
12886                if (savedInfo.second == info) {
12887                    // circled back to the highest ordered item; remove from order list
12888                    mOrderResult.remove(packageName);
12889                    if (mOrderResult.size() == 0) {
12890                        // no more ordered items
12891                        break;
12892                    }
12893                    continue;
12894                }
12895                // item has a worse order, remove it from the result list
12896                results.remove(i);
12897                resultSize--;
12898                i--;
12899            }
12900        }
12901    }
12902
12903    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12904            new Comparator<ResolveInfo>() {
12905        public int compare(ResolveInfo r1, ResolveInfo r2) {
12906            int v1 = r1.priority;
12907            int v2 = r2.priority;
12908            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12909            if (v1 != v2) {
12910                return (v1 > v2) ? -1 : 1;
12911            }
12912            v1 = r1.preferredOrder;
12913            v2 = r2.preferredOrder;
12914            if (v1 != v2) {
12915                return (v1 > v2) ? -1 : 1;
12916            }
12917            if (r1.isDefault != r2.isDefault) {
12918                return r1.isDefault ? -1 : 1;
12919            }
12920            v1 = r1.match;
12921            v2 = r2.match;
12922            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12923            if (v1 != v2) {
12924                return (v1 > v2) ? -1 : 1;
12925            }
12926            if (r1.system != r2.system) {
12927                return r1.system ? -1 : 1;
12928            }
12929            if (r1.activityInfo != null) {
12930                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12931            }
12932            if (r1.serviceInfo != null) {
12933                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12934            }
12935            if (r1.providerInfo != null) {
12936                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12937            }
12938            return 0;
12939        }
12940    };
12941
12942    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12943            new Comparator<ProviderInfo>() {
12944        public int compare(ProviderInfo p1, ProviderInfo p2) {
12945            final int v1 = p1.initOrder;
12946            final int v2 = p2.initOrder;
12947            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12948        }
12949    };
12950
12951    @Override
12952    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12953            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12954            final int[] userIds, int[] instantUserIds) {
12955        mHandler.post(new Runnable() {
12956            @Override
12957            public void run() {
12958                try {
12959                    final IActivityManager am = ActivityManager.getService();
12960                    if (am == null) return;
12961                    final int[] resolvedUserIds;
12962                    if (userIds == null) {
12963                        resolvedUserIds = am.getRunningUserIds();
12964                    } else {
12965                        resolvedUserIds = userIds;
12966                    }
12967                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12968                            resolvedUserIds, false);
12969                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
12970                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12971                                instantUserIds, true);
12972                    }
12973                } catch (RemoteException ex) {
12974                }
12975            }
12976        });
12977    }
12978
12979    /**
12980     * Sends a broadcast for the given action.
12981     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
12982     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
12983     * the system and applications allowed to see instant applications to receive package
12984     * lifecycle events for instant applications.
12985     */
12986    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
12987            int flags, String targetPkg, IIntentReceiver finishedReceiver,
12988            int[] userIds, boolean isInstantApp)
12989                    throws RemoteException {
12990        for (int id : userIds) {
12991            final Intent intent = new Intent(action,
12992                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12993            final String[] requiredPermissions =
12994                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
12995            if (extras != null) {
12996                intent.putExtras(extras);
12997            }
12998            if (targetPkg != null) {
12999                intent.setPackage(targetPkg);
13000            }
13001            // Modify the UID when posting to other users
13002            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13003            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13004                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13005                intent.putExtra(Intent.EXTRA_UID, uid);
13006            }
13007            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13008            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13009            if (DEBUG_BROADCASTS) {
13010                RuntimeException here = new RuntimeException("here");
13011                here.fillInStackTrace();
13012                Slog.d(TAG, "Sending to user " + id + ": "
13013                        + intent.toShortString(false, true, false, false)
13014                        + " " + intent.getExtras(), here);
13015            }
13016            am.broadcastIntent(null, intent, null, finishedReceiver,
13017                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13018                    null, finishedReceiver != null, false, id);
13019        }
13020    }
13021
13022    /**
13023     * Check if the external storage media is available. This is true if there
13024     * is a mounted external storage medium or if the external storage is
13025     * emulated.
13026     */
13027    private boolean isExternalMediaAvailable() {
13028        return mMediaMounted || Environment.isExternalStorageEmulated();
13029    }
13030
13031    @Override
13032    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13033        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13034            return null;
13035        }
13036        // writer
13037        synchronized (mPackages) {
13038            if (!isExternalMediaAvailable()) {
13039                // If the external storage is no longer mounted at this point,
13040                // the caller may not have been able to delete all of this
13041                // packages files and can not delete any more.  Bail.
13042                return null;
13043            }
13044            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13045            if (lastPackage != null) {
13046                pkgs.remove(lastPackage);
13047            }
13048            if (pkgs.size() > 0) {
13049                return pkgs.get(0);
13050            }
13051        }
13052        return null;
13053    }
13054
13055    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13056        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13057                userId, andCode ? 1 : 0, packageName);
13058        if (mSystemReady) {
13059            msg.sendToTarget();
13060        } else {
13061            if (mPostSystemReadyMessages == null) {
13062                mPostSystemReadyMessages = new ArrayList<>();
13063            }
13064            mPostSystemReadyMessages.add(msg);
13065        }
13066    }
13067
13068    void startCleaningPackages() {
13069        // reader
13070        if (!isExternalMediaAvailable()) {
13071            return;
13072        }
13073        synchronized (mPackages) {
13074            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13075                return;
13076            }
13077        }
13078        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13079        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13080        IActivityManager am = ActivityManager.getService();
13081        if (am != null) {
13082            int dcsUid = -1;
13083            synchronized (mPackages) {
13084                if (!mDefaultContainerWhitelisted) {
13085                    mDefaultContainerWhitelisted = true;
13086                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13087                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13088                }
13089            }
13090            try {
13091                if (dcsUid > 0) {
13092                    am.backgroundWhitelistUid(dcsUid);
13093                }
13094                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13095                        UserHandle.USER_SYSTEM);
13096            } catch (RemoteException e) {
13097            }
13098        }
13099    }
13100
13101    @Override
13102    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13103            int installFlags, String installerPackageName, int userId) {
13104        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13105
13106        final int callingUid = Binder.getCallingUid();
13107        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13108                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13109
13110        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13111            try {
13112                if (observer != null) {
13113                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13114                }
13115            } catch (RemoteException re) {
13116            }
13117            return;
13118        }
13119
13120        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13121            installFlags |= PackageManager.INSTALL_FROM_ADB;
13122
13123        } else {
13124            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13125            // about installerPackageName.
13126
13127            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13128            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13129        }
13130
13131        UserHandle user;
13132        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13133            user = UserHandle.ALL;
13134        } else {
13135            user = new UserHandle(userId);
13136        }
13137
13138        // Only system components can circumvent runtime permissions when installing.
13139        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13140                && mContext.checkCallingOrSelfPermission(Manifest.permission
13141                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13142            throw new SecurityException("You need the "
13143                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13144                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13145        }
13146
13147        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13148                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13149            throw new IllegalArgumentException(
13150                    "New installs into ASEC containers no longer supported");
13151        }
13152
13153        final File originFile = new File(originPath);
13154        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13155
13156        final Message msg = mHandler.obtainMessage(INIT_COPY);
13157        final VerificationInfo verificationInfo = new VerificationInfo(
13158                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13159        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13160                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13161                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13162                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13163        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13164        msg.obj = params;
13165
13166        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13167                System.identityHashCode(msg.obj));
13168        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13169                System.identityHashCode(msg.obj));
13170
13171        mHandler.sendMessage(msg);
13172    }
13173
13174
13175    /**
13176     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13177     * it is acting on behalf on an enterprise or the user).
13178     *
13179     * Note that the ordering of the conditionals in this method is important. The checks we perform
13180     * are as follows, in this order:
13181     *
13182     * 1) If the install is being performed by a system app, we can trust the app to have set the
13183     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13184     *    what it is.
13185     * 2) If the install is being performed by a device or profile owner app, the install reason
13186     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13187     *    set the install reason correctly. If the app targets an older SDK version where install
13188     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13189     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13190     * 3) In all other cases, the install is being performed by a regular app that is neither part
13191     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13192     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13193     *    set to enterprise policy and if so, change it to unknown instead.
13194     */
13195    private int fixUpInstallReason(String installerPackageName, int installerUid,
13196            int installReason) {
13197        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13198                == PERMISSION_GRANTED) {
13199            // If the install is being performed by a system app, we trust that app to have set the
13200            // install reason correctly.
13201            return installReason;
13202        }
13203
13204        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13205            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13206        if (dpm != null) {
13207            ComponentName owner = null;
13208            try {
13209                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13210                if (owner == null) {
13211                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13212                }
13213            } catch (RemoteException e) {
13214            }
13215            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13216                // If the install is being performed by a device or profile owner, the install
13217                // reason should be enterprise policy.
13218                return PackageManager.INSTALL_REASON_POLICY;
13219            }
13220        }
13221
13222        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13223            // If the install is being performed by a regular app (i.e. neither system app nor
13224            // device or profile owner), we have no reason to believe that the app is acting on
13225            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13226            // change it to unknown instead.
13227            return PackageManager.INSTALL_REASON_UNKNOWN;
13228        }
13229
13230        // If the install is being performed by a regular app and the install reason was set to any
13231        // value but enterprise policy, leave the install reason unchanged.
13232        return installReason;
13233    }
13234
13235    void installStage(String packageName, File stagedDir,
13236            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13237            String installerPackageName, int installerUid, UserHandle user,
13238            Certificate[][] certificates) {
13239        if (DEBUG_EPHEMERAL) {
13240            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13241                Slog.d(TAG, "Ephemeral install of " + packageName);
13242            }
13243        }
13244        final VerificationInfo verificationInfo = new VerificationInfo(
13245                sessionParams.originatingUri, sessionParams.referrerUri,
13246                sessionParams.originatingUid, installerUid);
13247
13248        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13249
13250        final Message msg = mHandler.obtainMessage(INIT_COPY);
13251        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13252                sessionParams.installReason);
13253        final InstallParams params = new InstallParams(origin, null, observer,
13254                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13255                verificationInfo, user, sessionParams.abiOverride,
13256                sessionParams.grantedRuntimePermissions, certificates, installReason);
13257        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13258        msg.obj = params;
13259
13260        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13261                System.identityHashCode(msg.obj));
13262        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13263                System.identityHashCode(msg.obj));
13264
13265        mHandler.sendMessage(msg);
13266    }
13267
13268    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13269            int userId) {
13270        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13271        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13272        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13273        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13274        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13275                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13276
13277        // Send a session commit broadcast
13278        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13279        info.installReason = pkgSetting.getInstallReason(userId);
13280        info.appPackageName = packageName;
13281        sendSessionCommitBroadcast(info, userId);
13282    }
13283
13284    @Override
13285    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13286            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13287        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13288            return;
13289        }
13290        Bundle extras = new Bundle(1);
13291        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13292        final int uid = UserHandle.getUid(
13293                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13294        extras.putInt(Intent.EXTRA_UID, uid);
13295
13296        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13297                packageName, extras, 0, null, null, userIds, instantUserIds);
13298        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13299            mHandler.post(() -> {
13300                        for (int userId : userIds) {
13301                            sendBootCompletedBroadcastToSystemApp(
13302                                    packageName, includeStopped, userId);
13303                        }
13304                    }
13305            );
13306        }
13307    }
13308
13309    /**
13310     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13311     * automatically without needing an explicit launch.
13312     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13313     */
13314    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13315            int userId) {
13316        // If user is not running, the app didn't miss any broadcast
13317        if (!mUserManagerInternal.isUserRunning(userId)) {
13318            return;
13319        }
13320        final IActivityManager am = ActivityManager.getService();
13321        try {
13322            // Deliver LOCKED_BOOT_COMPLETED first
13323            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13324                    .setPackage(packageName);
13325            if (includeStopped) {
13326                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13327            }
13328            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13329            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13330                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13331
13332            // Deliver BOOT_COMPLETED only if user is unlocked
13333            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13334                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13335                if (includeStopped) {
13336                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13337                }
13338                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13339                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13340            }
13341        } catch (RemoteException e) {
13342            throw e.rethrowFromSystemServer();
13343        }
13344    }
13345
13346    @Override
13347    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13348            int userId) {
13349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13350        PackageSetting pkgSetting;
13351        final int callingUid = Binder.getCallingUid();
13352        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13353                true /* requireFullPermission */, true /* checkShell */,
13354                "setApplicationHiddenSetting for user " + userId);
13355
13356        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13357            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13358            return false;
13359        }
13360
13361        long callingId = Binder.clearCallingIdentity();
13362        try {
13363            boolean sendAdded = false;
13364            boolean sendRemoved = false;
13365            // writer
13366            synchronized (mPackages) {
13367                pkgSetting = mSettings.mPackages.get(packageName);
13368                if (pkgSetting == null) {
13369                    return false;
13370                }
13371                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13372                    return false;
13373                }
13374                // Do not allow "android" is being disabled
13375                if ("android".equals(packageName)) {
13376                    Slog.w(TAG, "Cannot hide package: android");
13377                    return false;
13378                }
13379                // Cannot hide static shared libs as they are considered
13380                // a part of the using app (emulating static linking). Also
13381                // static libs are installed always on internal storage.
13382                PackageParser.Package pkg = mPackages.get(packageName);
13383                if (pkg != null && pkg.staticSharedLibName != null) {
13384                    Slog.w(TAG, "Cannot hide package: " + packageName
13385                            + " providing static shared library: "
13386                            + pkg.staticSharedLibName);
13387                    return false;
13388                }
13389                // Only allow protected packages to hide themselves.
13390                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13391                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13392                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13393                    return false;
13394                }
13395
13396                if (pkgSetting.getHidden(userId) != hidden) {
13397                    pkgSetting.setHidden(hidden, userId);
13398                    mSettings.writePackageRestrictionsLPr(userId);
13399                    if (hidden) {
13400                        sendRemoved = true;
13401                    } else {
13402                        sendAdded = true;
13403                    }
13404                }
13405            }
13406            if (sendAdded) {
13407                sendPackageAddedForUser(packageName, pkgSetting, userId);
13408                return true;
13409            }
13410            if (sendRemoved) {
13411                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13412                        "hiding pkg");
13413                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13414                return true;
13415            }
13416        } finally {
13417            Binder.restoreCallingIdentity(callingId);
13418        }
13419        return false;
13420    }
13421
13422    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13423            int userId) {
13424        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13425        info.removedPackage = packageName;
13426        info.installerPackageName = pkgSetting.installerPackageName;
13427        info.removedUsers = new int[] {userId};
13428        info.broadcastUsers = new int[] {userId};
13429        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13430        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13431    }
13432
13433    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13434        if (pkgList.length > 0) {
13435            Bundle extras = new Bundle(1);
13436            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13437
13438            sendPackageBroadcast(
13439                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13440                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13441                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13442                    new int[] {userId}, null);
13443        }
13444    }
13445
13446    /**
13447     * Returns true if application is not found or there was an error. Otherwise it returns
13448     * the hidden state of the package for the given user.
13449     */
13450    @Override
13451    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13452        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13453        final int callingUid = Binder.getCallingUid();
13454        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13455                true /* requireFullPermission */, false /* checkShell */,
13456                "getApplicationHidden for user " + userId);
13457        PackageSetting ps;
13458        long callingId = Binder.clearCallingIdentity();
13459        try {
13460            // writer
13461            synchronized (mPackages) {
13462                ps = mSettings.mPackages.get(packageName);
13463                if (ps == null) {
13464                    return true;
13465                }
13466                if (filterAppAccessLPr(ps, callingUid, userId)) {
13467                    return true;
13468                }
13469                return ps.getHidden(userId);
13470            }
13471        } finally {
13472            Binder.restoreCallingIdentity(callingId);
13473        }
13474    }
13475
13476    /**
13477     * @hide
13478     */
13479    @Override
13480    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13481            int installReason) {
13482        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13483                null);
13484        PackageSetting pkgSetting;
13485        final int callingUid = Binder.getCallingUid();
13486        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13487                true /* requireFullPermission */, true /* checkShell */,
13488                "installExistingPackage for user " + userId);
13489        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13490            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13491        }
13492
13493        long callingId = Binder.clearCallingIdentity();
13494        try {
13495            boolean installed = false;
13496            final boolean instantApp =
13497                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13498            final boolean fullApp =
13499                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13500
13501            // writer
13502            synchronized (mPackages) {
13503                pkgSetting = mSettings.mPackages.get(packageName);
13504                if (pkgSetting == null) {
13505                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13506                }
13507                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13508                    // only allow the existing package to be used if it's installed as a full
13509                    // application for at least one user
13510                    boolean installAllowed = false;
13511                    for (int checkUserId : sUserManager.getUserIds()) {
13512                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13513                        if (installAllowed) {
13514                            break;
13515                        }
13516                    }
13517                    if (!installAllowed) {
13518                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13519                    }
13520                }
13521                if (!pkgSetting.getInstalled(userId)) {
13522                    pkgSetting.setInstalled(true, userId);
13523                    pkgSetting.setHidden(false, userId);
13524                    pkgSetting.setInstallReason(installReason, userId);
13525                    mSettings.writePackageRestrictionsLPr(userId);
13526                    mSettings.writeKernelMappingLPr(pkgSetting);
13527                    installed = true;
13528                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13529                    // upgrade app from instant to full; we don't allow app downgrade
13530                    installed = true;
13531                }
13532                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13533            }
13534
13535            if (installed) {
13536                if (pkgSetting.pkg != null) {
13537                    synchronized (mInstallLock) {
13538                        // We don't need to freeze for a brand new install
13539                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13540                    }
13541                }
13542                sendPackageAddedForUser(packageName, pkgSetting, userId);
13543                synchronized (mPackages) {
13544                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13545                }
13546            }
13547        } finally {
13548            Binder.restoreCallingIdentity(callingId);
13549        }
13550
13551        return PackageManager.INSTALL_SUCCEEDED;
13552    }
13553
13554    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13555            boolean instantApp, boolean fullApp) {
13556        // no state specified; do nothing
13557        if (!instantApp && !fullApp) {
13558            return;
13559        }
13560        if (userId != UserHandle.USER_ALL) {
13561            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13562                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13563            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13564                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13565            }
13566        } else {
13567            for (int currentUserId : sUserManager.getUserIds()) {
13568                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13569                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13570                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13571                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13572                }
13573            }
13574        }
13575    }
13576
13577    boolean isUserRestricted(int userId, String restrictionKey) {
13578        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13579        if (restrictions.getBoolean(restrictionKey, false)) {
13580            Log.w(TAG, "User is restricted: " + restrictionKey);
13581            return true;
13582        }
13583        return false;
13584    }
13585
13586    @Override
13587    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13588            int userId) {
13589        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13590        final int callingUid = Binder.getCallingUid();
13591        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13592                true /* requireFullPermission */, true /* checkShell */,
13593                "setPackagesSuspended for user " + userId);
13594
13595        if (ArrayUtils.isEmpty(packageNames)) {
13596            return packageNames;
13597        }
13598
13599        // List of package names for whom the suspended state has changed.
13600        List<String> changedPackages = new ArrayList<>(packageNames.length);
13601        // List of package names for whom the suspended state is not set as requested in this
13602        // method.
13603        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13604        long callingId = Binder.clearCallingIdentity();
13605        try {
13606            for (int i = 0; i < packageNames.length; i++) {
13607                String packageName = packageNames[i];
13608                boolean changed = false;
13609                final int appId;
13610                synchronized (mPackages) {
13611                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13612                    if (pkgSetting == null
13613                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13614                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13615                                + "\". Skipping suspending/un-suspending.");
13616                        unactionedPackages.add(packageName);
13617                        continue;
13618                    }
13619                    appId = pkgSetting.appId;
13620                    if (pkgSetting.getSuspended(userId) != suspended) {
13621                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13622                            unactionedPackages.add(packageName);
13623                            continue;
13624                        }
13625                        pkgSetting.setSuspended(suspended, userId);
13626                        mSettings.writePackageRestrictionsLPr(userId);
13627                        changed = true;
13628                        changedPackages.add(packageName);
13629                    }
13630                }
13631
13632                if (changed && suspended) {
13633                    killApplication(packageName, UserHandle.getUid(userId, appId),
13634                            "suspending package");
13635                }
13636            }
13637        } finally {
13638            Binder.restoreCallingIdentity(callingId);
13639        }
13640
13641        if (!changedPackages.isEmpty()) {
13642            sendPackagesSuspendedForUser(changedPackages.toArray(
13643                    new String[changedPackages.size()]), userId, suspended);
13644        }
13645
13646        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13647    }
13648
13649    @Override
13650    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13651        final int callingUid = Binder.getCallingUid();
13652        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13653                true /* requireFullPermission */, false /* checkShell */,
13654                "isPackageSuspendedForUser for user " + userId);
13655        synchronized (mPackages) {
13656            final PackageSetting ps = mSettings.mPackages.get(packageName);
13657            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13658                throw new IllegalArgumentException("Unknown target package: " + packageName);
13659            }
13660            return ps.getSuspended(userId);
13661        }
13662    }
13663
13664    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13665        if (isPackageDeviceAdmin(packageName, userId)) {
13666            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13667                    + "\": has an active device admin");
13668            return false;
13669        }
13670
13671        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13672        if (packageName.equals(activeLauncherPackageName)) {
13673            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13674                    + "\": contains the active launcher");
13675            return false;
13676        }
13677
13678        if (packageName.equals(mRequiredInstallerPackage)) {
13679            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13680                    + "\": required for package installation");
13681            return false;
13682        }
13683
13684        if (packageName.equals(mRequiredUninstallerPackage)) {
13685            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13686                    + "\": required for package uninstallation");
13687            return false;
13688        }
13689
13690        if (packageName.equals(mRequiredVerifierPackage)) {
13691            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13692                    + "\": required for package verification");
13693            return false;
13694        }
13695
13696        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13697            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13698                    + "\": is the default dialer");
13699            return false;
13700        }
13701
13702        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13703            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13704                    + "\": protected package");
13705            return false;
13706        }
13707
13708        // Cannot suspend static shared libs as they are considered
13709        // a part of the using app (emulating static linking). Also
13710        // static libs are installed always on internal storage.
13711        PackageParser.Package pkg = mPackages.get(packageName);
13712        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13713            Slog.w(TAG, "Cannot suspend package: " + packageName
13714                    + " providing static shared library: "
13715                    + pkg.staticSharedLibName);
13716            return false;
13717        }
13718
13719        return true;
13720    }
13721
13722    private String getActiveLauncherPackageName(int userId) {
13723        Intent intent = new Intent(Intent.ACTION_MAIN);
13724        intent.addCategory(Intent.CATEGORY_HOME);
13725        ResolveInfo resolveInfo = resolveIntent(
13726                intent,
13727                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13728                PackageManager.MATCH_DEFAULT_ONLY,
13729                userId);
13730
13731        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13732    }
13733
13734    private String getDefaultDialerPackageName(int userId) {
13735        synchronized (mPackages) {
13736            return mSettings.getDefaultDialerPackageNameLPw(userId);
13737        }
13738    }
13739
13740    @Override
13741    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13742        mContext.enforceCallingOrSelfPermission(
13743                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13744                "Only package verification agents can verify applications");
13745
13746        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13747        final PackageVerificationResponse response = new PackageVerificationResponse(
13748                verificationCode, Binder.getCallingUid());
13749        msg.arg1 = id;
13750        msg.obj = response;
13751        mHandler.sendMessage(msg);
13752    }
13753
13754    @Override
13755    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13756            long millisecondsToDelay) {
13757        mContext.enforceCallingOrSelfPermission(
13758                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13759                "Only package verification agents can extend verification timeouts");
13760
13761        final PackageVerificationState state = mPendingVerification.get(id);
13762        final PackageVerificationResponse response = new PackageVerificationResponse(
13763                verificationCodeAtTimeout, Binder.getCallingUid());
13764
13765        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13766            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13767        }
13768        if (millisecondsToDelay < 0) {
13769            millisecondsToDelay = 0;
13770        }
13771        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13772                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13773            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13774        }
13775
13776        if ((state != null) && !state.timeoutExtended()) {
13777            state.extendTimeout();
13778
13779            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13780            msg.arg1 = id;
13781            msg.obj = response;
13782            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13783        }
13784    }
13785
13786    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13787            int verificationCode, UserHandle user) {
13788        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13789        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13790        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13791        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13792        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13793
13794        mContext.sendBroadcastAsUser(intent, user,
13795                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13796    }
13797
13798    private ComponentName matchComponentForVerifier(String packageName,
13799            List<ResolveInfo> receivers) {
13800        ActivityInfo targetReceiver = null;
13801
13802        final int NR = receivers.size();
13803        for (int i = 0; i < NR; i++) {
13804            final ResolveInfo info = receivers.get(i);
13805            if (info.activityInfo == null) {
13806                continue;
13807            }
13808
13809            if (packageName.equals(info.activityInfo.packageName)) {
13810                targetReceiver = info.activityInfo;
13811                break;
13812            }
13813        }
13814
13815        if (targetReceiver == null) {
13816            return null;
13817        }
13818
13819        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13820    }
13821
13822    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13823            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13824        if (pkgInfo.verifiers.length == 0) {
13825            return null;
13826        }
13827
13828        final int N = pkgInfo.verifiers.length;
13829        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13830        for (int i = 0; i < N; i++) {
13831            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13832
13833            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13834                    receivers);
13835            if (comp == null) {
13836                continue;
13837            }
13838
13839            final int verifierUid = getUidForVerifier(verifierInfo);
13840            if (verifierUid == -1) {
13841                continue;
13842            }
13843
13844            if (DEBUG_VERIFY) {
13845                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13846                        + " with the correct signature");
13847            }
13848            sufficientVerifiers.add(comp);
13849            verificationState.addSufficientVerifier(verifierUid);
13850        }
13851
13852        return sufficientVerifiers;
13853    }
13854
13855    private int getUidForVerifier(VerifierInfo verifierInfo) {
13856        synchronized (mPackages) {
13857            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13858            if (pkg == null) {
13859                return -1;
13860            } else if (pkg.mSignatures.length != 1) {
13861                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13862                        + " has more than one signature; ignoring");
13863                return -1;
13864            }
13865
13866            /*
13867             * If the public key of the package's signature does not match
13868             * our expected public key, then this is a different package and
13869             * we should skip.
13870             */
13871
13872            final byte[] expectedPublicKey;
13873            try {
13874                final Signature verifierSig = pkg.mSignatures[0];
13875                final PublicKey publicKey = verifierSig.getPublicKey();
13876                expectedPublicKey = publicKey.getEncoded();
13877            } catch (CertificateException e) {
13878                return -1;
13879            }
13880
13881            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13882
13883            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13884                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13885                        + " does not have the expected public key; ignoring");
13886                return -1;
13887            }
13888
13889            return pkg.applicationInfo.uid;
13890        }
13891    }
13892
13893    @Override
13894    public void finishPackageInstall(int token, boolean didLaunch) {
13895        enforceSystemOrRoot("Only the system is allowed to finish installs");
13896
13897        if (DEBUG_INSTALL) {
13898            Slog.v(TAG, "BM finishing package install for " + token);
13899        }
13900        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13901
13902        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13903        mHandler.sendMessage(msg);
13904    }
13905
13906    /**
13907     * Get the verification agent timeout.  Used for both the APK verifier and the
13908     * intent filter verifier.
13909     *
13910     * @return verification timeout in milliseconds
13911     */
13912    private long getVerificationTimeout() {
13913        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13914                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13915                DEFAULT_VERIFICATION_TIMEOUT);
13916    }
13917
13918    /**
13919     * Get the default verification agent response code.
13920     *
13921     * @return default verification response code
13922     */
13923    private int getDefaultVerificationResponse(UserHandle user) {
13924        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13925            return PackageManager.VERIFICATION_REJECT;
13926        }
13927        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13928                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13929                DEFAULT_VERIFICATION_RESPONSE);
13930    }
13931
13932    /**
13933     * Check whether or not package verification has been enabled.
13934     *
13935     * @return true if verification should be performed
13936     */
13937    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13938        if (!DEFAULT_VERIFY_ENABLE) {
13939            return false;
13940        }
13941
13942        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13943
13944        // Check if installing from ADB
13945        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13946            // Do not run verification in a test harness environment
13947            if (ActivityManager.isRunningInTestHarness()) {
13948                return false;
13949            }
13950            if (ensureVerifyAppsEnabled) {
13951                return true;
13952            }
13953            // Check if the developer does not want package verification for ADB installs
13954            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13955                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13956                return false;
13957            }
13958        } else {
13959            // only when not installed from ADB, skip verification for instant apps when
13960            // the installer and verifier are the same.
13961            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13962                if (mInstantAppInstallerActivity != null
13963                        && mInstantAppInstallerActivity.packageName.equals(
13964                                mRequiredVerifierPackage)) {
13965                    try {
13966                        mContext.getSystemService(AppOpsManager.class)
13967                                .checkPackage(installerUid, mRequiredVerifierPackage);
13968                        if (DEBUG_VERIFY) {
13969                            Slog.i(TAG, "disable verification for instant app");
13970                        }
13971                        return false;
13972                    } catch (SecurityException ignore) { }
13973                }
13974            }
13975        }
13976
13977        if (ensureVerifyAppsEnabled) {
13978            return true;
13979        }
13980
13981        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13982                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13983    }
13984
13985    @Override
13986    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13987            throws RemoteException {
13988        mContext.enforceCallingOrSelfPermission(
13989                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13990                "Only intentfilter verification agents can verify applications");
13991
13992        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13993        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13994                Binder.getCallingUid(), verificationCode, failedDomains);
13995        msg.arg1 = id;
13996        msg.obj = response;
13997        mHandler.sendMessage(msg);
13998    }
13999
14000    @Override
14001    public int getIntentVerificationStatus(String packageName, int userId) {
14002        final int callingUid = Binder.getCallingUid();
14003        if (UserHandle.getUserId(callingUid) != userId) {
14004            mContext.enforceCallingOrSelfPermission(
14005                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14006                    "getIntentVerificationStatus" + userId);
14007        }
14008        if (getInstantAppPackageName(callingUid) != null) {
14009            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14010        }
14011        synchronized (mPackages) {
14012            final PackageSetting ps = mSettings.mPackages.get(packageName);
14013            if (ps == null
14014                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14015                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14016            }
14017            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14018        }
14019    }
14020
14021    @Override
14022    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14023        mContext.enforceCallingOrSelfPermission(
14024                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14025
14026        boolean result = false;
14027        synchronized (mPackages) {
14028            final PackageSetting ps = mSettings.mPackages.get(packageName);
14029            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14030                return false;
14031            }
14032            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14033        }
14034        if (result) {
14035            scheduleWritePackageRestrictionsLocked(userId);
14036        }
14037        return result;
14038    }
14039
14040    @Override
14041    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14042            String packageName) {
14043        final int callingUid = Binder.getCallingUid();
14044        if (getInstantAppPackageName(callingUid) != null) {
14045            return ParceledListSlice.emptyList();
14046        }
14047        synchronized (mPackages) {
14048            final PackageSetting ps = mSettings.mPackages.get(packageName);
14049            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14050                return ParceledListSlice.emptyList();
14051            }
14052            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14053        }
14054    }
14055
14056    @Override
14057    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14058        if (TextUtils.isEmpty(packageName)) {
14059            return ParceledListSlice.emptyList();
14060        }
14061        final int callingUid = Binder.getCallingUid();
14062        final int callingUserId = UserHandle.getUserId(callingUid);
14063        synchronized (mPackages) {
14064            PackageParser.Package pkg = mPackages.get(packageName);
14065            if (pkg == null || pkg.activities == null) {
14066                return ParceledListSlice.emptyList();
14067            }
14068            if (pkg.mExtras == null) {
14069                return ParceledListSlice.emptyList();
14070            }
14071            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14072            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14073                return ParceledListSlice.emptyList();
14074            }
14075            final int count = pkg.activities.size();
14076            ArrayList<IntentFilter> result = new ArrayList<>();
14077            for (int n=0; n<count; n++) {
14078                PackageParser.Activity activity = pkg.activities.get(n);
14079                if (activity.intents != null && activity.intents.size() > 0) {
14080                    result.addAll(activity.intents);
14081                }
14082            }
14083            return new ParceledListSlice<>(result);
14084        }
14085    }
14086
14087    @Override
14088    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14089        mContext.enforceCallingOrSelfPermission(
14090                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14091        if (UserHandle.getCallingUserId() != userId) {
14092            mContext.enforceCallingOrSelfPermission(
14093                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14094        }
14095
14096        synchronized (mPackages) {
14097            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14098            if (packageName != null) {
14099                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14100                        packageName, userId);
14101            }
14102            return result;
14103        }
14104    }
14105
14106    @Override
14107    public String getDefaultBrowserPackageName(int userId) {
14108        if (UserHandle.getCallingUserId() != userId) {
14109            mContext.enforceCallingOrSelfPermission(
14110                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14111        }
14112        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14113            return null;
14114        }
14115        synchronized (mPackages) {
14116            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14117        }
14118    }
14119
14120    /**
14121     * Get the "allow unknown sources" setting.
14122     *
14123     * @return the current "allow unknown sources" setting
14124     */
14125    private int getUnknownSourcesSettings() {
14126        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14127                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14128                -1);
14129    }
14130
14131    @Override
14132    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14133        final int callingUid = Binder.getCallingUid();
14134        if (getInstantAppPackageName(callingUid) != null) {
14135            return;
14136        }
14137        // writer
14138        synchronized (mPackages) {
14139            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14140            if (targetPackageSetting == null
14141                    || filterAppAccessLPr(
14142                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14143                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14144            }
14145
14146            PackageSetting installerPackageSetting;
14147            if (installerPackageName != null) {
14148                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14149                if (installerPackageSetting == null) {
14150                    throw new IllegalArgumentException("Unknown installer package: "
14151                            + installerPackageName);
14152                }
14153            } else {
14154                installerPackageSetting = null;
14155            }
14156
14157            Signature[] callerSignature;
14158            Object obj = mSettings.getUserIdLPr(callingUid);
14159            if (obj != null) {
14160                if (obj instanceof SharedUserSetting) {
14161                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14162                } else if (obj instanceof PackageSetting) {
14163                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14164                } else {
14165                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14166                }
14167            } else {
14168                throw new SecurityException("Unknown calling UID: " + callingUid);
14169            }
14170
14171            // Verify: can't set installerPackageName to a package that is
14172            // not signed with the same cert as the caller.
14173            if (installerPackageSetting != null) {
14174                if (compareSignatures(callerSignature,
14175                        installerPackageSetting.signatures.mSignatures)
14176                        != PackageManager.SIGNATURE_MATCH) {
14177                    throw new SecurityException(
14178                            "Caller does not have same cert as new installer package "
14179                            + installerPackageName);
14180                }
14181            }
14182
14183            // Verify: if target already has an installer package, it must
14184            // be signed with the same cert as the caller.
14185            if (targetPackageSetting.installerPackageName != null) {
14186                PackageSetting setting = mSettings.mPackages.get(
14187                        targetPackageSetting.installerPackageName);
14188                // If the currently set package isn't valid, then it's always
14189                // okay to change it.
14190                if (setting != null) {
14191                    if (compareSignatures(callerSignature,
14192                            setting.signatures.mSignatures)
14193                            != PackageManager.SIGNATURE_MATCH) {
14194                        throw new SecurityException(
14195                                "Caller does not have same cert as old installer package "
14196                                + targetPackageSetting.installerPackageName);
14197                    }
14198                }
14199            }
14200
14201            // Okay!
14202            targetPackageSetting.installerPackageName = installerPackageName;
14203            if (installerPackageName != null) {
14204                mSettings.mInstallerPackages.add(installerPackageName);
14205            }
14206            scheduleWriteSettingsLocked();
14207        }
14208    }
14209
14210    @Override
14211    public void setApplicationCategoryHint(String packageName, int categoryHint,
14212            String callerPackageName) {
14213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14214            throw new SecurityException("Instant applications don't have access to this method");
14215        }
14216        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14217                callerPackageName);
14218        synchronized (mPackages) {
14219            PackageSetting ps = mSettings.mPackages.get(packageName);
14220            if (ps == null) {
14221                throw new IllegalArgumentException("Unknown target package " + packageName);
14222            }
14223            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14224                throw new IllegalArgumentException("Unknown target package " + packageName);
14225            }
14226            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14227                throw new IllegalArgumentException("Calling package " + callerPackageName
14228                        + " is not installer for " + packageName);
14229            }
14230
14231            if (ps.categoryHint != categoryHint) {
14232                ps.categoryHint = categoryHint;
14233                scheduleWriteSettingsLocked();
14234            }
14235        }
14236    }
14237
14238    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14239        // Queue up an async operation since the package installation may take a little while.
14240        mHandler.post(new Runnable() {
14241            public void run() {
14242                mHandler.removeCallbacks(this);
14243                 // Result object to be returned
14244                PackageInstalledInfo res = new PackageInstalledInfo();
14245                res.setReturnCode(currentStatus);
14246                res.uid = -1;
14247                res.pkg = null;
14248                res.removedInfo = null;
14249                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14250                    args.doPreInstall(res.returnCode);
14251                    synchronized (mInstallLock) {
14252                        installPackageTracedLI(args, res);
14253                    }
14254                    args.doPostInstall(res.returnCode, res.uid);
14255                }
14256
14257                // A restore should be performed at this point if (a) the install
14258                // succeeded, (b) the operation is not an update, and (c) the new
14259                // package has not opted out of backup participation.
14260                final boolean update = res.removedInfo != null
14261                        && res.removedInfo.removedPackage != null;
14262                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14263                boolean doRestore = !update
14264                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14265
14266                // Set up the post-install work request bookkeeping.  This will be used
14267                // and cleaned up by the post-install event handling regardless of whether
14268                // there's a restore pass performed.  Token values are >= 1.
14269                int token;
14270                if (mNextInstallToken < 0) mNextInstallToken = 1;
14271                token = mNextInstallToken++;
14272
14273                PostInstallData data = new PostInstallData(args, res);
14274                mRunningInstalls.put(token, data);
14275                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14276
14277                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14278                    // Pass responsibility to the Backup Manager.  It will perform a
14279                    // restore if appropriate, then pass responsibility back to the
14280                    // Package Manager to run the post-install observer callbacks
14281                    // and broadcasts.
14282                    IBackupManager bm = IBackupManager.Stub.asInterface(
14283                            ServiceManager.getService(Context.BACKUP_SERVICE));
14284                    if (bm != null) {
14285                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14286                                + " to BM for possible restore");
14287                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14288                        try {
14289                            // TODO: http://b/22388012
14290                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14291                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14292                            } else {
14293                                doRestore = false;
14294                            }
14295                        } catch (RemoteException e) {
14296                            // can't happen; the backup manager is local
14297                        } catch (Exception e) {
14298                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14299                            doRestore = false;
14300                        }
14301                    } else {
14302                        Slog.e(TAG, "Backup Manager not found!");
14303                        doRestore = false;
14304                    }
14305                }
14306
14307                if (!doRestore) {
14308                    // No restore possible, or the Backup Manager was mysteriously not
14309                    // available -- just fire the post-install work request directly.
14310                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14311
14312                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14313
14314                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14315                    mHandler.sendMessage(msg);
14316                }
14317            }
14318        });
14319    }
14320
14321    /**
14322     * Callback from PackageSettings whenever an app is first transitioned out of the
14323     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14324     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14325     * here whether the app is the target of an ongoing install, and only send the
14326     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14327     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14328     * handling.
14329     */
14330    void notifyFirstLaunch(final String packageName, final String installerPackage,
14331            final int userId) {
14332        // Serialize this with the rest of the install-process message chain.  In the
14333        // restore-at-install case, this Runnable will necessarily run before the
14334        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14335        // are coherent.  In the non-restore case, the app has already completed install
14336        // and been launched through some other means, so it is not in a problematic
14337        // state for observers to see the FIRST_LAUNCH signal.
14338        mHandler.post(new Runnable() {
14339            @Override
14340            public void run() {
14341                for (int i = 0; i < mRunningInstalls.size(); i++) {
14342                    final PostInstallData data = mRunningInstalls.valueAt(i);
14343                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14344                        continue;
14345                    }
14346                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14347                        // right package; but is it for the right user?
14348                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14349                            if (userId == data.res.newUsers[uIndex]) {
14350                                if (DEBUG_BACKUP) {
14351                                    Slog.i(TAG, "Package " + packageName
14352                                            + " being restored so deferring FIRST_LAUNCH");
14353                                }
14354                                return;
14355                            }
14356                        }
14357                    }
14358                }
14359                // didn't find it, so not being restored
14360                if (DEBUG_BACKUP) {
14361                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14362                }
14363                final boolean isInstantApp = isInstantApp(packageName, userId);
14364                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14365                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14366                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14367            }
14368        });
14369    }
14370
14371    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14372            int[] userIds, int[] instantUserIds) {
14373        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14374                installerPkg, null, userIds, instantUserIds);
14375    }
14376
14377    private abstract class HandlerParams {
14378        private static final int MAX_RETRIES = 4;
14379
14380        /**
14381         * Number of times startCopy() has been attempted and had a non-fatal
14382         * error.
14383         */
14384        private int mRetries = 0;
14385
14386        /** User handle for the user requesting the information or installation. */
14387        private final UserHandle mUser;
14388        String traceMethod;
14389        int traceCookie;
14390
14391        HandlerParams(UserHandle user) {
14392            mUser = user;
14393        }
14394
14395        UserHandle getUser() {
14396            return mUser;
14397        }
14398
14399        HandlerParams setTraceMethod(String traceMethod) {
14400            this.traceMethod = traceMethod;
14401            return this;
14402        }
14403
14404        HandlerParams setTraceCookie(int traceCookie) {
14405            this.traceCookie = traceCookie;
14406            return this;
14407        }
14408
14409        final boolean startCopy() {
14410            boolean res;
14411            try {
14412                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14413
14414                if (++mRetries > MAX_RETRIES) {
14415                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14416                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14417                    handleServiceError();
14418                    return false;
14419                } else {
14420                    handleStartCopy();
14421                    res = true;
14422                }
14423            } catch (RemoteException e) {
14424                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14425                mHandler.sendEmptyMessage(MCS_RECONNECT);
14426                res = false;
14427            }
14428            handleReturnCode();
14429            return res;
14430        }
14431
14432        final void serviceError() {
14433            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14434            handleServiceError();
14435            handleReturnCode();
14436        }
14437
14438        abstract void handleStartCopy() throws RemoteException;
14439        abstract void handleServiceError();
14440        abstract void handleReturnCode();
14441    }
14442
14443    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14444        for (File path : paths) {
14445            try {
14446                mcs.clearDirectory(path.getAbsolutePath());
14447            } catch (RemoteException e) {
14448            }
14449        }
14450    }
14451
14452    static class OriginInfo {
14453        /**
14454         * Location where install is coming from, before it has been
14455         * copied/renamed into place. This could be a single monolithic APK
14456         * file, or a cluster directory. This location may be untrusted.
14457         */
14458        final File file;
14459
14460        /**
14461         * Flag indicating that {@link #file} or {@link #cid} has already been
14462         * staged, meaning downstream users don't need to defensively copy the
14463         * contents.
14464         */
14465        final boolean staged;
14466
14467        /**
14468         * Flag indicating that {@link #file} or {@link #cid} is an already
14469         * installed app that is being moved.
14470         */
14471        final boolean existing;
14472
14473        final String resolvedPath;
14474        final File resolvedFile;
14475
14476        static OriginInfo fromNothing() {
14477            return new OriginInfo(null, false, false);
14478        }
14479
14480        static OriginInfo fromUntrustedFile(File file) {
14481            return new OriginInfo(file, false, false);
14482        }
14483
14484        static OriginInfo fromExistingFile(File file) {
14485            return new OriginInfo(file, false, true);
14486        }
14487
14488        static OriginInfo fromStagedFile(File file) {
14489            return new OriginInfo(file, true, false);
14490        }
14491
14492        private OriginInfo(File file, boolean staged, boolean existing) {
14493            this.file = file;
14494            this.staged = staged;
14495            this.existing = existing;
14496
14497            if (file != null) {
14498                resolvedPath = file.getAbsolutePath();
14499                resolvedFile = file;
14500            } else {
14501                resolvedPath = null;
14502                resolvedFile = null;
14503            }
14504        }
14505    }
14506
14507    static class MoveInfo {
14508        final int moveId;
14509        final String fromUuid;
14510        final String toUuid;
14511        final String packageName;
14512        final String dataAppName;
14513        final int appId;
14514        final String seinfo;
14515        final int targetSdkVersion;
14516
14517        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14518                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14519            this.moveId = moveId;
14520            this.fromUuid = fromUuid;
14521            this.toUuid = toUuid;
14522            this.packageName = packageName;
14523            this.dataAppName = dataAppName;
14524            this.appId = appId;
14525            this.seinfo = seinfo;
14526            this.targetSdkVersion = targetSdkVersion;
14527        }
14528    }
14529
14530    static class VerificationInfo {
14531        /** A constant used to indicate that a uid value is not present. */
14532        public static final int NO_UID = -1;
14533
14534        /** URI referencing where the package was downloaded from. */
14535        final Uri originatingUri;
14536
14537        /** HTTP referrer URI associated with the originatingURI. */
14538        final Uri referrer;
14539
14540        /** UID of the application that the install request originated from. */
14541        final int originatingUid;
14542
14543        /** UID of application requesting the install */
14544        final int installerUid;
14545
14546        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14547            this.originatingUri = originatingUri;
14548            this.referrer = referrer;
14549            this.originatingUid = originatingUid;
14550            this.installerUid = installerUid;
14551        }
14552    }
14553
14554    class InstallParams extends HandlerParams {
14555        final OriginInfo origin;
14556        final MoveInfo move;
14557        final IPackageInstallObserver2 observer;
14558        int installFlags;
14559        final String installerPackageName;
14560        final String volumeUuid;
14561        private InstallArgs mArgs;
14562        private int mRet;
14563        final String packageAbiOverride;
14564        final String[] grantedRuntimePermissions;
14565        final VerificationInfo verificationInfo;
14566        final Certificate[][] certificates;
14567        final int installReason;
14568
14569        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14570                int installFlags, String installerPackageName, String volumeUuid,
14571                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14572                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14573            super(user);
14574            this.origin = origin;
14575            this.move = move;
14576            this.observer = observer;
14577            this.installFlags = installFlags;
14578            this.installerPackageName = installerPackageName;
14579            this.volumeUuid = volumeUuid;
14580            this.verificationInfo = verificationInfo;
14581            this.packageAbiOverride = packageAbiOverride;
14582            this.grantedRuntimePermissions = grantedPermissions;
14583            this.certificates = certificates;
14584            this.installReason = installReason;
14585        }
14586
14587        @Override
14588        public String toString() {
14589            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14590                    + " file=" + origin.file + "}";
14591        }
14592
14593        private int installLocationPolicy(PackageInfoLite pkgLite) {
14594            String packageName = pkgLite.packageName;
14595            int installLocation = pkgLite.installLocation;
14596            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14597            // reader
14598            synchronized (mPackages) {
14599                // Currently installed package which the new package is attempting to replace or
14600                // null if no such package is installed.
14601                PackageParser.Package installedPkg = mPackages.get(packageName);
14602                // Package which currently owns the data which the new package will own if installed.
14603                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14604                // will be null whereas dataOwnerPkg will contain information about the package
14605                // which was uninstalled while keeping its data.
14606                PackageParser.Package dataOwnerPkg = installedPkg;
14607                if (dataOwnerPkg  == null) {
14608                    PackageSetting ps = mSettings.mPackages.get(packageName);
14609                    if (ps != null) {
14610                        dataOwnerPkg = ps.pkg;
14611                    }
14612                }
14613
14614                if (dataOwnerPkg != null) {
14615                    // If installed, the package will get access to data left on the device by its
14616                    // predecessor. As a security measure, this is permited only if this is not a
14617                    // version downgrade or if the predecessor package is marked as debuggable and
14618                    // a downgrade is explicitly requested.
14619                    //
14620                    // On debuggable platform builds, downgrades are permitted even for
14621                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14622                    // not offer security guarantees and thus it's OK to disable some security
14623                    // mechanisms to make debugging/testing easier on those builds. However, even on
14624                    // debuggable builds downgrades of packages are permitted only if requested via
14625                    // installFlags. This is because we aim to keep the behavior of debuggable
14626                    // platform builds as close as possible to the behavior of non-debuggable
14627                    // platform builds.
14628                    final boolean downgradeRequested =
14629                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14630                    final boolean packageDebuggable =
14631                                (dataOwnerPkg.applicationInfo.flags
14632                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14633                    final boolean downgradePermitted =
14634                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14635                    if (!downgradePermitted) {
14636                        try {
14637                            checkDowngrade(dataOwnerPkg, pkgLite);
14638                        } catch (PackageManagerException e) {
14639                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14640                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14641                        }
14642                    }
14643                }
14644
14645                if (installedPkg != null) {
14646                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14647                        // Check for updated system application.
14648                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14649                            if (onSd) {
14650                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14651                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14652                            }
14653                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14654                        } else {
14655                            if (onSd) {
14656                                // Install flag overrides everything.
14657                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14658                            }
14659                            // If current upgrade specifies particular preference
14660                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14661                                // Application explicitly specified internal.
14662                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14663                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14664                                // App explictly prefers external. Let policy decide
14665                            } else {
14666                                // Prefer previous location
14667                                if (isExternal(installedPkg)) {
14668                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14669                                }
14670                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14671                            }
14672                        }
14673                    } else {
14674                        // Invalid install. Return error code
14675                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14676                    }
14677                }
14678            }
14679            // All the special cases have been taken care of.
14680            // Return result based on recommended install location.
14681            if (onSd) {
14682                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14683            }
14684            return pkgLite.recommendedInstallLocation;
14685        }
14686
14687        /*
14688         * Invoke remote method to get package information and install
14689         * location values. Override install location based on default
14690         * policy if needed and then create install arguments based
14691         * on the install location.
14692         */
14693        public void handleStartCopy() throws RemoteException {
14694            int ret = PackageManager.INSTALL_SUCCEEDED;
14695
14696            // If we're already staged, we've firmly committed to an install location
14697            if (origin.staged) {
14698                if (origin.file != null) {
14699                    installFlags |= PackageManager.INSTALL_INTERNAL;
14700                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14701                } else {
14702                    throw new IllegalStateException("Invalid stage location");
14703                }
14704            }
14705
14706            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14707            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14708            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14709            PackageInfoLite pkgLite = null;
14710
14711            if (onInt && onSd) {
14712                // Check if both bits are set.
14713                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14714                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14715            } else if (onSd && ephemeral) {
14716                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14717                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14718            } else {
14719                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14720                        packageAbiOverride);
14721
14722                if (DEBUG_EPHEMERAL && ephemeral) {
14723                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14724                }
14725
14726                /*
14727                 * If we have too little free space, try to free cache
14728                 * before giving up.
14729                 */
14730                if (!origin.staged && pkgLite.recommendedInstallLocation
14731                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14732                    // TODO: focus freeing disk space on the target device
14733                    final StorageManager storage = StorageManager.from(mContext);
14734                    final long lowThreshold = storage.getStorageLowBytes(
14735                            Environment.getDataDirectory());
14736
14737                    final long sizeBytes = mContainerService.calculateInstalledSize(
14738                            origin.resolvedPath, packageAbiOverride);
14739
14740                    try {
14741                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14742                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14743                                installFlags, packageAbiOverride);
14744                    } catch (InstallerException e) {
14745                        Slog.w(TAG, "Failed to free cache", e);
14746                    }
14747
14748                    /*
14749                     * The cache free must have deleted the file we
14750                     * downloaded to install.
14751                     *
14752                     * TODO: fix the "freeCache" call to not delete
14753                     *       the file we care about.
14754                     */
14755                    if (pkgLite.recommendedInstallLocation
14756                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14757                        pkgLite.recommendedInstallLocation
14758                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14759                    }
14760                }
14761            }
14762
14763            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14764                int loc = pkgLite.recommendedInstallLocation;
14765                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14766                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14767                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14768                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14769                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14770                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14771                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14772                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14773                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14774                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14775                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14776                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14777                } else {
14778                    // Override with defaults if needed.
14779                    loc = installLocationPolicy(pkgLite);
14780                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14781                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14782                    } else if (!onSd && !onInt) {
14783                        // Override install location with flags
14784                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14785                            // Set the flag to install on external media.
14786                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14787                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14788                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14789                            if (DEBUG_EPHEMERAL) {
14790                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14791                            }
14792                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14793                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14794                                    |PackageManager.INSTALL_INTERNAL);
14795                        } else {
14796                            // Make sure the flag for installing on external
14797                            // media is unset
14798                            installFlags |= PackageManager.INSTALL_INTERNAL;
14799                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14800                        }
14801                    }
14802                }
14803            }
14804
14805            final InstallArgs args = createInstallArgs(this);
14806            mArgs = args;
14807
14808            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14809                // TODO: http://b/22976637
14810                // Apps installed for "all" users use the device owner to verify the app
14811                UserHandle verifierUser = getUser();
14812                if (verifierUser == UserHandle.ALL) {
14813                    verifierUser = UserHandle.SYSTEM;
14814                }
14815
14816                /*
14817                 * Determine if we have any installed package verifiers. If we
14818                 * do, then we'll defer to them to verify the packages.
14819                 */
14820                final int requiredUid = mRequiredVerifierPackage == null ? -1
14821                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14822                                verifierUser.getIdentifier());
14823                final int installerUid =
14824                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14825                if (!origin.existing && requiredUid != -1
14826                        && isVerificationEnabled(
14827                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14828                    final Intent verification = new Intent(
14829                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14830                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14831                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14832                            PACKAGE_MIME_TYPE);
14833                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14834
14835                    // Query all live verifiers based on current user state
14836                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14837                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14838                            false /*allowDynamicSplits*/);
14839
14840                    if (DEBUG_VERIFY) {
14841                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14842                                + verification.toString() + " with " + pkgLite.verifiers.length
14843                                + " optional verifiers");
14844                    }
14845
14846                    final int verificationId = mPendingVerificationToken++;
14847
14848                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14849
14850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14851                            installerPackageName);
14852
14853                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14854                            installFlags);
14855
14856                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14857                            pkgLite.packageName);
14858
14859                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14860                            pkgLite.versionCode);
14861
14862                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
14863                            pkgLite.getLongVersionCode());
14864
14865                    if (verificationInfo != null) {
14866                        if (verificationInfo.originatingUri != null) {
14867                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14868                                    verificationInfo.originatingUri);
14869                        }
14870                        if (verificationInfo.referrer != null) {
14871                            verification.putExtra(Intent.EXTRA_REFERRER,
14872                                    verificationInfo.referrer);
14873                        }
14874                        if (verificationInfo.originatingUid >= 0) {
14875                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14876                                    verificationInfo.originatingUid);
14877                        }
14878                        if (verificationInfo.installerUid >= 0) {
14879                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14880                                    verificationInfo.installerUid);
14881                        }
14882                    }
14883
14884                    final PackageVerificationState verificationState = new PackageVerificationState(
14885                            requiredUid, args);
14886
14887                    mPendingVerification.append(verificationId, verificationState);
14888
14889                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14890                            receivers, verificationState);
14891
14892                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14893                    final long idleDuration = getVerificationTimeout();
14894
14895                    /*
14896                     * If any sufficient verifiers were listed in the package
14897                     * manifest, attempt to ask them.
14898                     */
14899                    if (sufficientVerifiers != null) {
14900                        final int N = sufficientVerifiers.size();
14901                        if (N == 0) {
14902                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14903                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14904                        } else {
14905                            for (int i = 0; i < N; i++) {
14906                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14907                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14908                                        verifierComponent.getPackageName(), idleDuration,
14909                                        verifierUser.getIdentifier(), false, "package verifier");
14910
14911                                final Intent sufficientIntent = new Intent(verification);
14912                                sufficientIntent.setComponent(verifierComponent);
14913                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14914                            }
14915                        }
14916                    }
14917
14918                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14919                            mRequiredVerifierPackage, receivers);
14920                    if (ret == PackageManager.INSTALL_SUCCEEDED
14921                            && mRequiredVerifierPackage != null) {
14922                        Trace.asyncTraceBegin(
14923                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14924                        /*
14925                         * Send the intent to the required verification agent,
14926                         * but only start the verification timeout after the
14927                         * target BroadcastReceivers have run.
14928                         */
14929                        verification.setComponent(requiredVerifierComponent);
14930                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14931                                mRequiredVerifierPackage, idleDuration,
14932                                verifierUser.getIdentifier(), false, "package verifier");
14933                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14934                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14935                                new BroadcastReceiver() {
14936                                    @Override
14937                                    public void onReceive(Context context, Intent intent) {
14938                                        final Message msg = mHandler
14939                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14940                                        msg.arg1 = verificationId;
14941                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14942                                    }
14943                                }, null, 0, null, null);
14944
14945                        /*
14946                         * We don't want the copy to proceed until verification
14947                         * succeeds, so null out this field.
14948                         */
14949                        mArgs = null;
14950                    }
14951                } else {
14952                    /*
14953                     * No package verification is enabled, so immediately start
14954                     * the remote call to initiate copy using temporary file.
14955                     */
14956                    ret = args.copyApk(mContainerService, true);
14957                }
14958            }
14959
14960            mRet = ret;
14961        }
14962
14963        @Override
14964        void handleReturnCode() {
14965            // If mArgs is null, then MCS couldn't be reached. When it
14966            // reconnects, it will try again to install. At that point, this
14967            // will succeed.
14968            if (mArgs != null) {
14969                processPendingInstall(mArgs, mRet);
14970            }
14971        }
14972
14973        @Override
14974        void handleServiceError() {
14975            mArgs = createInstallArgs(this);
14976            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14977        }
14978    }
14979
14980    private InstallArgs createInstallArgs(InstallParams params) {
14981        if (params.move != null) {
14982            return new MoveInstallArgs(params);
14983        } else {
14984            return new FileInstallArgs(params);
14985        }
14986    }
14987
14988    /**
14989     * Create args that describe an existing installed package. Typically used
14990     * when cleaning up old installs, or used as a move source.
14991     */
14992    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14993            String resourcePath, String[] instructionSets) {
14994        return new FileInstallArgs(codePath, resourcePath, instructionSets);
14995    }
14996
14997    static abstract class InstallArgs {
14998        /** @see InstallParams#origin */
14999        final OriginInfo origin;
15000        /** @see InstallParams#move */
15001        final MoveInfo move;
15002
15003        final IPackageInstallObserver2 observer;
15004        // Always refers to PackageManager flags only
15005        final int installFlags;
15006        final String installerPackageName;
15007        final String volumeUuid;
15008        final UserHandle user;
15009        final String abiOverride;
15010        final String[] installGrantPermissions;
15011        /** If non-null, drop an async trace when the install completes */
15012        final String traceMethod;
15013        final int traceCookie;
15014        final Certificate[][] certificates;
15015        final int installReason;
15016
15017        // The list of instruction sets supported by this app. This is currently
15018        // only used during the rmdex() phase to clean up resources. We can get rid of this
15019        // if we move dex files under the common app path.
15020        /* nullable */ String[] instructionSets;
15021
15022        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15023                int installFlags, String installerPackageName, String volumeUuid,
15024                UserHandle user, String[] instructionSets,
15025                String abiOverride, String[] installGrantPermissions,
15026                String traceMethod, int traceCookie, Certificate[][] certificates,
15027                int installReason) {
15028            this.origin = origin;
15029            this.move = move;
15030            this.installFlags = installFlags;
15031            this.observer = observer;
15032            this.installerPackageName = installerPackageName;
15033            this.volumeUuid = volumeUuid;
15034            this.user = user;
15035            this.instructionSets = instructionSets;
15036            this.abiOverride = abiOverride;
15037            this.installGrantPermissions = installGrantPermissions;
15038            this.traceMethod = traceMethod;
15039            this.traceCookie = traceCookie;
15040            this.certificates = certificates;
15041            this.installReason = installReason;
15042        }
15043
15044        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15045        abstract int doPreInstall(int status);
15046
15047        /**
15048         * Rename package into final resting place. All paths on the given
15049         * scanned package should be updated to reflect the rename.
15050         */
15051        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15052        abstract int doPostInstall(int status, int uid);
15053
15054        /** @see PackageSettingBase#codePathString */
15055        abstract String getCodePath();
15056        /** @see PackageSettingBase#resourcePathString */
15057        abstract String getResourcePath();
15058
15059        // Need installer lock especially for dex file removal.
15060        abstract void cleanUpResourcesLI();
15061        abstract boolean doPostDeleteLI(boolean delete);
15062
15063        /**
15064         * Called before the source arguments are copied. This is used mostly
15065         * for MoveParams when it needs to read the source file to put it in the
15066         * destination.
15067         */
15068        int doPreCopy() {
15069            return PackageManager.INSTALL_SUCCEEDED;
15070        }
15071
15072        /**
15073         * Called after the source arguments are copied. This is used mostly for
15074         * MoveParams when it needs to read the source file to put it in the
15075         * destination.
15076         */
15077        int doPostCopy(int uid) {
15078            return PackageManager.INSTALL_SUCCEEDED;
15079        }
15080
15081        protected boolean isFwdLocked() {
15082            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15083        }
15084
15085        protected boolean isExternalAsec() {
15086            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15087        }
15088
15089        protected boolean isEphemeral() {
15090            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15091        }
15092
15093        UserHandle getUser() {
15094            return user;
15095        }
15096    }
15097
15098    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15099        if (!allCodePaths.isEmpty()) {
15100            if (instructionSets == null) {
15101                throw new IllegalStateException("instructionSet == null");
15102            }
15103            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15104            for (String codePath : allCodePaths) {
15105                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15106                    try {
15107                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15108                    } catch (InstallerException ignored) {
15109                    }
15110                }
15111            }
15112        }
15113    }
15114
15115    /**
15116     * Logic to handle installation of non-ASEC applications, including copying
15117     * and renaming logic.
15118     */
15119    class FileInstallArgs extends InstallArgs {
15120        private File codeFile;
15121        private File resourceFile;
15122
15123        // Example topology:
15124        // /data/app/com.example/base.apk
15125        // /data/app/com.example/split_foo.apk
15126        // /data/app/com.example/lib/arm/libfoo.so
15127        // /data/app/com.example/lib/arm64/libfoo.so
15128        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15129
15130        /** New install */
15131        FileInstallArgs(InstallParams params) {
15132            super(params.origin, params.move, params.observer, params.installFlags,
15133                    params.installerPackageName, params.volumeUuid,
15134                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15135                    params.grantedRuntimePermissions,
15136                    params.traceMethod, params.traceCookie, params.certificates,
15137                    params.installReason);
15138            if (isFwdLocked()) {
15139                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15140            }
15141        }
15142
15143        /** Existing install */
15144        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15145            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15146                    null, null, null, 0, null /*certificates*/,
15147                    PackageManager.INSTALL_REASON_UNKNOWN);
15148            this.codeFile = (codePath != null) ? new File(codePath) : null;
15149            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15150        }
15151
15152        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15153            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15154            try {
15155                return doCopyApk(imcs, temp);
15156            } finally {
15157                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15158            }
15159        }
15160
15161        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15162            if (origin.staged) {
15163                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15164                codeFile = origin.file;
15165                resourceFile = origin.file;
15166                return PackageManager.INSTALL_SUCCEEDED;
15167            }
15168
15169            try {
15170                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15171                final File tempDir =
15172                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15173                codeFile = tempDir;
15174                resourceFile = tempDir;
15175            } catch (IOException e) {
15176                Slog.w(TAG, "Failed to create copy file: " + e);
15177                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15178            }
15179
15180            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15181                @Override
15182                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15183                    if (!FileUtils.isValidExtFilename(name)) {
15184                        throw new IllegalArgumentException("Invalid filename: " + name);
15185                    }
15186                    try {
15187                        final File file = new File(codeFile, name);
15188                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15189                                O_RDWR | O_CREAT, 0644);
15190                        Os.chmod(file.getAbsolutePath(), 0644);
15191                        return new ParcelFileDescriptor(fd);
15192                    } catch (ErrnoException e) {
15193                        throw new RemoteException("Failed to open: " + e.getMessage());
15194                    }
15195                }
15196            };
15197
15198            int ret = PackageManager.INSTALL_SUCCEEDED;
15199            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15200            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15201                Slog.e(TAG, "Failed to copy package");
15202                return ret;
15203            }
15204
15205            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15206            NativeLibraryHelper.Handle handle = null;
15207            try {
15208                handle = NativeLibraryHelper.Handle.create(codeFile);
15209                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15210                        abiOverride);
15211            } catch (IOException e) {
15212                Slog.e(TAG, "Copying native libraries failed", e);
15213                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15214            } finally {
15215                IoUtils.closeQuietly(handle);
15216            }
15217
15218            return ret;
15219        }
15220
15221        int doPreInstall(int status) {
15222            if (status != PackageManager.INSTALL_SUCCEEDED) {
15223                cleanUp();
15224            }
15225            return status;
15226        }
15227
15228        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15229            if (status != PackageManager.INSTALL_SUCCEEDED) {
15230                cleanUp();
15231                return false;
15232            }
15233
15234            final File targetDir = codeFile.getParentFile();
15235            final File beforeCodeFile = codeFile;
15236            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15237
15238            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15239            try {
15240                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15241            } catch (ErrnoException e) {
15242                Slog.w(TAG, "Failed to rename", e);
15243                return false;
15244            }
15245
15246            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15247                Slog.w(TAG, "Failed to restorecon");
15248                return false;
15249            }
15250
15251            // Reflect the rename internally
15252            codeFile = afterCodeFile;
15253            resourceFile = afterCodeFile;
15254
15255            // Reflect the rename in scanned details
15256            try {
15257                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15258            } catch (IOException e) {
15259                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15260                return false;
15261            }
15262            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15263                    afterCodeFile, pkg.baseCodePath));
15264            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15265                    afterCodeFile, pkg.splitCodePaths));
15266
15267            // Reflect the rename in app info
15268            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15269            pkg.setApplicationInfoCodePath(pkg.codePath);
15270            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15271            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15272            pkg.setApplicationInfoResourcePath(pkg.codePath);
15273            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15274            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15275
15276            return true;
15277        }
15278
15279        int doPostInstall(int status, int uid) {
15280            if (status != PackageManager.INSTALL_SUCCEEDED) {
15281                cleanUp();
15282            }
15283            return status;
15284        }
15285
15286        @Override
15287        String getCodePath() {
15288            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15289        }
15290
15291        @Override
15292        String getResourcePath() {
15293            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15294        }
15295
15296        private boolean cleanUp() {
15297            if (codeFile == null || !codeFile.exists()) {
15298                return false;
15299            }
15300
15301            removeCodePathLI(codeFile);
15302
15303            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15304                resourceFile.delete();
15305            }
15306
15307            return true;
15308        }
15309
15310        void cleanUpResourcesLI() {
15311            // Try enumerating all code paths before deleting
15312            List<String> allCodePaths = Collections.EMPTY_LIST;
15313            if (codeFile != null && codeFile.exists()) {
15314                try {
15315                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15316                    allCodePaths = pkg.getAllCodePaths();
15317                } catch (PackageParserException e) {
15318                    // Ignored; we tried our best
15319                }
15320            }
15321
15322            cleanUp();
15323            removeDexFiles(allCodePaths, instructionSets);
15324        }
15325
15326        boolean doPostDeleteLI(boolean delete) {
15327            // XXX err, shouldn't we respect the delete flag?
15328            cleanUpResourcesLI();
15329            return true;
15330        }
15331    }
15332
15333    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15334            PackageManagerException {
15335        if (copyRet < 0) {
15336            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15337                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15338                throw new PackageManagerException(copyRet, message);
15339            }
15340        }
15341    }
15342
15343    /**
15344     * Extract the StorageManagerService "container ID" from the full code path of an
15345     * .apk.
15346     */
15347    static String cidFromCodePath(String fullCodePath) {
15348        int eidx = fullCodePath.lastIndexOf("/");
15349        String subStr1 = fullCodePath.substring(0, eidx);
15350        int sidx = subStr1.lastIndexOf("/");
15351        return subStr1.substring(sidx+1, eidx);
15352    }
15353
15354    /**
15355     * Logic to handle movement of existing installed applications.
15356     */
15357    class MoveInstallArgs extends InstallArgs {
15358        private File codeFile;
15359        private File resourceFile;
15360
15361        /** New install */
15362        MoveInstallArgs(InstallParams params) {
15363            super(params.origin, params.move, params.observer, params.installFlags,
15364                    params.installerPackageName, params.volumeUuid,
15365                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15366                    params.grantedRuntimePermissions,
15367                    params.traceMethod, params.traceCookie, params.certificates,
15368                    params.installReason);
15369        }
15370
15371        int copyApk(IMediaContainerService imcs, boolean temp) {
15372            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15373                    + move.fromUuid + " to " + move.toUuid);
15374            synchronized (mInstaller) {
15375                try {
15376                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15377                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15378                } catch (InstallerException e) {
15379                    Slog.w(TAG, "Failed to move app", e);
15380                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15381                }
15382            }
15383
15384            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15385            resourceFile = codeFile;
15386            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15387
15388            return PackageManager.INSTALL_SUCCEEDED;
15389        }
15390
15391        int doPreInstall(int status) {
15392            if (status != PackageManager.INSTALL_SUCCEEDED) {
15393                cleanUp(move.toUuid);
15394            }
15395            return status;
15396        }
15397
15398        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15399            if (status != PackageManager.INSTALL_SUCCEEDED) {
15400                cleanUp(move.toUuid);
15401                return false;
15402            }
15403
15404            // Reflect the move in app info
15405            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15406            pkg.setApplicationInfoCodePath(pkg.codePath);
15407            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15408            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15409            pkg.setApplicationInfoResourcePath(pkg.codePath);
15410            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15411            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15412
15413            return true;
15414        }
15415
15416        int doPostInstall(int status, int uid) {
15417            if (status == PackageManager.INSTALL_SUCCEEDED) {
15418                cleanUp(move.fromUuid);
15419            } else {
15420                cleanUp(move.toUuid);
15421            }
15422            return status;
15423        }
15424
15425        @Override
15426        String getCodePath() {
15427            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15428        }
15429
15430        @Override
15431        String getResourcePath() {
15432            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15433        }
15434
15435        private boolean cleanUp(String volumeUuid) {
15436            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15437                    move.dataAppName);
15438            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15439            final int[] userIds = sUserManager.getUserIds();
15440            synchronized (mInstallLock) {
15441                // Clean up both app data and code
15442                // All package moves are frozen until finished
15443                for (int userId : userIds) {
15444                    try {
15445                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15446                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15447                    } catch (InstallerException e) {
15448                        Slog.w(TAG, String.valueOf(e));
15449                    }
15450                }
15451                removeCodePathLI(codeFile);
15452            }
15453            return true;
15454        }
15455
15456        void cleanUpResourcesLI() {
15457            throw new UnsupportedOperationException();
15458        }
15459
15460        boolean doPostDeleteLI(boolean delete) {
15461            throw new UnsupportedOperationException();
15462        }
15463    }
15464
15465    static String getAsecPackageName(String packageCid) {
15466        int idx = packageCid.lastIndexOf("-");
15467        if (idx == -1) {
15468            return packageCid;
15469        }
15470        return packageCid.substring(0, idx);
15471    }
15472
15473    // Utility method used to create code paths based on package name and available index.
15474    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15475        String idxStr = "";
15476        int idx = 1;
15477        // Fall back to default value of idx=1 if prefix is not
15478        // part of oldCodePath
15479        if (oldCodePath != null) {
15480            String subStr = oldCodePath;
15481            // Drop the suffix right away
15482            if (suffix != null && subStr.endsWith(suffix)) {
15483                subStr = subStr.substring(0, subStr.length() - suffix.length());
15484            }
15485            // If oldCodePath already contains prefix find out the
15486            // ending index to either increment or decrement.
15487            int sidx = subStr.lastIndexOf(prefix);
15488            if (sidx != -1) {
15489                subStr = subStr.substring(sidx + prefix.length());
15490                if (subStr != null) {
15491                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15492                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15493                    }
15494                    try {
15495                        idx = Integer.parseInt(subStr);
15496                        if (idx <= 1) {
15497                            idx++;
15498                        } else {
15499                            idx--;
15500                        }
15501                    } catch(NumberFormatException e) {
15502                    }
15503                }
15504            }
15505        }
15506        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15507        return prefix + idxStr;
15508    }
15509
15510    private File getNextCodePath(File targetDir, String packageName) {
15511        File result;
15512        SecureRandom random = new SecureRandom();
15513        byte[] bytes = new byte[16];
15514        do {
15515            random.nextBytes(bytes);
15516            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15517            result = new File(targetDir, packageName + "-" + suffix);
15518        } while (result.exists());
15519        return result;
15520    }
15521
15522    // Utility method that returns the relative package path with respect
15523    // to the installation directory. Like say for /data/data/com.test-1.apk
15524    // string com.test-1 is returned.
15525    static String deriveCodePathName(String codePath) {
15526        if (codePath == null) {
15527            return null;
15528        }
15529        final File codeFile = new File(codePath);
15530        final String name = codeFile.getName();
15531        if (codeFile.isDirectory()) {
15532            return name;
15533        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15534            final int lastDot = name.lastIndexOf('.');
15535            return name.substring(0, lastDot);
15536        } else {
15537            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15538            return null;
15539        }
15540    }
15541
15542    static class PackageInstalledInfo {
15543        String name;
15544        int uid;
15545        // The set of users that originally had this package installed.
15546        int[] origUsers;
15547        // The set of users that now have this package installed.
15548        int[] newUsers;
15549        PackageParser.Package pkg;
15550        int returnCode;
15551        String returnMsg;
15552        String installerPackageName;
15553        PackageRemovedInfo removedInfo;
15554        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15555
15556        public void setError(int code, String msg) {
15557            setReturnCode(code);
15558            setReturnMessage(msg);
15559            Slog.w(TAG, msg);
15560        }
15561
15562        public void setError(String msg, PackageParserException e) {
15563            setReturnCode(e.error);
15564            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15565            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15566            for (int i = 0; i < childCount; i++) {
15567                addedChildPackages.valueAt(i).setError(msg, e);
15568            }
15569            Slog.w(TAG, msg, e);
15570        }
15571
15572        public void setError(String msg, PackageManagerException e) {
15573            returnCode = e.error;
15574            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15575            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15576            for (int i = 0; i < childCount; i++) {
15577                addedChildPackages.valueAt(i).setError(msg, e);
15578            }
15579            Slog.w(TAG, msg, e);
15580        }
15581
15582        public void setReturnCode(int returnCode) {
15583            this.returnCode = returnCode;
15584            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15585            for (int i = 0; i < childCount; i++) {
15586                addedChildPackages.valueAt(i).returnCode = returnCode;
15587            }
15588        }
15589
15590        private void setReturnMessage(String returnMsg) {
15591            this.returnMsg = returnMsg;
15592            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15593            for (int i = 0; i < childCount; i++) {
15594                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15595            }
15596        }
15597
15598        // In some error cases we want to convey more info back to the observer
15599        String origPackage;
15600        String origPermission;
15601    }
15602
15603    /*
15604     * Install a non-existing package.
15605     */
15606    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15607            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15608            String volumeUuid, PackageInstalledInfo res, int installReason) {
15609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15610
15611        // Remember this for later, in case we need to rollback this install
15612        String pkgName = pkg.packageName;
15613
15614        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15615
15616        synchronized(mPackages) {
15617            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15618            if (renamedPackage != null) {
15619                // A package with the same name is already installed, though
15620                // it has been renamed to an older name.  The package we
15621                // are trying to install should be installed as an update to
15622                // the existing one, but that has not been requested, so bail.
15623                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15624                        + " without first uninstalling package running as "
15625                        + renamedPackage);
15626                return;
15627            }
15628            if (mPackages.containsKey(pkgName)) {
15629                // Don't allow installation over an existing package with the same name.
15630                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15631                        + " without first uninstalling.");
15632                return;
15633            }
15634        }
15635
15636        try {
15637            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15638                    System.currentTimeMillis(), user);
15639
15640            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15641
15642            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15643                prepareAppDataAfterInstallLIF(newPackage);
15644
15645            } else {
15646                // Remove package from internal structures, but keep around any
15647                // data that might have already existed
15648                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15649                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15650            }
15651        } catch (PackageManagerException e) {
15652            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15653        }
15654
15655        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15656    }
15657
15658    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15659        try (DigestInputStream digestStream =
15660                new DigestInputStream(new FileInputStream(file), digest)) {
15661            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15662        }
15663    }
15664
15665    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15666            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15667            PackageInstalledInfo res, int installReason) {
15668        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15669
15670        final PackageParser.Package oldPackage;
15671        final PackageSetting ps;
15672        final String pkgName = pkg.packageName;
15673        final int[] allUsers;
15674        final int[] installedUsers;
15675
15676        synchronized(mPackages) {
15677            oldPackage = mPackages.get(pkgName);
15678            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15679
15680            // don't allow upgrade to target a release SDK from a pre-release SDK
15681            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15682                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15683            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15684                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15685            if (oldTargetsPreRelease
15686                    && !newTargetsPreRelease
15687                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15688                Slog.w(TAG, "Can't install package targeting released sdk");
15689                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15690                return;
15691            }
15692
15693            ps = mSettings.mPackages.get(pkgName);
15694
15695            // verify signatures are valid
15696            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15697            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15698                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15699                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15700                            "New package not signed by keys specified by upgrade-keysets: "
15701                                    + pkgName);
15702                    return;
15703                }
15704            } else {
15705                // default to original signature matching
15706                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15707                        != PackageManager.SIGNATURE_MATCH) {
15708                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15709                            "New package has a different signature: " + pkgName);
15710                    return;
15711                }
15712            }
15713
15714            // don't allow a system upgrade unless the upgrade hash matches
15715            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15716                byte[] digestBytes = null;
15717                try {
15718                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15719                    updateDigest(digest, new File(pkg.baseCodePath));
15720                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15721                        for (String path : pkg.splitCodePaths) {
15722                            updateDigest(digest, new File(path));
15723                        }
15724                    }
15725                    digestBytes = digest.digest();
15726                } catch (NoSuchAlgorithmException | IOException e) {
15727                    res.setError(INSTALL_FAILED_INVALID_APK,
15728                            "Could not compute hash: " + pkgName);
15729                    return;
15730                }
15731                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15732                    res.setError(INSTALL_FAILED_INVALID_APK,
15733                            "New package fails restrict-update check: " + pkgName);
15734                    return;
15735                }
15736                // retain upgrade restriction
15737                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15738            }
15739
15740            // Check for shared user id changes
15741            String invalidPackageName =
15742                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15743            if (invalidPackageName != null) {
15744                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15745                        "Package " + invalidPackageName + " tried to change user "
15746                                + oldPackage.mSharedUserId);
15747                return;
15748            }
15749
15750            // check if the new package supports all of the abis which the old package supports
15751            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
15752            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
15753            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
15754                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15755                        "Update to package " + pkgName + " doesn't support multi arch");
15756                return;
15757            }
15758
15759            // In case of rollback, remember per-user/profile install state
15760            allUsers = sUserManager.getUserIds();
15761            installedUsers = ps.queryInstalledUsers(allUsers, true);
15762
15763            // don't allow an upgrade from full to ephemeral
15764            if (isInstantApp) {
15765                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15766                    for (int currentUser : allUsers) {
15767                        if (!ps.getInstantApp(currentUser)) {
15768                            // can't downgrade from full to instant
15769                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15770                                    + " for user: " + currentUser);
15771                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15772                            return;
15773                        }
15774                    }
15775                } else if (!ps.getInstantApp(user.getIdentifier())) {
15776                    // can't downgrade from full to instant
15777                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15778                            + " for user: " + user.getIdentifier());
15779                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15780                    return;
15781                }
15782            }
15783        }
15784
15785        // Update what is removed
15786        res.removedInfo = new PackageRemovedInfo(this);
15787        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15788        res.removedInfo.removedPackage = oldPackage.packageName;
15789        res.removedInfo.installerPackageName = ps.installerPackageName;
15790        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15791        res.removedInfo.isUpdate = true;
15792        res.removedInfo.origUsers = installedUsers;
15793        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15794        for (int i = 0; i < installedUsers.length; i++) {
15795            final int userId = installedUsers[i];
15796            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15797        }
15798
15799        final int childCount = (oldPackage.childPackages != null)
15800                ? oldPackage.childPackages.size() : 0;
15801        for (int i = 0; i < childCount; i++) {
15802            boolean childPackageUpdated = false;
15803            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15804            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15805            if (res.addedChildPackages != null) {
15806                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15807                if (childRes != null) {
15808                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15809                    childRes.removedInfo.removedPackage = childPkg.packageName;
15810                    if (childPs != null) {
15811                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15812                    }
15813                    childRes.removedInfo.isUpdate = true;
15814                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15815                    childPackageUpdated = true;
15816                }
15817            }
15818            if (!childPackageUpdated) {
15819                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15820                childRemovedRes.removedPackage = childPkg.packageName;
15821                if (childPs != null) {
15822                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15823                }
15824                childRemovedRes.isUpdate = false;
15825                childRemovedRes.dataRemoved = true;
15826                synchronized (mPackages) {
15827                    if (childPs != null) {
15828                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15829                    }
15830                }
15831                if (res.removedInfo.removedChildPackages == null) {
15832                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15833                }
15834                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15835            }
15836        }
15837
15838        boolean sysPkg = (isSystemApp(oldPackage));
15839        if (sysPkg) {
15840            // Set the system/privileged/oem/vendor flags as needed
15841            final boolean privileged =
15842                    (oldPackage.applicationInfo.privateFlags
15843                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15844            final boolean oem =
15845                    (oldPackage.applicationInfo.privateFlags
15846                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15847            final boolean vendor =
15848                    (oldPackage.applicationInfo.privateFlags
15849                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
15850            final @ParseFlags int systemParseFlags = parseFlags;
15851            final @ScanFlags int systemScanFlags = scanFlags
15852                    | SCAN_AS_SYSTEM
15853                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15854                    | (oem ? SCAN_AS_OEM : 0)
15855                    | (vendor ? SCAN_AS_VENDOR : 0);
15856
15857            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15858                    user, allUsers, installerPackageName, res, installReason);
15859        } else {
15860            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15861                    user, allUsers, installerPackageName, res, installReason);
15862        }
15863    }
15864
15865    @Override
15866    public List<String> getPreviousCodePaths(String packageName) {
15867        final int callingUid = Binder.getCallingUid();
15868        final List<String> result = new ArrayList<>();
15869        if (getInstantAppPackageName(callingUid) != null) {
15870            return result;
15871        }
15872        final PackageSetting ps = mSettings.mPackages.get(packageName);
15873        if (ps != null
15874                && ps.oldCodePaths != null
15875                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15876            result.addAll(ps.oldCodePaths);
15877        }
15878        return result;
15879    }
15880
15881    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15882            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15883            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15884            String installerPackageName, PackageInstalledInfo res, int installReason) {
15885        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15886                + deletedPackage);
15887
15888        String pkgName = deletedPackage.packageName;
15889        boolean deletedPkg = true;
15890        boolean addedPkg = false;
15891        boolean updatedSettings = false;
15892        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15893        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15894                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15895
15896        final long origUpdateTime = (pkg.mExtras != null)
15897                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15898
15899        // First delete the existing package while retaining the data directory
15900        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15901                res.removedInfo, true, pkg)) {
15902            // If the existing package wasn't successfully deleted
15903            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15904            deletedPkg = false;
15905        } else {
15906            // Successfully deleted the old package; proceed with replace.
15907
15908            // If deleted package lived in a container, give users a chance to
15909            // relinquish resources before killing.
15910            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15911                if (DEBUG_INSTALL) {
15912                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15913                }
15914                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15915                final ArrayList<String> pkgList = new ArrayList<String>(1);
15916                pkgList.add(deletedPackage.applicationInfo.packageName);
15917                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15918            }
15919
15920            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15921                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15922            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15923
15924            try {
15925                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15926                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15927                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15928                        installReason);
15929
15930                // Update the in-memory copy of the previous code paths.
15931                PackageSetting ps = mSettings.mPackages.get(pkgName);
15932                if (!killApp) {
15933                    if (ps.oldCodePaths == null) {
15934                        ps.oldCodePaths = new ArraySet<>();
15935                    }
15936                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15937                    if (deletedPackage.splitCodePaths != null) {
15938                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15939                    }
15940                } else {
15941                    ps.oldCodePaths = null;
15942                }
15943                if (ps.childPackageNames != null) {
15944                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15945                        final String childPkgName = ps.childPackageNames.get(i);
15946                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15947                        childPs.oldCodePaths = ps.oldCodePaths;
15948                    }
15949                }
15950                // set instant app status, but, only if it's explicitly specified
15951                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15952                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15953                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15954                prepareAppDataAfterInstallLIF(newPackage);
15955                addedPkg = true;
15956                mDexManager.notifyPackageUpdated(newPackage.packageName,
15957                        newPackage.baseCodePath, newPackage.splitCodePaths);
15958            } catch (PackageManagerException e) {
15959                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15960            }
15961        }
15962
15963        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15964            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15965
15966            // Revert all internal state mutations and added folders for the failed install
15967            if (addedPkg) {
15968                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15969                        res.removedInfo, true, null);
15970            }
15971
15972            // Restore the old package
15973            if (deletedPkg) {
15974                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15975                File restoreFile = new File(deletedPackage.codePath);
15976                // Parse old package
15977                boolean oldExternal = isExternal(deletedPackage);
15978                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15979                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15980                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15981                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15982                try {
15983                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15984                            null);
15985                } catch (PackageManagerException e) {
15986                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15987                            + e.getMessage());
15988                    return;
15989                }
15990
15991                synchronized (mPackages) {
15992                    // Ensure the installer package name up to date
15993                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15994
15995                    // Update permissions for restored package
15996                    mPermissionManager.updatePermissions(
15997                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15998                            mPermissionCallback);
15999
16000                    mSettings.writeLPr();
16001                }
16002
16003                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16004            }
16005        } else {
16006            synchronized (mPackages) {
16007                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16008                if (ps != null) {
16009                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16010                    if (res.removedInfo.removedChildPackages != null) {
16011                        final int childCount = res.removedInfo.removedChildPackages.size();
16012                        // Iterate in reverse as we may modify the collection
16013                        for (int i = childCount - 1; i >= 0; i--) {
16014                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16015                            if (res.addedChildPackages.containsKey(childPackageName)) {
16016                                res.removedInfo.removedChildPackages.removeAt(i);
16017                            } else {
16018                                PackageRemovedInfo childInfo = res.removedInfo
16019                                        .removedChildPackages.valueAt(i);
16020                                childInfo.removedForAllUsers = mPackages.get(
16021                                        childInfo.removedPackage) == null;
16022                            }
16023                        }
16024                    }
16025                }
16026            }
16027        }
16028    }
16029
16030    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16031            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16032            final @ScanFlags int scanFlags, UserHandle user,
16033            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16034            int installReason) {
16035        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16036                + ", old=" + deletedPackage);
16037
16038        final boolean disabledSystem;
16039
16040        // Remove existing system package
16041        removePackageLI(deletedPackage, true);
16042
16043        synchronized (mPackages) {
16044            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16045        }
16046        if (!disabledSystem) {
16047            // We didn't need to disable the .apk as a current system package,
16048            // which means we are replacing another update that is already
16049            // installed.  We need to make sure to delete the older one's .apk.
16050            res.removedInfo.args = createInstallArgsForExisting(0,
16051                    deletedPackage.applicationInfo.getCodePath(),
16052                    deletedPackage.applicationInfo.getResourcePath(),
16053                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16054        } else {
16055            res.removedInfo.args = null;
16056        }
16057
16058        // Successfully disabled the old package. Now proceed with re-installation
16059        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16060                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16061        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16062
16063        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16064        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16065                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16066
16067        PackageParser.Package newPackage = null;
16068        try {
16069            // Add the package to the internal data structures
16070            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16071
16072            // Set the update and install times
16073            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16074            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16075                    System.currentTimeMillis());
16076
16077            // Update the package dynamic state if succeeded
16078            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16079                // Now that the install succeeded make sure we remove data
16080                // directories for any child package the update removed.
16081                final int deletedChildCount = (deletedPackage.childPackages != null)
16082                        ? deletedPackage.childPackages.size() : 0;
16083                final int newChildCount = (newPackage.childPackages != null)
16084                        ? newPackage.childPackages.size() : 0;
16085                for (int i = 0; i < deletedChildCount; i++) {
16086                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16087                    boolean childPackageDeleted = true;
16088                    for (int j = 0; j < newChildCount; j++) {
16089                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16090                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16091                            childPackageDeleted = false;
16092                            break;
16093                        }
16094                    }
16095                    if (childPackageDeleted) {
16096                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16097                                deletedChildPkg.packageName);
16098                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16099                            PackageRemovedInfo removedChildRes = res.removedInfo
16100                                    .removedChildPackages.get(deletedChildPkg.packageName);
16101                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16102                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16103                        }
16104                    }
16105                }
16106
16107                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16108                        installReason);
16109                prepareAppDataAfterInstallLIF(newPackage);
16110
16111                mDexManager.notifyPackageUpdated(newPackage.packageName,
16112                            newPackage.baseCodePath, newPackage.splitCodePaths);
16113            }
16114        } catch (PackageManagerException e) {
16115            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16116            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16117        }
16118
16119        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16120            // Re installation failed. Restore old information
16121            // Remove new pkg information
16122            if (newPackage != null) {
16123                removeInstalledPackageLI(newPackage, true);
16124            }
16125            // Add back the old system package
16126            try {
16127                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16128            } catch (PackageManagerException e) {
16129                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16130            }
16131
16132            synchronized (mPackages) {
16133                if (disabledSystem) {
16134                    enableSystemPackageLPw(deletedPackage);
16135                }
16136
16137                // Ensure the installer package name up to date
16138                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16139
16140                // Update permissions for restored package
16141                mPermissionManager.updatePermissions(
16142                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16143                        mPermissionCallback);
16144
16145                mSettings.writeLPr();
16146            }
16147
16148            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16149                    + " after failed upgrade");
16150        }
16151    }
16152
16153    /**
16154     * Checks whether the parent or any of the child packages have a change shared
16155     * user. For a package to be a valid update the shred users of the parent and
16156     * the children should match. We may later support changing child shared users.
16157     * @param oldPkg The updated package.
16158     * @param newPkg The update package.
16159     * @return The shared user that change between the versions.
16160     */
16161    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16162            PackageParser.Package newPkg) {
16163        // Check parent shared user
16164        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16165            return newPkg.packageName;
16166        }
16167        // Check child shared users
16168        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16169        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16170        for (int i = 0; i < newChildCount; i++) {
16171            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16172            // If this child was present, did it have the same shared user?
16173            for (int j = 0; j < oldChildCount; j++) {
16174                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16175                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16176                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16177                    return newChildPkg.packageName;
16178                }
16179            }
16180        }
16181        return null;
16182    }
16183
16184    private void removeNativeBinariesLI(PackageSetting ps) {
16185        // Remove the lib path for the parent package
16186        if (ps != null) {
16187            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16188            // Remove the lib path for the child packages
16189            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16190            for (int i = 0; i < childCount; i++) {
16191                PackageSetting childPs = null;
16192                synchronized (mPackages) {
16193                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16194                }
16195                if (childPs != null) {
16196                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16197                            .legacyNativeLibraryPathString);
16198                }
16199            }
16200        }
16201    }
16202
16203    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16204        // Enable the parent package
16205        mSettings.enableSystemPackageLPw(pkg.packageName);
16206        // Enable the child packages
16207        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16208        for (int i = 0; i < childCount; i++) {
16209            PackageParser.Package childPkg = pkg.childPackages.get(i);
16210            mSettings.enableSystemPackageLPw(childPkg.packageName);
16211        }
16212    }
16213
16214    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16215            PackageParser.Package newPkg) {
16216        // Disable the parent package (parent always replaced)
16217        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16218        // Disable the child packages
16219        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16220        for (int i = 0; i < childCount; i++) {
16221            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16222            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16223            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16224        }
16225        return disabled;
16226    }
16227
16228    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16229            String installerPackageName) {
16230        // Enable the parent package
16231        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16232        // Enable the child packages
16233        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16234        for (int i = 0; i < childCount; i++) {
16235            PackageParser.Package childPkg = pkg.childPackages.get(i);
16236            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16237        }
16238    }
16239
16240    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16241            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16242        // Update the parent package setting
16243        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16244                res, user, installReason);
16245        // Update the child packages setting
16246        final int childCount = (newPackage.childPackages != null)
16247                ? newPackage.childPackages.size() : 0;
16248        for (int i = 0; i < childCount; i++) {
16249            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16250            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16251            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16252                    childRes.origUsers, childRes, user, installReason);
16253        }
16254    }
16255
16256    private void updateSettingsInternalLI(PackageParser.Package pkg,
16257            String installerPackageName, int[] allUsers, int[] installedForUsers,
16258            PackageInstalledInfo res, UserHandle user, int installReason) {
16259        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16260
16261        String pkgName = pkg.packageName;
16262        synchronized (mPackages) {
16263            //write settings. the installStatus will be incomplete at this stage.
16264            //note that the new package setting would have already been
16265            //added to mPackages. It hasn't been persisted yet.
16266            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16267            // TODO: Remove this write? It's also written at the end of this method
16268            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16269            mSettings.writeLPr();
16270            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16271        }
16272
16273        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16274        synchronized (mPackages) {
16275// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16276            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16277                    mPermissionCallback);
16278            // For system-bundled packages, we assume that installing an upgraded version
16279            // of the package implies that the user actually wants to run that new code,
16280            // so we enable the package.
16281            PackageSetting ps = mSettings.mPackages.get(pkgName);
16282            final int userId = user.getIdentifier();
16283            if (ps != null) {
16284                if (isSystemApp(pkg)) {
16285                    if (DEBUG_INSTALL) {
16286                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16287                    }
16288                    // Enable system package for requested users
16289                    if (res.origUsers != null) {
16290                        for (int origUserId : res.origUsers) {
16291                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16292                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16293                                        origUserId, installerPackageName);
16294                            }
16295                        }
16296                    }
16297                    // Also convey the prior install/uninstall state
16298                    if (allUsers != null && installedForUsers != null) {
16299                        for (int currentUserId : allUsers) {
16300                            final boolean installed = ArrayUtils.contains(
16301                                    installedForUsers, currentUserId);
16302                            if (DEBUG_INSTALL) {
16303                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16304                            }
16305                            ps.setInstalled(installed, currentUserId);
16306                        }
16307                        // these install state changes will be persisted in the
16308                        // upcoming call to mSettings.writeLPr().
16309                    }
16310                }
16311                // It's implied that when a user requests installation, they want the app to be
16312                // installed and enabled.
16313                if (userId != UserHandle.USER_ALL) {
16314                    ps.setInstalled(true, userId);
16315                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16316                }
16317
16318                // When replacing an existing package, preserve the original install reason for all
16319                // users that had the package installed before.
16320                final Set<Integer> previousUserIds = new ArraySet<>();
16321                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16322                    final int installReasonCount = res.removedInfo.installReasons.size();
16323                    for (int i = 0; i < installReasonCount; i++) {
16324                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16325                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16326                        ps.setInstallReason(previousInstallReason, previousUserId);
16327                        previousUserIds.add(previousUserId);
16328                    }
16329                }
16330
16331                // Set install reason for users that are having the package newly installed.
16332                if (userId == UserHandle.USER_ALL) {
16333                    for (int currentUserId : sUserManager.getUserIds()) {
16334                        if (!previousUserIds.contains(currentUserId)) {
16335                            ps.setInstallReason(installReason, currentUserId);
16336                        }
16337                    }
16338                } else if (!previousUserIds.contains(userId)) {
16339                    ps.setInstallReason(installReason, userId);
16340                }
16341                mSettings.writeKernelMappingLPr(ps);
16342            }
16343            res.name = pkgName;
16344            res.uid = pkg.applicationInfo.uid;
16345            res.pkg = pkg;
16346            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16347            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16348            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16349            //to update install status
16350            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16351            mSettings.writeLPr();
16352            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16353        }
16354
16355        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16356    }
16357
16358    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16359        try {
16360            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16361            installPackageLI(args, res);
16362        } finally {
16363            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16364        }
16365    }
16366
16367    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16368        final int installFlags = args.installFlags;
16369        final String installerPackageName = args.installerPackageName;
16370        final String volumeUuid = args.volumeUuid;
16371        final File tmpPackageFile = new File(args.getCodePath());
16372        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16373        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16374                || (args.volumeUuid != null));
16375        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16376        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16377        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16378        final boolean virtualPreload =
16379                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16380        boolean replace = false;
16381        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16382        if (args.move != null) {
16383            // moving a complete application; perform an initial scan on the new install location
16384            scanFlags |= SCAN_INITIAL;
16385        }
16386        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16387            scanFlags |= SCAN_DONT_KILL_APP;
16388        }
16389        if (instantApp) {
16390            scanFlags |= SCAN_AS_INSTANT_APP;
16391        }
16392        if (fullApp) {
16393            scanFlags |= SCAN_AS_FULL_APP;
16394        }
16395        if (virtualPreload) {
16396            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16397        }
16398
16399        // Result object to be returned
16400        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16401        res.installerPackageName = installerPackageName;
16402
16403        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16404
16405        // Sanity check
16406        if (instantApp && (forwardLocked || onExternal)) {
16407            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16408                    + " external=" + onExternal);
16409            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16410            return;
16411        }
16412
16413        // Retrieve PackageSettings and parse package
16414        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16415                | PackageParser.PARSE_ENFORCE_CODE
16416                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16417                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16418                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16419                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16420        PackageParser pp = new PackageParser();
16421        pp.setSeparateProcesses(mSeparateProcesses);
16422        pp.setDisplayMetrics(mMetrics);
16423        pp.setCallback(mPackageParserCallback);
16424
16425        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16426        final PackageParser.Package pkg;
16427        try {
16428            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16429        } catch (PackageParserException e) {
16430            res.setError("Failed parse during installPackageLI", e);
16431            return;
16432        } finally {
16433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16434        }
16435
16436        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16437        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16438            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16439            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16440                    "Instant app package must target O");
16441            return;
16442        }
16443        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16444            Slog.w(TAG, "Instant app package " + pkg.packageName
16445                    + " does not target targetSandboxVersion 2");
16446            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16447                    "Instant app package must use targetSanboxVersion 2");
16448            return;
16449        }
16450
16451        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16452            // Static shared libraries have synthetic package names
16453            renameStaticSharedLibraryPackage(pkg);
16454
16455            // No static shared libs on external storage
16456            if (onExternal) {
16457                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16458                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16459                        "Packages declaring static-shared libs cannot be updated");
16460                return;
16461            }
16462        }
16463
16464        // If we are installing a clustered package add results for the children
16465        if (pkg.childPackages != null) {
16466            synchronized (mPackages) {
16467                final int childCount = pkg.childPackages.size();
16468                for (int i = 0; i < childCount; i++) {
16469                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16470                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16471                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16472                    childRes.pkg = childPkg;
16473                    childRes.name = childPkg.packageName;
16474                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16475                    if (childPs != null) {
16476                        childRes.origUsers = childPs.queryInstalledUsers(
16477                                sUserManager.getUserIds(), true);
16478                    }
16479                    if ((mPackages.containsKey(childPkg.packageName))) {
16480                        childRes.removedInfo = new PackageRemovedInfo(this);
16481                        childRes.removedInfo.removedPackage = childPkg.packageName;
16482                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16483                    }
16484                    if (res.addedChildPackages == null) {
16485                        res.addedChildPackages = new ArrayMap<>();
16486                    }
16487                    res.addedChildPackages.put(childPkg.packageName, childRes);
16488                }
16489            }
16490        }
16491
16492        // If package doesn't declare API override, mark that we have an install
16493        // time CPU ABI override.
16494        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16495            pkg.cpuAbiOverride = args.abiOverride;
16496        }
16497
16498        String pkgName = res.name = pkg.packageName;
16499        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16500            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16501                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16502                return;
16503            }
16504        }
16505
16506        try {
16507            // either use what we've been given or parse directly from the APK
16508            if (args.certificates != null) {
16509                try {
16510                    PackageParser.populateCertificates(pkg, args.certificates);
16511                } catch (PackageParserException e) {
16512                    // there was something wrong with the certificates we were given;
16513                    // try to pull them from the APK
16514                    PackageParser.collectCertificates(pkg, parseFlags);
16515                }
16516            } else {
16517                PackageParser.collectCertificates(pkg, parseFlags);
16518            }
16519        } catch (PackageParserException e) {
16520            res.setError("Failed collect during installPackageLI", e);
16521            return;
16522        }
16523
16524        // Get rid of all references to package scan path via parser.
16525        pp = null;
16526        String oldCodePath = null;
16527        boolean systemApp = false;
16528        synchronized (mPackages) {
16529            // Check if installing already existing package
16530            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16531                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16532                if (pkg.mOriginalPackages != null
16533                        && pkg.mOriginalPackages.contains(oldName)
16534                        && mPackages.containsKey(oldName)) {
16535                    // This package is derived from an original package,
16536                    // and this device has been updating from that original
16537                    // name.  We must continue using the original name, so
16538                    // rename the new package here.
16539                    pkg.setPackageName(oldName);
16540                    pkgName = pkg.packageName;
16541                    replace = true;
16542                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16543                            + oldName + " pkgName=" + pkgName);
16544                } else if (mPackages.containsKey(pkgName)) {
16545                    // This package, under its official name, already exists
16546                    // on the device; we should replace it.
16547                    replace = true;
16548                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16549                }
16550
16551                // Child packages are installed through the parent package
16552                if (pkg.parentPackage != null) {
16553                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16554                            "Package " + pkg.packageName + " is child of package "
16555                                    + pkg.parentPackage.parentPackage + ". Child packages "
16556                                    + "can be updated only through the parent package.");
16557                    return;
16558                }
16559
16560                if (replace) {
16561                    // Prevent apps opting out from runtime permissions
16562                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16563                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16564                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16565                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16566                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16567                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16568                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16569                                        + " doesn't support runtime permissions but the old"
16570                                        + " target SDK " + oldTargetSdk + " does.");
16571                        return;
16572                    }
16573                    // Prevent apps from downgrading their targetSandbox.
16574                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16575                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16576                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16577                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16578                                "Package " + pkg.packageName + " new target sandbox "
16579                                + newTargetSandbox + " is incompatible with the previous value of"
16580                                + oldTargetSandbox + ".");
16581                        return;
16582                    }
16583
16584                    // Prevent installing of child packages
16585                    if (oldPackage.parentPackage != null) {
16586                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16587                                "Package " + pkg.packageName + " is child of package "
16588                                        + oldPackage.parentPackage + ". Child packages "
16589                                        + "can be updated only through the parent package.");
16590                        return;
16591                    }
16592                }
16593            }
16594
16595            PackageSetting ps = mSettings.mPackages.get(pkgName);
16596            if (ps != null) {
16597                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16598
16599                // Static shared libs have same package with different versions where
16600                // we internally use a synthetic package name to allow multiple versions
16601                // of the same package, therefore we need to compare signatures against
16602                // the package setting for the latest library version.
16603                PackageSetting signatureCheckPs = ps;
16604                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16605                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16606                    if (libraryEntry != null) {
16607                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16608                    }
16609                }
16610
16611                // Quick sanity check that we're signed correctly if updating;
16612                // we'll check this again later when scanning, but we want to
16613                // bail early here before tripping over redefined permissions.
16614                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16615                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16616                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16617                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16618                                + pkg.packageName + " upgrade keys do not match the "
16619                                + "previously installed version");
16620                        return;
16621                    }
16622                } else {
16623                    try {
16624                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16625                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16626                        final boolean compatMatch = verifySignatures(
16627                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16628                        // The new KeySets will be re-added later in the scanning process.
16629                        if (compatMatch) {
16630                            synchronized (mPackages) {
16631                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16632                            }
16633                        }
16634                    } catch (PackageManagerException e) {
16635                        res.setError(e.error, e.getMessage());
16636                        return;
16637                    }
16638                }
16639
16640                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16641                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16642                    systemApp = (ps.pkg.applicationInfo.flags &
16643                            ApplicationInfo.FLAG_SYSTEM) != 0;
16644                }
16645                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16646            }
16647
16648            int N = pkg.permissions.size();
16649            for (int i = N-1; i >= 0; i--) {
16650                final PackageParser.Permission perm = pkg.permissions.get(i);
16651                final BasePermission bp =
16652                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16653
16654                // Don't allow anyone but the system to define ephemeral permissions.
16655                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16656                        && !systemApp) {
16657                    Slog.w(TAG, "Non-System package " + pkg.packageName
16658                            + " attempting to delcare ephemeral permission "
16659                            + perm.info.name + "; Removing ephemeral.");
16660                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16661                }
16662
16663                // Check whether the newly-scanned package wants to define an already-defined perm
16664                if (bp != null) {
16665                    // If the defining package is signed with our cert, it's okay.  This
16666                    // also includes the "updating the same package" case, of course.
16667                    // "updating same package" could also involve key-rotation.
16668                    final boolean sigsOk;
16669                    final String sourcePackageName = bp.getSourcePackageName();
16670                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16671                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16672                    if (sourcePackageName.equals(pkg.packageName)
16673                            && (ksms.shouldCheckUpgradeKeySetLocked(
16674                                    sourcePackageSetting, scanFlags))) {
16675                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16676                    } else {
16677                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16678                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16679                    }
16680                    if (!sigsOk) {
16681                        // If the owning package is the system itself, we log but allow
16682                        // install to proceed; we fail the install on all other permission
16683                        // redefinitions.
16684                        if (!sourcePackageName.equals("android")) {
16685                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16686                                    + pkg.packageName + " attempting to redeclare permission "
16687                                    + perm.info.name + " already owned by " + sourcePackageName);
16688                            res.origPermission = perm.info.name;
16689                            res.origPackage = sourcePackageName;
16690                            return;
16691                        } else {
16692                            Slog.w(TAG, "Package " + pkg.packageName
16693                                    + " attempting to redeclare system permission "
16694                                    + perm.info.name + "; ignoring new declaration");
16695                            pkg.permissions.remove(i);
16696                        }
16697                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16698                        // Prevent apps to change protection level to dangerous from any other
16699                        // type as this would allow a privilege escalation where an app adds a
16700                        // normal/signature permission in other app's group and later redefines
16701                        // it as dangerous leading to the group auto-grant.
16702                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16703                                == PermissionInfo.PROTECTION_DANGEROUS) {
16704                            if (bp != null && !bp.isRuntime()) {
16705                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16706                                        + "non-runtime permission " + perm.info.name
16707                                        + " to runtime; keeping old protection level");
16708                                perm.info.protectionLevel = bp.getProtectionLevel();
16709                            }
16710                        }
16711                    }
16712                }
16713            }
16714        }
16715
16716        if (systemApp) {
16717            if (onExternal) {
16718                // Abort update; system app can't be replaced with app on sdcard
16719                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16720                        "Cannot install updates to system apps on sdcard");
16721                return;
16722            } else if (instantApp) {
16723                // Abort update; system app can't be replaced with an instant app
16724                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16725                        "Cannot update a system app with an instant app");
16726                return;
16727            }
16728        }
16729
16730        if (args.move != null) {
16731            // We did an in-place move, so dex is ready to roll
16732            scanFlags |= SCAN_NO_DEX;
16733            scanFlags |= SCAN_MOVE;
16734
16735            synchronized (mPackages) {
16736                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16737                if (ps == null) {
16738                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16739                            "Missing settings for moved package " + pkgName);
16740                }
16741
16742                // We moved the entire application as-is, so bring over the
16743                // previously derived ABI information.
16744                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16745                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16746            }
16747
16748        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16749            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16750            scanFlags |= SCAN_NO_DEX;
16751
16752            try {
16753                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16754                    args.abiOverride : pkg.cpuAbiOverride);
16755                final boolean extractNativeLibs = !pkg.isLibrary();
16756                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
16757            } catch (PackageManagerException pme) {
16758                Slog.e(TAG, "Error deriving application ABI", pme);
16759                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16760                return;
16761            }
16762
16763            // Shared libraries for the package need to be updated.
16764            synchronized (mPackages) {
16765                try {
16766                    updateSharedLibrariesLPr(pkg, null);
16767                } catch (PackageManagerException e) {
16768                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16769                }
16770            }
16771        }
16772
16773        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16774            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16775            return;
16776        }
16777
16778        if (!instantApp) {
16779            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16780        } else {
16781            if (DEBUG_DOMAIN_VERIFICATION) {
16782                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16783            }
16784        }
16785
16786        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16787                "installPackageLI")) {
16788            if (replace) {
16789                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16790                    // Static libs have a synthetic package name containing the version
16791                    // and cannot be updated as an update would get a new package name,
16792                    // unless this is the exact same version code which is useful for
16793                    // development.
16794                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16795                    if (existingPkg != null &&
16796                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
16797                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16798                                + "static-shared libs cannot be updated");
16799                        return;
16800                    }
16801                }
16802                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16803                        installerPackageName, res, args.installReason);
16804            } else {
16805                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16806                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16807            }
16808        }
16809
16810        // Check whether we need to dexopt the app.
16811        //
16812        // NOTE: it is IMPORTANT to call dexopt:
16813        //   - after doRename which will sync the package data from PackageParser.Package and its
16814        //     corresponding ApplicationInfo.
16815        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
16816        //     uid of the application (pkg.applicationInfo.uid).
16817        //     This update happens in place!
16818        //
16819        // We only need to dexopt if the package meets ALL of the following conditions:
16820        //   1) it is not forward locked.
16821        //   2) it is not on on an external ASEC container.
16822        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16823        //
16824        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16825        // complete, so we skip this step during installation. Instead, we'll take extra time
16826        // the first time the instant app starts. It's preferred to do it this way to provide
16827        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16828        // middle of running an instant app. The default behaviour can be overridden
16829        // via gservices.
16830        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
16831                && !forwardLocked
16832                && !pkg.applicationInfo.isExternalAsec()
16833                && (!instantApp || Global.getInt(mContext.getContentResolver(),
16834                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16835
16836        if (performDexopt) {
16837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16838            // Do not run PackageDexOptimizer through the local performDexOpt
16839            // method because `pkg` may not be in `mPackages` yet.
16840            //
16841            // Also, don't fail application installs if the dexopt step fails.
16842            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16843                    REASON_INSTALL,
16844                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
16845            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16846                    null /* instructionSets */,
16847                    getOrCreateCompilerPackageStats(pkg),
16848                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16849                    dexoptOptions);
16850            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16851        }
16852
16853        // Notify BackgroundDexOptService that the package has been changed.
16854        // If this is an update of a package which used to fail to compile,
16855        // BackgroundDexOptService will remove it from its blacklist.
16856        // TODO: Layering violation
16857        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16858
16859        synchronized (mPackages) {
16860            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16861            if (ps != null) {
16862                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16863                ps.setUpdateAvailable(false /*updateAvailable*/);
16864            }
16865
16866            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16867            for (int i = 0; i < childCount; i++) {
16868                PackageParser.Package childPkg = pkg.childPackages.get(i);
16869                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16870                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16871                if (childPs != null) {
16872                    childRes.newUsers = childPs.queryInstalledUsers(
16873                            sUserManager.getUserIds(), true);
16874                }
16875            }
16876
16877            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16878                updateSequenceNumberLP(ps, res.newUsers);
16879                updateInstantAppInstallerLocked(pkgName);
16880            }
16881        }
16882    }
16883
16884    private void startIntentFilterVerifications(int userId, boolean replacing,
16885            PackageParser.Package pkg) {
16886        if (mIntentFilterVerifierComponent == null) {
16887            Slog.w(TAG, "No IntentFilter verification will not be done as "
16888                    + "there is no IntentFilterVerifier available!");
16889            return;
16890        }
16891
16892        final int verifierUid = getPackageUid(
16893                mIntentFilterVerifierComponent.getPackageName(),
16894                MATCH_DEBUG_TRIAGED_MISSING,
16895                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16896
16897        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16898        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16899        mHandler.sendMessage(msg);
16900
16901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16902        for (int i = 0; i < childCount; i++) {
16903            PackageParser.Package childPkg = pkg.childPackages.get(i);
16904            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16905            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16906            mHandler.sendMessage(msg);
16907        }
16908    }
16909
16910    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16911            PackageParser.Package pkg) {
16912        int size = pkg.activities.size();
16913        if (size == 0) {
16914            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16915                    "No activity, so no need to verify any IntentFilter!");
16916            return;
16917        }
16918
16919        final boolean hasDomainURLs = hasDomainURLs(pkg);
16920        if (!hasDomainURLs) {
16921            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16922                    "No domain URLs, so no need to verify any IntentFilter!");
16923            return;
16924        }
16925
16926        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16927                + " if any IntentFilter from the " + size
16928                + " Activities needs verification ...");
16929
16930        int count = 0;
16931        final String packageName = pkg.packageName;
16932
16933        synchronized (mPackages) {
16934            // If this is a new install and we see that we've already run verification for this
16935            // package, we have nothing to do: it means the state was restored from backup.
16936            if (!replacing) {
16937                IntentFilterVerificationInfo ivi =
16938                        mSettings.getIntentFilterVerificationLPr(packageName);
16939                if (ivi != null) {
16940                    if (DEBUG_DOMAIN_VERIFICATION) {
16941                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16942                                + ivi.getStatusString());
16943                    }
16944                    return;
16945                }
16946            }
16947
16948            // If any filters need to be verified, then all need to be.
16949            boolean needToVerify = false;
16950            for (PackageParser.Activity a : pkg.activities) {
16951                for (ActivityIntentInfo filter : a.intents) {
16952                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16953                        if (DEBUG_DOMAIN_VERIFICATION) {
16954                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16955                        }
16956                        needToVerify = true;
16957                        break;
16958                    }
16959                }
16960            }
16961
16962            if (needToVerify) {
16963                final int verificationId = mIntentFilterVerificationToken++;
16964                for (PackageParser.Activity a : pkg.activities) {
16965                    for (ActivityIntentInfo filter : a.intents) {
16966                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16967                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16968                                    "Verification needed for IntentFilter:" + filter.toString());
16969                            mIntentFilterVerifier.addOneIntentFilterVerification(
16970                                    verifierUid, userId, verificationId, filter, packageName);
16971                            count++;
16972                        }
16973                    }
16974                }
16975            }
16976        }
16977
16978        if (count > 0) {
16979            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16980                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16981                    +  " for userId:" + userId);
16982            mIntentFilterVerifier.startVerifications(userId);
16983        } else {
16984            if (DEBUG_DOMAIN_VERIFICATION) {
16985                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16986            }
16987        }
16988    }
16989
16990    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16991        final ComponentName cn  = filter.activity.getComponentName();
16992        final String packageName = cn.getPackageName();
16993
16994        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16995                packageName);
16996        if (ivi == null) {
16997            return true;
16998        }
16999        int status = ivi.getStatus();
17000        switch (status) {
17001            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17002            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17003                return true;
17004
17005            default:
17006                // Nothing to do
17007                return false;
17008        }
17009    }
17010
17011    private static boolean isMultiArch(ApplicationInfo info) {
17012        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17013    }
17014
17015    private static boolean isExternal(PackageParser.Package pkg) {
17016        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17017    }
17018
17019    private static boolean isExternal(PackageSetting ps) {
17020        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17021    }
17022
17023    private static boolean isSystemApp(PackageParser.Package pkg) {
17024        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17025    }
17026
17027    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17028        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17029    }
17030
17031    private static boolean isOemApp(PackageParser.Package pkg) {
17032        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17033    }
17034
17035    private static boolean isVendorApp(PackageParser.Package pkg) {
17036        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17037    }
17038
17039    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17040        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17041    }
17042
17043    private static boolean isSystemApp(PackageSetting ps) {
17044        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17045    }
17046
17047    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17048        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17049    }
17050
17051    private int packageFlagsToInstallFlags(PackageSetting ps) {
17052        int installFlags = 0;
17053        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17054            // This existing package was an external ASEC install when we have
17055            // the external flag without a UUID
17056            installFlags |= PackageManager.INSTALL_EXTERNAL;
17057        }
17058        if (ps.isForwardLocked()) {
17059            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17060        }
17061        return installFlags;
17062    }
17063
17064    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17065        if (isExternal(pkg)) {
17066            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17067                return mSettings.getExternalVersion();
17068            } else {
17069                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17070            }
17071        } else {
17072            return mSettings.getInternalVersion();
17073        }
17074    }
17075
17076    private void deleteTempPackageFiles() {
17077        final FilenameFilter filter = new FilenameFilter() {
17078            public boolean accept(File dir, String name) {
17079                return name.startsWith("vmdl") && name.endsWith(".tmp");
17080            }
17081        };
17082        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17083            file.delete();
17084        }
17085    }
17086
17087    @Override
17088    public void deletePackageAsUser(String packageName, int versionCode,
17089            IPackageDeleteObserver observer, int userId, int flags) {
17090        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17091                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17092    }
17093
17094    @Override
17095    public void deletePackageVersioned(VersionedPackage versionedPackage,
17096            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17097        final int callingUid = Binder.getCallingUid();
17098        mContext.enforceCallingOrSelfPermission(
17099                android.Manifest.permission.DELETE_PACKAGES, null);
17100        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17101        Preconditions.checkNotNull(versionedPackage);
17102        Preconditions.checkNotNull(observer);
17103        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17104                PackageManager.VERSION_CODE_HIGHEST,
17105                Long.MAX_VALUE, "versionCode must be >= -1");
17106
17107        final String packageName = versionedPackage.getPackageName();
17108        final long versionCode = versionedPackage.getLongVersionCode();
17109        final String internalPackageName;
17110        synchronized (mPackages) {
17111            // Normalize package name to handle renamed packages and static libs
17112            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17113        }
17114
17115        final int uid = Binder.getCallingUid();
17116        if (!isOrphaned(internalPackageName)
17117                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17118            try {
17119                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17120                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17121                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17122                observer.onUserActionRequired(intent);
17123            } catch (RemoteException re) {
17124            }
17125            return;
17126        }
17127        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17128        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17129        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17130            mContext.enforceCallingOrSelfPermission(
17131                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17132                    "deletePackage for user " + userId);
17133        }
17134
17135        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17136            try {
17137                observer.onPackageDeleted(packageName,
17138                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17139            } catch (RemoteException re) {
17140            }
17141            return;
17142        }
17143
17144        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17145            try {
17146                observer.onPackageDeleted(packageName,
17147                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17148            } catch (RemoteException re) {
17149            }
17150            return;
17151        }
17152
17153        if (DEBUG_REMOVE) {
17154            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17155                    + " deleteAllUsers: " + deleteAllUsers + " version="
17156                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17157                    ? "VERSION_CODE_HIGHEST" : versionCode));
17158        }
17159        // Queue up an async operation since the package deletion may take a little while.
17160        mHandler.post(new Runnable() {
17161            public void run() {
17162                mHandler.removeCallbacks(this);
17163                int returnCode;
17164                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17165                boolean doDeletePackage = true;
17166                if (ps != null) {
17167                    final boolean targetIsInstantApp =
17168                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17169                    doDeletePackage = !targetIsInstantApp
17170                            || canViewInstantApps;
17171                }
17172                if (doDeletePackage) {
17173                    if (!deleteAllUsers) {
17174                        returnCode = deletePackageX(internalPackageName, versionCode,
17175                                userId, deleteFlags);
17176                    } else {
17177                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17178                                internalPackageName, users);
17179                        // If nobody is blocking uninstall, proceed with delete for all users
17180                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17181                            returnCode = deletePackageX(internalPackageName, versionCode,
17182                                    userId, deleteFlags);
17183                        } else {
17184                            // Otherwise uninstall individually for users with blockUninstalls=false
17185                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17186                            for (int userId : users) {
17187                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17188                                    returnCode = deletePackageX(internalPackageName, versionCode,
17189                                            userId, userFlags);
17190                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17191                                        Slog.w(TAG, "Package delete failed for user " + userId
17192                                                + ", returnCode " + returnCode);
17193                                    }
17194                                }
17195                            }
17196                            // The app has only been marked uninstalled for certain users.
17197                            // We still need to report that delete was blocked
17198                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17199                        }
17200                    }
17201                } else {
17202                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17203                }
17204                try {
17205                    observer.onPackageDeleted(packageName, returnCode, null);
17206                } catch (RemoteException e) {
17207                    Log.i(TAG, "Observer no longer exists.");
17208                } //end catch
17209            } //end run
17210        });
17211    }
17212
17213    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17214        if (pkg.staticSharedLibName != null) {
17215            return pkg.manifestPackageName;
17216        }
17217        return pkg.packageName;
17218    }
17219
17220    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17221        // Handle renamed packages
17222        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17223        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17224
17225        // Is this a static library?
17226        LongSparseArray<SharedLibraryEntry> versionedLib =
17227                mStaticLibsByDeclaringPackage.get(packageName);
17228        if (versionedLib == null || versionedLib.size() <= 0) {
17229            return packageName;
17230        }
17231
17232        // Figure out which lib versions the caller can see
17233        LongSparseLongArray versionsCallerCanSee = null;
17234        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17235        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17236                && callingAppId != Process.ROOT_UID) {
17237            versionsCallerCanSee = new LongSparseLongArray();
17238            String libName = versionedLib.valueAt(0).info.getName();
17239            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17240            if (uidPackages != null) {
17241                for (String uidPackage : uidPackages) {
17242                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17243                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17244                    if (libIdx >= 0) {
17245                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17246                        versionsCallerCanSee.append(libVersion, libVersion);
17247                    }
17248                }
17249            }
17250        }
17251
17252        // Caller can see nothing - done
17253        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17254            return packageName;
17255        }
17256
17257        // Find the version the caller can see and the app version code
17258        SharedLibraryEntry highestVersion = null;
17259        final int versionCount = versionedLib.size();
17260        for (int i = 0; i < versionCount; i++) {
17261            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17262            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17263                    libEntry.info.getLongVersion()) < 0) {
17264                continue;
17265            }
17266            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17267            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17268                if (libVersionCode == versionCode) {
17269                    return libEntry.apk;
17270                }
17271            } else if (highestVersion == null) {
17272                highestVersion = libEntry;
17273            } else if (libVersionCode  > highestVersion.info
17274                    .getDeclaringPackage().getLongVersionCode()) {
17275                highestVersion = libEntry;
17276            }
17277        }
17278
17279        if (highestVersion != null) {
17280            return highestVersion.apk;
17281        }
17282
17283        return packageName;
17284    }
17285
17286    boolean isCallerVerifier(int callingUid) {
17287        final int callingUserId = UserHandle.getUserId(callingUid);
17288        return mRequiredVerifierPackage != null &&
17289                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17290    }
17291
17292    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17293        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17294              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17295            return true;
17296        }
17297        final int callingUserId = UserHandle.getUserId(callingUid);
17298        // If the caller installed the pkgName, then allow it to silently uninstall.
17299        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17300            return true;
17301        }
17302
17303        // Allow package verifier to silently uninstall.
17304        if (mRequiredVerifierPackage != null &&
17305                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17306            return true;
17307        }
17308
17309        // Allow package uninstaller to silently uninstall.
17310        if (mRequiredUninstallerPackage != null &&
17311                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17312            return true;
17313        }
17314
17315        // Allow storage manager to silently uninstall.
17316        if (mStorageManagerPackage != null &&
17317                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17318            return true;
17319        }
17320
17321        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17322        // uninstall for device owner provisioning.
17323        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17324                == PERMISSION_GRANTED) {
17325            return true;
17326        }
17327
17328        return false;
17329    }
17330
17331    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17332        int[] result = EMPTY_INT_ARRAY;
17333        for (int userId : userIds) {
17334            if (getBlockUninstallForUser(packageName, userId)) {
17335                result = ArrayUtils.appendInt(result, userId);
17336            }
17337        }
17338        return result;
17339    }
17340
17341    @Override
17342    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17343        final int callingUid = Binder.getCallingUid();
17344        if (getInstantAppPackageName(callingUid) != null
17345                && !isCallerSameApp(packageName, callingUid)) {
17346            return false;
17347        }
17348        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17349    }
17350
17351    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17352        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17353                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17354        try {
17355            if (dpm != null) {
17356                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17357                        /* callingUserOnly =*/ false);
17358                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17359                        : deviceOwnerComponentName.getPackageName();
17360                // Does the package contains the device owner?
17361                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17362                // this check is probably not needed, since DO should be registered as a device
17363                // admin on some user too. (Original bug for this: b/17657954)
17364                if (packageName.equals(deviceOwnerPackageName)) {
17365                    return true;
17366                }
17367                // Does it contain a device admin for any user?
17368                int[] users;
17369                if (userId == UserHandle.USER_ALL) {
17370                    users = sUserManager.getUserIds();
17371                } else {
17372                    users = new int[]{userId};
17373                }
17374                for (int i = 0; i < users.length; ++i) {
17375                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17376                        return true;
17377                    }
17378                }
17379            }
17380        } catch (RemoteException e) {
17381        }
17382        return false;
17383    }
17384
17385    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17386        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17387    }
17388
17389    /**
17390     *  This method is an internal method that could be get invoked either
17391     *  to delete an installed package or to clean up a failed installation.
17392     *  After deleting an installed package, a broadcast is sent to notify any
17393     *  listeners that the package has been removed. For cleaning up a failed
17394     *  installation, the broadcast is not necessary since the package's
17395     *  installation wouldn't have sent the initial broadcast either
17396     *  The key steps in deleting a package are
17397     *  deleting the package information in internal structures like mPackages,
17398     *  deleting the packages base directories through installd
17399     *  updating mSettings to reflect current status
17400     *  persisting settings for later use
17401     *  sending a broadcast if necessary
17402     */
17403    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17404        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17405        final boolean res;
17406
17407        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17408                ? UserHandle.USER_ALL : userId;
17409
17410        if (isPackageDeviceAdmin(packageName, removeUser)) {
17411            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17412            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17413        }
17414
17415        PackageSetting uninstalledPs = null;
17416        PackageParser.Package pkg = null;
17417
17418        // for the uninstall-updates case and restricted profiles, remember the per-
17419        // user handle installed state
17420        int[] allUsers;
17421        synchronized (mPackages) {
17422            uninstalledPs = mSettings.mPackages.get(packageName);
17423            if (uninstalledPs == null) {
17424                Slog.w(TAG, "Not removing non-existent package " + packageName);
17425                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17426            }
17427
17428            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17429                    && uninstalledPs.versionCode != versionCode) {
17430                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17431                        + uninstalledPs.versionCode + " != " + versionCode);
17432                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17433            }
17434
17435            // Static shared libs can be declared by any package, so let us not
17436            // allow removing a package if it provides a lib others depend on.
17437            pkg = mPackages.get(packageName);
17438
17439            allUsers = sUserManager.getUserIds();
17440
17441            if (pkg != null && pkg.staticSharedLibName != null) {
17442                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17443                        pkg.staticSharedLibVersion);
17444                if (libEntry != null) {
17445                    for (int currUserId : allUsers) {
17446                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17447                            continue;
17448                        }
17449                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17450                                libEntry.info, 0, currUserId);
17451                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17452                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17453                                    + " hosting lib " + libEntry.info.getName() + " version "
17454                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17455                                    + " for user " + currUserId);
17456                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17457                        }
17458                    }
17459                }
17460            }
17461
17462            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17463        }
17464
17465        final int freezeUser;
17466        if (isUpdatedSystemApp(uninstalledPs)
17467                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17468            // We're downgrading a system app, which will apply to all users, so
17469            // freeze them all during the downgrade
17470            freezeUser = UserHandle.USER_ALL;
17471        } else {
17472            freezeUser = removeUser;
17473        }
17474
17475        synchronized (mInstallLock) {
17476            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17477            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17478                    deleteFlags, "deletePackageX")) {
17479                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17480                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17481            }
17482            synchronized (mPackages) {
17483                if (res) {
17484                    if (pkg != null) {
17485                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17486                    }
17487                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17488                    updateInstantAppInstallerLocked(packageName);
17489                }
17490            }
17491        }
17492
17493        if (res) {
17494            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17495            info.sendPackageRemovedBroadcasts(killApp);
17496            info.sendSystemPackageUpdatedBroadcasts();
17497            info.sendSystemPackageAppearedBroadcasts();
17498        }
17499        // Force a gc here.
17500        Runtime.getRuntime().gc();
17501        // Delete the resources here after sending the broadcast to let
17502        // other processes clean up before deleting resources.
17503        if (info.args != null) {
17504            synchronized (mInstallLock) {
17505                info.args.doPostDeleteLI(true);
17506            }
17507        }
17508
17509        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17510    }
17511
17512    static class PackageRemovedInfo {
17513        final PackageSender packageSender;
17514        String removedPackage;
17515        String installerPackageName;
17516        int uid = -1;
17517        int removedAppId = -1;
17518        int[] origUsers;
17519        int[] removedUsers = null;
17520        int[] broadcastUsers = null;
17521        int[] instantUserIds = null;
17522        SparseArray<Integer> installReasons;
17523        boolean isRemovedPackageSystemUpdate = false;
17524        boolean isUpdate;
17525        boolean dataRemoved;
17526        boolean removedForAllUsers;
17527        boolean isStaticSharedLib;
17528        // Clean up resources deleted packages.
17529        InstallArgs args = null;
17530        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17531        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17532
17533        PackageRemovedInfo(PackageSender packageSender) {
17534            this.packageSender = packageSender;
17535        }
17536
17537        void sendPackageRemovedBroadcasts(boolean killApp) {
17538            sendPackageRemovedBroadcastInternal(killApp);
17539            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17540            for (int i = 0; i < childCount; i++) {
17541                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17542                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17543            }
17544        }
17545
17546        void sendSystemPackageUpdatedBroadcasts() {
17547            if (isRemovedPackageSystemUpdate) {
17548                sendSystemPackageUpdatedBroadcastsInternal();
17549                final int childCount = (removedChildPackages != null)
17550                        ? removedChildPackages.size() : 0;
17551                for (int i = 0; i < childCount; i++) {
17552                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17553                    if (childInfo.isRemovedPackageSystemUpdate) {
17554                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17555                    }
17556                }
17557            }
17558        }
17559
17560        void sendSystemPackageAppearedBroadcasts() {
17561            final int packageCount = (appearedChildPackages != null)
17562                    ? appearedChildPackages.size() : 0;
17563            for (int i = 0; i < packageCount; i++) {
17564                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17565                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17566                    true /*sendBootCompleted*/, false /*startReceiver*/,
17567                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17568            }
17569        }
17570
17571        private void sendSystemPackageUpdatedBroadcastsInternal() {
17572            Bundle extras = new Bundle(2);
17573            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17574            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17575            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17576                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17577            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17578                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17579            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17580                null, null, 0, removedPackage, null, null, null);
17581            if (installerPackageName != null) {
17582                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17583                        removedPackage, extras, 0 /*flags*/,
17584                        installerPackageName, null, null, null);
17585                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17586                        removedPackage, extras, 0 /*flags*/,
17587                        installerPackageName, null, null, null);
17588            }
17589        }
17590
17591        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17592            // Don't send static shared library removal broadcasts as these
17593            // libs are visible only the the apps that depend on them an one
17594            // cannot remove the library if it has a dependency.
17595            if (isStaticSharedLib) {
17596                return;
17597            }
17598            Bundle extras = new Bundle(2);
17599            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17600            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17601            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17602            if (isUpdate || isRemovedPackageSystemUpdate) {
17603                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17604            }
17605            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17606            if (removedPackage != null) {
17607                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17608                    removedPackage, extras, 0, null /*targetPackage*/, null,
17609                    broadcastUsers, instantUserIds);
17610                if (installerPackageName != null) {
17611                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17612                            removedPackage, extras, 0 /*flags*/,
17613                            installerPackageName, null, broadcastUsers, instantUserIds);
17614                }
17615                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17616                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17617                        removedPackage, extras,
17618                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17619                        null, null, broadcastUsers, instantUserIds);
17620                }
17621            }
17622            if (removedAppId >= 0) {
17623                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17624                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17625                    null, null, broadcastUsers, instantUserIds);
17626            }
17627        }
17628
17629        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17630            removedUsers = userIds;
17631            if (removedUsers == null) {
17632                broadcastUsers = null;
17633                return;
17634            }
17635
17636            broadcastUsers = EMPTY_INT_ARRAY;
17637            instantUserIds = EMPTY_INT_ARRAY;
17638            for (int i = userIds.length - 1; i >= 0; --i) {
17639                final int userId = userIds[i];
17640                if (deletedPackageSetting.getInstantApp(userId)) {
17641                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
17642                } else {
17643                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17644                }
17645            }
17646        }
17647    }
17648
17649    /*
17650     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17651     * flag is not set, the data directory is removed as well.
17652     * make sure this flag is set for partially installed apps. If not its meaningless to
17653     * delete a partially installed application.
17654     */
17655    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17656            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17657        String packageName = ps.name;
17658        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17659        // Retrieve object to delete permissions for shared user later on
17660        final PackageParser.Package deletedPkg;
17661        final PackageSetting deletedPs;
17662        // reader
17663        synchronized (mPackages) {
17664            deletedPkg = mPackages.get(packageName);
17665            deletedPs = mSettings.mPackages.get(packageName);
17666            if (outInfo != null) {
17667                outInfo.removedPackage = packageName;
17668                outInfo.installerPackageName = ps.installerPackageName;
17669                outInfo.isStaticSharedLib = deletedPkg != null
17670                        && deletedPkg.staticSharedLibName != null;
17671                outInfo.populateUsers(deletedPs == null ? null
17672                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17673            }
17674        }
17675
17676        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17677
17678        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17679            final PackageParser.Package resolvedPkg;
17680            if (deletedPkg != null) {
17681                resolvedPkg = deletedPkg;
17682            } else {
17683                // We don't have a parsed package when it lives on an ejected
17684                // adopted storage device, so fake something together
17685                resolvedPkg = new PackageParser.Package(ps.name);
17686                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17687            }
17688            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17689                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17690            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17691            if (outInfo != null) {
17692                outInfo.dataRemoved = true;
17693            }
17694            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17695        }
17696
17697        int removedAppId = -1;
17698
17699        // writer
17700        synchronized (mPackages) {
17701            boolean installedStateChanged = false;
17702            if (deletedPs != null) {
17703                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17704                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17705                    clearDefaultBrowserIfNeeded(packageName);
17706                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17707                    removedAppId = mSettings.removePackageLPw(packageName);
17708                    if (outInfo != null) {
17709                        outInfo.removedAppId = removedAppId;
17710                    }
17711                    mPermissionManager.updatePermissions(
17712                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17713                    if (deletedPs.sharedUser != null) {
17714                        // Remove permissions associated with package. Since runtime
17715                        // permissions are per user we have to kill the removed package
17716                        // or packages running under the shared user of the removed
17717                        // package if revoking the permissions requested only by the removed
17718                        // package is successful and this causes a change in gids.
17719                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17720                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17721                                    userId);
17722                            if (userIdToKill == UserHandle.USER_ALL
17723                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17724                                // If gids changed for this user, kill all affected packages.
17725                                mHandler.post(new Runnable() {
17726                                    @Override
17727                                    public void run() {
17728                                        // This has to happen with no lock held.
17729                                        killApplication(deletedPs.name, deletedPs.appId,
17730                                                KILL_APP_REASON_GIDS_CHANGED);
17731                                    }
17732                                });
17733                                break;
17734                            }
17735                        }
17736                    }
17737                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17738                }
17739                // make sure to preserve per-user disabled state if this removal was just
17740                // a downgrade of a system app to the factory package
17741                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17742                    if (DEBUG_REMOVE) {
17743                        Slog.d(TAG, "Propagating install state across downgrade");
17744                    }
17745                    for (int userId : allUserHandles) {
17746                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17747                        if (DEBUG_REMOVE) {
17748                            Slog.d(TAG, "    user " + userId + " => " + installed);
17749                        }
17750                        if (installed != ps.getInstalled(userId)) {
17751                            installedStateChanged = true;
17752                        }
17753                        ps.setInstalled(installed, userId);
17754                    }
17755                }
17756            }
17757            // can downgrade to reader
17758            if (writeSettings) {
17759                // Save settings now
17760                mSettings.writeLPr();
17761            }
17762            if (installedStateChanged) {
17763                mSettings.writeKernelMappingLPr(ps);
17764            }
17765        }
17766        if (removedAppId != -1) {
17767            // A user ID was deleted here. Go through all users and remove it
17768            // from KeyStore.
17769            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17770        }
17771    }
17772
17773    static boolean locationIsPrivileged(String path) {
17774        try {
17775            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17776            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
17777            return path.startsWith(privilegedAppDir.getCanonicalPath())
17778                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath());
17779        } catch (IOException e) {
17780            Slog.e(TAG, "Unable to access code path " + path);
17781        }
17782        return false;
17783    }
17784
17785    static boolean locationIsOem(String path) {
17786        try {
17787            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
17788        } catch (IOException e) {
17789            Slog.e(TAG, "Unable to access code path " + path);
17790        }
17791        return false;
17792    }
17793
17794    static boolean locationIsVendor(String path) {
17795        try {
17796            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
17797        } catch (IOException e) {
17798            Slog.e(TAG, "Unable to access code path " + path);
17799        }
17800        return false;
17801    }
17802
17803    /*
17804     * Tries to delete system package.
17805     */
17806    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17807            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17808            boolean writeSettings) {
17809        if (deletedPs.parentPackageName != null) {
17810            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17811            return false;
17812        }
17813
17814        final boolean applyUserRestrictions
17815                = (allUserHandles != null) && (outInfo.origUsers != null);
17816        final PackageSetting disabledPs;
17817        // Confirm if the system package has been updated
17818        // An updated system app can be deleted. This will also have to restore
17819        // the system pkg from system partition
17820        // reader
17821        synchronized (mPackages) {
17822            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17823        }
17824
17825        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17826                + " disabledPs=" + disabledPs);
17827
17828        if (disabledPs == null) {
17829            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17830            return false;
17831        } else if (DEBUG_REMOVE) {
17832            Slog.d(TAG, "Deleting system pkg from data partition");
17833        }
17834
17835        if (DEBUG_REMOVE) {
17836            if (applyUserRestrictions) {
17837                Slog.d(TAG, "Remembering install states:");
17838                for (int userId : allUserHandles) {
17839                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17840                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17841                }
17842            }
17843        }
17844
17845        // Delete the updated package
17846        outInfo.isRemovedPackageSystemUpdate = true;
17847        if (outInfo.removedChildPackages != null) {
17848            final int childCount = (deletedPs.childPackageNames != null)
17849                    ? deletedPs.childPackageNames.size() : 0;
17850            for (int i = 0; i < childCount; i++) {
17851                String childPackageName = deletedPs.childPackageNames.get(i);
17852                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17853                        .contains(childPackageName)) {
17854                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17855                            childPackageName);
17856                    if (childInfo != null) {
17857                        childInfo.isRemovedPackageSystemUpdate = true;
17858                    }
17859                }
17860            }
17861        }
17862
17863        if (disabledPs.versionCode < deletedPs.versionCode) {
17864            // Delete data for downgrades
17865            flags &= ~PackageManager.DELETE_KEEP_DATA;
17866        } else {
17867            // Preserve data by setting flag
17868            flags |= PackageManager.DELETE_KEEP_DATA;
17869        }
17870
17871        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17872                outInfo, writeSettings, disabledPs.pkg);
17873        if (!ret) {
17874            return false;
17875        }
17876
17877        // writer
17878        synchronized (mPackages) {
17879            // NOTE: The system package always needs to be enabled; even if it's for
17880            // a compressed stub. If we don't, installing the system package fails
17881            // during scan [scanning checks the disabled packages]. We will reverse
17882            // this later, after we've "installed" the stub.
17883            // Reinstate the old system package
17884            enableSystemPackageLPw(disabledPs.pkg);
17885            // Remove any native libraries from the upgraded package.
17886            removeNativeBinariesLI(deletedPs);
17887        }
17888
17889        // Install the system package
17890        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17891        try {
17892            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
17893                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17894        } catch (PackageManagerException e) {
17895            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17896                    + e.getMessage());
17897            return false;
17898        } finally {
17899            if (disabledPs.pkg.isStub) {
17900                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17901            }
17902        }
17903        return true;
17904    }
17905
17906    /**
17907     * Installs a package that's already on the system partition.
17908     */
17909    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
17910            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17911            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17912                    throws PackageManagerException {
17913        @ParseFlags int parseFlags =
17914                mDefParseFlags
17915                | PackageParser.PARSE_MUST_BE_APK
17916                | PackageParser.PARSE_IS_SYSTEM_DIR;
17917        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17918        if (isPrivileged || locationIsPrivileged(codePathString)) {
17919            scanFlags |= SCAN_AS_PRIVILEGED;
17920        }
17921        if (locationIsOem(codePathString)) {
17922            scanFlags |= SCAN_AS_OEM;
17923        }
17924        if (locationIsVendor(codePathString)) {
17925            scanFlags |= SCAN_AS_VENDOR;
17926        }
17927
17928        final File codePath = new File(codePathString);
17929        final PackageParser.Package pkg =
17930                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17931
17932        try {
17933            // update shared libraries for the newly re-installed system package
17934            updateSharedLibrariesLPr(pkg, null);
17935        } catch (PackageManagerException e) {
17936            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17937        }
17938
17939        prepareAppDataAfterInstallLIF(pkg);
17940
17941        // writer
17942        synchronized (mPackages) {
17943            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17944
17945            // Propagate the permissions state as we do not want to drop on the floor
17946            // runtime permissions. The update permissions method below will take
17947            // care of removing obsolete permissions and grant install permissions.
17948            if (origPermissionState != null) {
17949                ps.getPermissionsState().copyFrom(origPermissionState);
17950            }
17951            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17952                    mPermissionCallback);
17953
17954            final boolean applyUserRestrictions
17955                    = (allUserHandles != null) && (origUserHandles != null);
17956            if (applyUserRestrictions) {
17957                boolean installedStateChanged = false;
17958                if (DEBUG_REMOVE) {
17959                    Slog.d(TAG, "Propagating install state across reinstall");
17960                }
17961                for (int userId : allUserHandles) {
17962                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17963                    if (DEBUG_REMOVE) {
17964                        Slog.d(TAG, "    user " + userId + " => " + installed);
17965                    }
17966                    if (installed != ps.getInstalled(userId)) {
17967                        installedStateChanged = true;
17968                    }
17969                    ps.setInstalled(installed, userId);
17970
17971                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17972                }
17973                // Regardless of writeSettings we need to ensure that this restriction
17974                // state propagation is persisted
17975                mSettings.writeAllUsersPackageRestrictionsLPr();
17976                if (installedStateChanged) {
17977                    mSettings.writeKernelMappingLPr(ps);
17978                }
17979            }
17980            // can downgrade to reader here
17981            if (writeSettings) {
17982                mSettings.writeLPr();
17983            }
17984        }
17985        return pkg;
17986    }
17987
17988    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17989            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17990            PackageRemovedInfo outInfo, boolean writeSettings,
17991            PackageParser.Package replacingPackage) {
17992        synchronized (mPackages) {
17993            if (outInfo != null) {
17994                outInfo.uid = ps.appId;
17995            }
17996
17997            if (outInfo != null && outInfo.removedChildPackages != null) {
17998                final int childCount = (ps.childPackageNames != null)
17999                        ? ps.childPackageNames.size() : 0;
18000                for (int i = 0; i < childCount; i++) {
18001                    String childPackageName = ps.childPackageNames.get(i);
18002                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18003                    if (childPs == null) {
18004                        return false;
18005                    }
18006                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18007                            childPackageName);
18008                    if (childInfo != null) {
18009                        childInfo.uid = childPs.appId;
18010                    }
18011                }
18012            }
18013        }
18014
18015        // Delete package data from internal structures and also remove data if flag is set
18016        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18017
18018        // Delete the child packages data
18019        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18020        for (int i = 0; i < childCount; i++) {
18021            PackageSetting childPs;
18022            synchronized (mPackages) {
18023                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18024            }
18025            if (childPs != null) {
18026                PackageRemovedInfo childOutInfo = (outInfo != null
18027                        && outInfo.removedChildPackages != null)
18028                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18029                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18030                        && (replacingPackage != null
18031                        && !replacingPackage.hasChildPackage(childPs.name))
18032                        ? flags & ~DELETE_KEEP_DATA : flags;
18033                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18034                        deleteFlags, writeSettings);
18035            }
18036        }
18037
18038        // Delete application code and resources only for parent packages
18039        if (ps.parentPackageName == null) {
18040            if (deleteCodeAndResources && (outInfo != null)) {
18041                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18042                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18043                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18044            }
18045        }
18046
18047        return true;
18048    }
18049
18050    @Override
18051    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18052            int userId) {
18053        mContext.enforceCallingOrSelfPermission(
18054                android.Manifest.permission.DELETE_PACKAGES, null);
18055        synchronized (mPackages) {
18056            // Cannot block uninstall of static shared libs as they are
18057            // considered a part of the using app (emulating static linking).
18058            // Also static libs are installed always on internal storage.
18059            PackageParser.Package pkg = mPackages.get(packageName);
18060            if (pkg != null && pkg.staticSharedLibName != null) {
18061                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18062                        + " providing static shared library: " + pkg.staticSharedLibName);
18063                return false;
18064            }
18065            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18066            mSettings.writePackageRestrictionsLPr(userId);
18067        }
18068        return true;
18069    }
18070
18071    @Override
18072    public boolean getBlockUninstallForUser(String packageName, int userId) {
18073        synchronized (mPackages) {
18074            final PackageSetting ps = mSettings.mPackages.get(packageName);
18075            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18076                return false;
18077            }
18078            return mSettings.getBlockUninstallLPr(userId, packageName);
18079        }
18080    }
18081
18082    @Override
18083    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18084        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18085        synchronized (mPackages) {
18086            PackageSetting ps = mSettings.mPackages.get(packageName);
18087            if (ps == null) {
18088                Log.w(TAG, "Package doesn't exist: " + packageName);
18089                return false;
18090            }
18091            if (systemUserApp) {
18092                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18093            } else {
18094                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18095            }
18096            mSettings.writeLPr();
18097        }
18098        return true;
18099    }
18100
18101    /*
18102     * This method handles package deletion in general
18103     */
18104    private boolean deletePackageLIF(String packageName, UserHandle user,
18105            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18106            PackageRemovedInfo outInfo, boolean writeSettings,
18107            PackageParser.Package replacingPackage) {
18108        if (packageName == null) {
18109            Slog.w(TAG, "Attempt to delete null packageName.");
18110            return false;
18111        }
18112
18113        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18114
18115        PackageSetting ps;
18116        synchronized (mPackages) {
18117            ps = mSettings.mPackages.get(packageName);
18118            if (ps == null) {
18119                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18120                return false;
18121            }
18122
18123            if (ps.parentPackageName != null && (!isSystemApp(ps)
18124                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18125                if (DEBUG_REMOVE) {
18126                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18127                            + ((user == null) ? UserHandle.USER_ALL : user));
18128                }
18129                final int removedUserId = (user != null) ? user.getIdentifier()
18130                        : UserHandle.USER_ALL;
18131                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18132                    return false;
18133                }
18134                markPackageUninstalledForUserLPw(ps, user);
18135                scheduleWritePackageRestrictionsLocked(user);
18136                return true;
18137            }
18138        }
18139
18140        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18141                && user.getIdentifier() != UserHandle.USER_ALL)) {
18142            // The caller is asking that the package only be deleted for a single
18143            // user.  To do this, we just mark its uninstalled state and delete
18144            // its data. If this is a system app, we only allow this to happen if
18145            // they have set the special DELETE_SYSTEM_APP which requests different
18146            // semantics than normal for uninstalling system apps.
18147            markPackageUninstalledForUserLPw(ps, user);
18148
18149            if (!isSystemApp(ps)) {
18150                // Do not uninstall the APK if an app should be cached
18151                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18152                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18153                    // Other user still have this package installed, so all
18154                    // we need to do is clear this user's data and save that
18155                    // it is uninstalled.
18156                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18157                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18158                        return false;
18159                    }
18160                    scheduleWritePackageRestrictionsLocked(user);
18161                    return true;
18162                } else {
18163                    // We need to set it back to 'installed' so the uninstall
18164                    // broadcasts will be sent correctly.
18165                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18166                    ps.setInstalled(true, user.getIdentifier());
18167                    mSettings.writeKernelMappingLPr(ps);
18168                }
18169            } else {
18170                // This is a system app, so we assume that the
18171                // other users still have this package installed, so all
18172                // we need to do is clear this user's data and save that
18173                // it is uninstalled.
18174                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18175                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18176                    return false;
18177                }
18178                scheduleWritePackageRestrictionsLocked(user);
18179                return true;
18180            }
18181        }
18182
18183        // If we are deleting a composite package for all users, keep track
18184        // of result for each child.
18185        if (ps.childPackageNames != null && outInfo != null) {
18186            synchronized (mPackages) {
18187                final int childCount = ps.childPackageNames.size();
18188                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18189                for (int i = 0; i < childCount; i++) {
18190                    String childPackageName = ps.childPackageNames.get(i);
18191                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18192                    childInfo.removedPackage = childPackageName;
18193                    childInfo.installerPackageName = ps.installerPackageName;
18194                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18195                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18196                    if (childPs != null) {
18197                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18198                    }
18199                }
18200            }
18201        }
18202
18203        boolean ret = false;
18204        if (isSystemApp(ps)) {
18205            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18206            // When an updated system application is deleted we delete the existing resources
18207            // as well and fall back to existing code in system partition
18208            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18209        } else {
18210            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18211            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18212                    outInfo, writeSettings, replacingPackage);
18213        }
18214
18215        // Take a note whether we deleted the package for all users
18216        if (outInfo != null) {
18217            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18218            if (outInfo.removedChildPackages != null) {
18219                synchronized (mPackages) {
18220                    final int childCount = outInfo.removedChildPackages.size();
18221                    for (int i = 0; i < childCount; i++) {
18222                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18223                        if (childInfo != null) {
18224                            childInfo.removedForAllUsers = mPackages.get(
18225                                    childInfo.removedPackage) == null;
18226                        }
18227                    }
18228                }
18229            }
18230            // If we uninstalled an update to a system app there may be some
18231            // child packages that appeared as they are declared in the system
18232            // app but were not declared in the update.
18233            if (isSystemApp(ps)) {
18234                synchronized (mPackages) {
18235                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18236                    final int childCount = (updatedPs.childPackageNames != null)
18237                            ? updatedPs.childPackageNames.size() : 0;
18238                    for (int i = 0; i < childCount; i++) {
18239                        String childPackageName = updatedPs.childPackageNames.get(i);
18240                        if (outInfo.removedChildPackages == null
18241                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18242                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18243                            if (childPs == null) {
18244                                continue;
18245                            }
18246                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18247                            installRes.name = childPackageName;
18248                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18249                            installRes.pkg = mPackages.get(childPackageName);
18250                            installRes.uid = childPs.pkg.applicationInfo.uid;
18251                            if (outInfo.appearedChildPackages == null) {
18252                                outInfo.appearedChildPackages = new ArrayMap<>();
18253                            }
18254                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18255                        }
18256                    }
18257                }
18258            }
18259        }
18260
18261        return ret;
18262    }
18263
18264    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18265        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18266                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18267        for (int nextUserId : userIds) {
18268            if (DEBUG_REMOVE) {
18269                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18270            }
18271            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18272                    false /*installed*/,
18273                    true /*stopped*/,
18274                    true /*notLaunched*/,
18275                    false /*hidden*/,
18276                    false /*suspended*/,
18277                    false /*instantApp*/,
18278                    false /*virtualPreload*/,
18279                    null /*lastDisableAppCaller*/,
18280                    null /*enabledComponents*/,
18281                    null /*disabledComponents*/,
18282                    ps.readUserState(nextUserId).domainVerificationStatus,
18283                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18284        }
18285        mSettings.writeKernelMappingLPr(ps);
18286    }
18287
18288    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18289            PackageRemovedInfo outInfo) {
18290        final PackageParser.Package pkg;
18291        synchronized (mPackages) {
18292            pkg = mPackages.get(ps.name);
18293        }
18294
18295        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18296                : new int[] {userId};
18297        for (int nextUserId : userIds) {
18298            if (DEBUG_REMOVE) {
18299                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18300                        + nextUserId);
18301            }
18302
18303            destroyAppDataLIF(pkg, userId,
18304                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18305            destroyAppProfilesLIF(pkg, userId);
18306            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18307            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18308            schedulePackageCleaning(ps.name, nextUserId, false);
18309            synchronized (mPackages) {
18310                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18311                    scheduleWritePackageRestrictionsLocked(nextUserId);
18312                }
18313                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18314            }
18315        }
18316
18317        if (outInfo != null) {
18318            outInfo.removedPackage = ps.name;
18319            outInfo.installerPackageName = ps.installerPackageName;
18320            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18321            outInfo.removedAppId = ps.appId;
18322            outInfo.removedUsers = userIds;
18323            outInfo.broadcastUsers = userIds;
18324        }
18325
18326        return true;
18327    }
18328
18329    private final class ClearStorageConnection implements ServiceConnection {
18330        IMediaContainerService mContainerService;
18331
18332        @Override
18333        public void onServiceConnected(ComponentName name, IBinder service) {
18334            synchronized (this) {
18335                mContainerService = IMediaContainerService.Stub
18336                        .asInterface(Binder.allowBlocking(service));
18337                notifyAll();
18338            }
18339        }
18340
18341        @Override
18342        public void onServiceDisconnected(ComponentName name) {
18343        }
18344    }
18345
18346    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18347        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18348
18349        final boolean mounted;
18350        if (Environment.isExternalStorageEmulated()) {
18351            mounted = true;
18352        } else {
18353            final String status = Environment.getExternalStorageState();
18354
18355            mounted = status.equals(Environment.MEDIA_MOUNTED)
18356                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18357        }
18358
18359        if (!mounted) {
18360            return;
18361        }
18362
18363        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18364        int[] users;
18365        if (userId == UserHandle.USER_ALL) {
18366            users = sUserManager.getUserIds();
18367        } else {
18368            users = new int[] { userId };
18369        }
18370        final ClearStorageConnection conn = new ClearStorageConnection();
18371        if (mContext.bindServiceAsUser(
18372                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18373            try {
18374                for (int curUser : users) {
18375                    long timeout = SystemClock.uptimeMillis() + 5000;
18376                    synchronized (conn) {
18377                        long now;
18378                        while (conn.mContainerService == null &&
18379                                (now = SystemClock.uptimeMillis()) < timeout) {
18380                            try {
18381                                conn.wait(timeout - now);
18382                            } catch (InterruptedException e) {
18383                            }
18384                        }
18385                    }
18386                    if (conn.mContainerService == null) {
18387                        return;
18388                    }
18389
18390                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18391                    clearDirectory(conn.mContainerService,
18392                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18393                    if (allData) {
18394                        clearDirectory(conn.mContainerService,
18395                                userEnv.buildExternalStorageAppDataDirs(packageName));
18396                        clearDirectory(conn.mContainerService,
18397                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18398                    }
18399                }
18400            } finally {
18401                mContext.unbindService(conn);
18402            }
18403        }
18404    }
18405
18406    @Override
18407    public void clearApplicationProfileData(String packageName) {
18408        enforceSystemOrRoot("Only the system can clear all profile data");
18409
18410        final PackageParser.Package pkg;
18411        synchronized (mPackages) {
18412            pkg = mPackages.get(packageName);
18413        }
18414
18415        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18416            synchronized (mInstallLock) {
18417                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18418            }
18419        }
18420    }
18421
18422    @Override
18423    public void clearApplicationUserData(final String packageName,
18424            final IPackageDataObserver observer, final int userId) {
18425        mContext.enforceCallingOrSelfPermission(
18426                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18427
18428        final int callingUid = Binder.getCallingUid();
18429        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18430                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18431
18432        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18433        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18434        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18435            throw new SecurityException("Cannot clear data for a protected package: "
18436                    + packageName);
18437        }
18438        // Queue up an async operation since the package deletion may take a little while.
18439        mHandler.post(new Runnable() {
18440            public void run() {
18441                mHandler.removeCallbacks(this);
18442                final boolean succeeded;
18443                if (!filterApp) {
18444                    try (PackageFreezer freezer = freezePackage(packageName,
18445                            "clearApplicationUserData")) {
18446                        synchronized (mInstallLock) {
18447                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18448                        }
18449                        clearExternalStorageDataSync(packageName, userId, true);
18450                        synchronized (mPackages) {
18451                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18452                                    packageName, userId);
18453                        }
18454                    }
18455                    if (succeeded) {
18456                        // invoke DeviceStorageMonitor's update method to clear any notifications
18457                        DeviceStorageMonitorInternal dsm = LocalServices
18458                                .getService(DeviceStorageMonitorInternal.class);
18459                        if (dsm != null) {
18460                            dsm.checkMemory();
18461                        }
18462                    }
18463                } else {
18464                    succeeded = false;
18465                }
18466                if (observer != null) {
18467                    try {
18468                        observer.onRemoveCompleted(packageName, succeeded);
18469                    } catch (RemoteException e) {
18470                        Log.i(TAG, "Observer no longer exists.");
18471                    }
18472                } //end if observer
18473            } //end run
18474        });
18475    }
18476
18477    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18478        if (packageName == null) {
18479            Slog.w(TAG, "Attempt to delete null packageName.");
18480            return false;
18481        }
18482
18483        // Try finding details about the requested package
18484        PackageParser.Package pkg;
18485        synchronized (mPackages) {
18486            pkg = mPackages.get(packageName);
18487            if (pkg == null) {
18488                final PackageSetting ps = mSettings.mPackages.get(packageName);
18489                if (ps != null) {
18490                    pkg = ps.pkg;
18491                }
18492            }
18493
18494            if (pkg == null) {
18495                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18496                return false;
18497            }
18498
18499            PackageSetting ps = (PackageSetting) pkg.mExtras;
18500            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18501        }
18502
18503        clearAppDataLIF(pkg, userId,
18504                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18505
18506        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18507        removeKeystoreDataIfNeeded(userId, appId);
18508
18509        UserManagerInternal umInternal = getUserManagerInternal();
18510        final int flags;
18511        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18512            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18513        } else if (umInternal.isUserRunning(userId)) {
18514            flags = StorageManager.FLAG_STORAGE_DE;
18515        } else {
18516            flags = 0;
18517        }
18518        prepareAppDataContentsLIF(pkg, userId, flags);
18519
18520        return true;
18521    }
18522
18523    /**
18524     * Reverts user permission state changes (permissions and flags) in
18525     * all packages for a given user.
18526     *
18527     * @param userId The device user for which to do a reset.
18528     */
18529    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18530        final int packageCount = mPackages.size();
18531        for (int i = 0; i < packageCount; i++) {
18532            PackageParser.Package pkg = mPackages.valueAt(i);
18533            PackageSetting ps = (PackageSetting) pkg.mExtras;
18534            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18535        }
18536    }
18537
18538    private void resetNetworkPolicies(int userId) {
18539        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18540    }
18541
18542    /**
18543     * Reverts user permission state changes (permissions and flags).
18544     *
18545     * @param ps The package for which to reset.
18546     * @param userId The device user for which to do a reset.
18547     */
18548    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18549            final PackageSetting ps, final int userId) {
18550        if (ps.pkg == null) {
18551            return;
18552        }
18553
18554        // These are flags that can change base on user actions.
18555        final int userSettableMask = FLAG_PERMISSION_USER_SET
18556                | FLAG_PERMISSION_USER_FIXED
18557                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18558                | FLAG_PERMISSION_REVIEW_REQUIRED;
18559
18560        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18561                | FLAG_PERMISSION_POLICY_FIXED;
18562
18563        boolean writeInstallPermissions = false;
18564        boolean writeRuntimePermissions = false;
18565
18566        final int permissionCount = ps.pkg.requestedPermissions.size();
18567        for (int i = 0; i < permissionCount; i++) {
18568            final String permName = ps.pkg.requestedPermissions.get(i);
18569            final BasePermission bp =
18570                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18571            if (bp == null) {
18572                continue;
18573            }
18574
18575            // If shared user we just reset the state to which only this app contributed.
18576            if (ps.sharedUser != null) {
18577                boolean used = false;
18578                final int packageCount = ps.sharedUser.packages.size();
18579                for (int j = 0; j < packageCount; j++) {
18580                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18581                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18582                            && pkg.pkg.requestedPermissions.contains(permName)) {
18583                        used = true;
18584                        break;
18585                    }
18586                }
18587                if (used) {
18588                    continue;
18589                }
18590            }
18591
18592            final PermissionsState permissionsState = ps.getPermissionsState();
18593
18594            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18595
18596            // Always clear the user settable flags.
18597            final boolean hasInstallState =
18598                    permissionsState.getInstallPermissionState(permName) != null;
18599            // If permission review is enabled and this is a legacy app, mark the
18600            // permission as requiring a review as this is the initial state.
18601            int flags = 0;
18602            if (mSettings.mPermissions.mPermissionReviewRequired
18603                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18604                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18605            }
18606            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18607                if (hasInstallState) {
18608                    writeInstallPermissions = true;
18609                } else {
18610                    writeRuntimePermissions = true;
18611                }
18612            }
18613
18614            // Below is only runtime permission handling.
18615            if (!bp.isRuntime()) {
18616                continue;
18617            }
18618
18619            // Never clobber system or policy.
18620            if ((oldFlags & policyOrSystemFlags) != 0) {
18621                continue;
18622            }
18623
18624            // If this permission was granted by default, make sure it is.
18625            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18626                if (permissionsState.grantRuntimePermission(bp, userId)
18627                        != PERMISSION_OPERATION_FAILURE) {
18628                    writeRuntimePermissions = true;
18629                }
18630            // If permission review is enabled the permissions for a legacy apps
18631            // are represented as constantly granted runtime ones, so don't revoke.
18632            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18633                // Otherwise, reset the permission.
18634                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18635                switch (revokeResult) {
18636                    case PERMISSION_OPERATION_SUCCESS:
18637                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18638                        writeRuntimePermissions = true;
18639                        final int appId = ps.appId;
18640                        mHandler.post(new Runnable() {
18641                            @Override
18642                            public void run() {
18643                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18644                            }
18645                        });
18646                    } break;
18647                }
18648            }
18649        }
18650
18651        // Synchronously write as we are taking permissions away.
18652        if (writeRuntimePermissions) {
18653            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18654        }
18655
18656        // Synchronously write as we are taking permissions away.
18657        if (writeInstallPermissions) {
18658            mSettings.writeLPr();
18659        }
18660    }
18661
18662    /**
18663     * Remove entries from the keystore daemon. Will only remove it if the
18664     * {@code appId} is valid.
18665     */
18666    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18667        if (appId < 0) {
18668            return;
18669        }
18670
18671        final KeyStore keyStore = KeyStore.getInstance();
18672        if (keyStore != null) {
18673            if (userId == UserHandle.USER_ALL) {
18674                for (final int individual : sUserManager.getUserIds()) {
18675                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18676                }
18677            } else {
18678                keyStore.clearUid(UserHandle.getUid(userId, appId));
18679            }
18680        } else {
18681            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18682        }
18683    }
18684
18685    @Override
18686    public void deleteApplicationCacheFiles(final String packageName,
18687            final IPackageDataObserver observer) {
18688        final int userId = UserHandle.getCallingUserId();
18689        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18690    }
18691
18692    @Override
18693    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18694            final IPackageDataObserver observer) {
18695        final int callingUid = Binder.getCallingUid();
18696        mContext.enforceCallingOrSelfPermission(
18697                android.Manifest.permission.DELETE_CACHE_FILES, null);
18698        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18699                /* requireFullPermission= */ true, /* checkShell= */ false,
18700                "delete application cache files");
18701        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18702                android.Manifest.permission.ACCESS_INSTANT_APPS);
18703
18704        final PackageParser.Package pkg;
18705        synchronized (mPackages) {
18706            pkg = mPackages.get(packageName);
18707        }
18708
18709        // Queue up an async operation since the package deletion may take a little while.
18710        mHandler.post(new Runnable() {
18711            public void run() {
18712                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18713                boolean doClearData = true;
18714                if (ps != null) {
18715                    final boolean targetIsInstantApp =
18716                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18717                    doClearData = !targetIsInstantApp
18718                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18719                }
18720                if (doClearData) {
18721                    synchronized (mInstallLock) {
18722                        final int flags = StorageManager.FLAG_STORAGE_DE
18723                                | StorageManager.FLAG_STORAGE_CE;
18724                        // We're only clearing cache files, so we don't care if the
18725                        // app is unfrozen and still able to run
18726                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18727                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18728                    }
18729                    clearExternalStorageDataSync(packageName, userId, false);
18730                }
18731                if (observer != null) {
18732                    try {
18733                        observer.onRemoveCompleted(packageName, true);
18734                    } catch (RemoteException e) {
18735                        Log.i(TAG, "Observer no longer exists.");
18736                    }
18737                }
18738            }
18739        });
18740    }
18741
18742    @Override
18743    public void getPackageSizeInfo(final String packageName, int userHandle,
18744            final IPackageStatsObserver observer) {
18745        throw new UnsupportedOperationException(
18746                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18747    }
18748
18749    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18750        final PackageSetting ps;
18751        synchronized (mPackages) {
18752            ps = mSettings.mPackages.get(packageName);
18753            if (ps == null) {
18754                Slog.w(TAG, "Failed to find settings for " + packageName);
18755                return false;
18756            }
18757        }
18758
18759        final String[] packageNames = { packageName };
18760        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18761        final String[] codePaths = { ps.codePathString };
18762
18763        try {
18764            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18765                    ps.appId, ceDataInodes, codePaths, stats);
18766
18767            // For now, ignore code size of packages on system partition
18768            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18769                stats.codeSize = 0;
18770            }
18771
18772            // External clients expect these to be tracked separately
18773            stats.dataSize -= stats.cacheSize;
18774
18775        } catch (InstallerException e) {
18776            Slog.w(TAG, String.valueOf(e));
18777            return false;
18778        }
18779
18780        return true;
18781    }
18782
18783    private int getUidTargetSdkVersionLockedLPr(int uid) {
18784        Object obj = mSettings.getUserIdLPr(uid);
18785        if (obj instanceof SharedUserSetting) {
18786            final SharedUserSetting sus = (SharedUserSetting) obj;
18787            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18788            final Iterator<PackageSetting> it = sus.packages.iterator();
18789            while (it.hasNext()) {
18790                final PackageSetting ps = it.next();
18791                if (ps.pkg != null) {
18792                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18793                    if (v < vers) vers = v;
18794                }
18795            }
18796            return vers;
18797        } else if (obj instanceof PackageSetting) {
18798            final PackageSetting ps = (PackageSetting) obj;
18799            if (ps.pkg != null) {
18800                return ps.pkg.applicationInfo.targetSdkVersion;
18801            }
18802        }
18803        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18804    }
18805
18806    @Override
18807    public void addPreferredActivity(IntentFilter filter, int match,
18808            ComponentName[] set, ComponentName activity, int userId) {
18809        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18810                "Adding preferred");
18811    }
18812
18813    private void addPreferredActivityInternal(IntentFilter filter, int match,
18814            ComponentName[] set, ComponentName activity, boolean always, int userId,
18815            String opname) {
18816        // writer
18817        int callingUid = Binder.getCallingUid();
18818        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18819                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18820        if (filter.countActions() == 0) {
18821            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18822            return;
18823        }
18824        synchronized (mPackages) {
18825            if (mContext.checkCallingOrSelfPermission(
18826                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18827                    != PackageManager.PERMISSION_GRANTED) {
18828                if (getUidTargetSdkVersionLockedLPr(callingUid)
18829                        < Build.VERSION_CODES.FROYO) {
18830                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18831                            + callingUid);
18832                    return;
18833                }
18834                mContext.enforceCallingOrSelfPermission(
18835                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18836            }
18837
18838            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18839            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18840                    + userId + ":");
18841            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18842            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18843            scheduleWritePackageRestrictionsLocked(userId);
18844            postPreferredActivityChangedBroadcast(userId);
18845        }
18846    }
18847
18848    private void postPreferredActivityChangedBroadcast(int userId) {
18849        mHandler.post(() -> {
18850            final IActivityManager am = ActivityManager.getService();
18851            if (am == null) {
18852                return;
18853            }
18854
18855            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18856            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18857            try {
18858                am.broadcastIntent(null, intent, null, null,
18859                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18860                        null, false, false, userId);
18861            } catch (RemoteException e) {
18862            }
18863        });
18864    }
18865
18866    @Override
18867    public void replacePreferredActivity(IntentFilter filter, int match,
18868            ComponentName[] set, ComponentName activity, int userId) {
18869        if (filter.countActions() != 1) {
18870            throw new IllegalArgumentException(
18871                    "replacePreferredActivity expects filter to have only 1 action.");
18872        }
18873        if (filter.countDataAuthorities() != 0
18874                || filter.countDataPaths() != 0
18875                || filter.countDataSchemes() > 1
18876                || filter.countDataTypes() != 0) {
18877            throw new IllegalArgumentException(
18878                    "replacePreferredActivity expects filter to have no data authorities, " +
18879                    "paths, or types; and at most one scheme.");
18880        }
18881
18882        final int callingUid = Binder.getCallingUid();
18883        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18884                true /* requireFullPermission */, false /* checkShell */,
18885                "replace preferred activity");
18886        synchronized (mPackages) {
18887            if (mContext.checkCallingOrSelfPermission(
18888                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18889                    != PackageManager.PERMISSION_GRANTED) {
18890                if (getUidTargetSdkVersionLockedLPr(callingUid)
18891                        < Build.VERSION_CODES.FROYO) {
18892                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18893                            + Binder.getCallingUid());
18894                    return;
18895                }
18896                mContext.enforceCallingOrSelfPermission(
18897                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18898            }
18899
18900            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18901            if (pir != null) {
18902                // Get all of the existing entries that exactly match this filter.
18903                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18904                if (existing != null && existing.size() == 1) {
18905                    PreferredActivity cur = existing.get(0);
18906                    if (DEBUG_PREFERRED) {
18907                        Slog.i(TAG, "Checking replace of preferred:");
18908                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18909                        if (!cur.mPref.mAlways) {
18910                            Slog.i(TAG, "  -- CUR; not mAlways!");
18911                        } else {
18912                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18913                            Slog.i(TAG, "  -- CUR: mSet="
18914                                    + Arrays.toString(cur.mPref.mSetComponents));
18915                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18916                            Slog.i(TAG, "  -- NEW: mMatch="
18917                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18918                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18919                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18920                        }
18921                    }
18922                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18923                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18924                            && cur.mPref.sameSet(set)) {
18925                        // Setting the preferred activity to what it happens to be already
18926                        if (DEBUG_PREFERRED) {
18927                            Slog.i(TAG, "Replacing with same preferred activity "
18928                                    + cur.mPref.mShortComponent + " for user "
18929                                    + userId + ":");
18930                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18931                        }
18932                        return;
18933                    }
18934                }
18935
18936                if (existing != null) {
18937                    if (DEBUG_PREFERRED) {
18938                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18939                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18940                    }
18941                    for (int i = 0; i < existing.size(); i++) {
18942                        PreferredActivity pa = existing.get(i);
18943                        if (DEBUG_PREFERRED) {
18944                            Slog.i(TAG, "Removing existing preferred activity "
18945                                    + pa.mPref.mComponent + ":");
18946                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18947                        }
18948                        pir.removeFilter(pa);
18949                    }
18950                }
18951            }
18952            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18953                    "Replacing preferred");
18954        }
18955    }
18956
18957    @Override
18958    public void clearPackagePreferredActivities(String packageName) {
18959        final int callingUid = Binder.getCallingUid();
18960        if (getInstantAppPackageName(callingUid) != null) {
18961            return;
18962        }
18963        // writer
18964        synchronized (mPackages) {
18965            PackageParser.Package pkg = mPackages.get(packageName);
18966            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18967                if (mContext.checkCallingOrSelfPermission(
18968                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18969                        != PackageManager.PERMISSION_GRANTED) {
18970                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18971                            < Build.VERSION_CODES.FROYO) {
18972                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18973                                + callingUid);
18974                        return;
18975                    }
18976                    mContext.enforceCallingOrSelfPermission(
18977                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18978                }
18979            }
18980            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18981            if (ps != null
18982                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18983                return;
18984            }
18985            int user = UserHandle.getCallingUserId();
18986            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18987                scheduleWritePackageRestrictionsLocked(user);
18988            }
18989        }
18990    }
18991
18992    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18993    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18994        ArrayList<PreferredActivity> removed = null;
18995        boolean changed = false;
18996        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18997            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18998            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18999            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19000                continue;
19001            }
19002            Iterator<PreferredActivity> it = pir.filterIterator();
19003            while (it.hasNext()) {
19004                PreferredActivity pa = it.next();
19005                // Mark entry for removal only if it matches the package name
19006                // and the entry is of type "always".
19007                if (packageName == null ||
19008                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19009                                && pa.mPref.mAlways)) {
19010                    if (removed == null) {
19011                        removed = new ArrayList<PreferredActivity>();
19012                    }
19013                    removed.add(pa);
19014                }
19015            }
19016            if (removed != null) {
19017                for (int j=0; j<removed.size(); j++) {
19018                    PreferredActivity pa = removed.get(j);
19019                    pir.removeFilter(pa);
19020                }
19021                changed = true;
19022            }
19023        }
19024        if (changed) {
19025            postPreferredActivityChangedBroadcast(userId);
19026        }
19027        return changed;
19028    }
19029
19030    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19031    private void clearIntentFilterVerificationsLPw(int userId) {
19032        final int packageCount = mPackages.size();
19033        for (int i = 0; i < packageCount; i++) {
19034            PackageParser.Package pkg = mPackages.valueAt(i);
19035            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19036        }
19037    }
19038
19039    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19040    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19041        if (userId == UserHandle.USER_ALL) {
19042            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19043                    sUserManager.getUserIds())) {
19044                for (int oneUserId : sUserManager.getUserIds()) {
19045                    scheduleWritePackageRestrictionsLocked(oneUserId);
19046                }
19047            }
19048        } else {
19049            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19050                scheduleWritePackageRestrictionsLocked(userId);
19051            }
19052        }
19053    }
19054
19055    /** Clears state for all users, and touches intent filter verification policy */
19056    void clearDefaultBrowserIfNeeded(String packageName) {
19057        for (int oneUserId : sUserManager.getUserIds()) {
19058            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19059        }
19060    }
19061
19062    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19063        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19064        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19065            if (packageName.equals(defaultBrowserPackageName)) {
19066                setDefaultBrowserPackageName(null, userId);
19067            }
19068        }
19069    }
19070
19071    @Override
19072    public void resetApplicationPreferences(int userId) {
19073        mContext.enforceCallingOrSelfPermission(
19074                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19075        final long identity = Binder.clearCallingIdentity();
19076        // writer
19077        try {
19078            synchronized (mPackages) {
19079                clearPackagePreferredActivitiesLPw(null, userId);
19080                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19081                // TODO: We have to reset the default SMS and Phone. This requires
19082                // significant refactoring to keep all default apps in the package
19083                // manager (cleaner but more work) or have the services provide
19084                // callbacks to the package manager to request a default app reset.
19085                applyFactoryDefaultBrowserLPw(userId);
19086                clearIntentFilterVerificationsLPw(userId);
19087                primeDomainVerificationsLPw(userId);
19088                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19089                scheduleWritePackageRestrictionsLocked(userId);
19090            }
19091            resetNetworkPolicies(userId);
19092        } finally {
19093            Binder.restoreCallingIdentity(identity);
19094        }
19095    }
19096
19097    @Override
19098    public int getPreferredActivities(List<IntentFilter> outFilters,
19099            List<ComponentName> outActivities, String packageName) {
19100        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19101            return 0;
19102        }
19103        int num = 0;
19104        final int userId = UserHandle.getCallingUserId();
19105        // reader
19106        synchronized (mPackages) {
19107            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19108            if (pir != null) {
19109                final Iterator<PreferredActivity> it = pir.filterIterator();
19110                while (it.hasNext()) {
19111                    final PreferredActivity pa = it.next();
19112                    if (packageName == null
19113                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19114                                    && pa.mPref.mAlways)) {
19115                        if (outFilters != null) {
19116                            outFilters.add(new IntentFilter(pa));
19117                        }
19118                        if (outActivities != null) {
19119                            outActivities.add(pa.mPref.mComponent);
19120                        }
19121                    }
19122                }
19123            }
19124        }
19125
19126        return num;
19127    }
19128
19129    @Override
19130    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19131            int userId) {
19132        int callingUid = Binder.getCallingUid();
19133        if (callingUid != Process.SYSTEM_UID) {
19134            throw new SecurityException(
19135                    "addPersistentPreferredActivity can only be run by the system");
19136        }
19137        if (filter.countActions() == 0) {
19138            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19139            return;
19140        }
19141        synchronized (mPackages) {
19142            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19143                    ":");
19144            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19145            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19146                    new PersistentPreferredActivity(filter, activity));
19147            scheduleWritePackageRestrictionsLocked(userId);
19148            postPreferredActivityChangedBroadcast(userId);
19149        }
19150    }
19151
19152    @Override
19153    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19154        int callingUid = Binder.getCallingUid();
19155        if (callingUid != Process.SYSTEM_UID) {
19156            throw new SecurityException(
19157                    "clearPackagePersistentPreferredActivities can only be run by the system");
19158        }
19159        ArrayList<PersistentPreferredActivity> removed = null;
19160        boolean changed = false;
19161        synchronized (mPackages) {
19162            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19163                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19164                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19165                        .valueAt(i);
19166                if (userId != thisUserId) {
19167                    continue;
19168                }
19169                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19170                while (it.hasNext()) {
19171                    PersistentPreferredActivity ppa = it.next();
19172                    // Mark entry for removal only if it matches the package name.
19173                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19174                        if (removed == null) {
19175                            removed = new ArrayList<PersistentPreferredActivity>();
19176                        }
19177                        removed.add(ppa);
19178                    }
19179                }
19180                if (removed != null) {
19181                    for (int j=0; j<removed.size(); j++) {
19182                        PersistentPreferredActivity ppa = removed.get(j);
19183                        ppir.removeFilter(ppa);
19184                    }
19185                    changed = true;
19186                }
19187            }
19188
19189            if (changed) {
19190                scheduleWritePackageRestrictionsLocked(userId);
19191                postPreferredActivityChangedBroadcast(userId);
19192            }
19193        }
19194    }
19195
19196    /**
19197     * Common machinery for picking apart a restored XML blob and passing
19198     * it to a caller-supplied functor to be applied to the running system.
19199     */
19200    private void restoreFromXml(XmlPullParser parser, int userId,
19201            String expectedStartTag, BlobXmlRestorer functor)
19202            throws IOException, XmlPullParserException {
19203        int type;
19204        while ((type = parser.next()) != XmlPullParser.START_TAG
19205                && type != XmlPullParser.END_DOCUMENT) {
19206        }
19207        if (type != XmlPullParser.START_TAG) {
19208            // oops didn't find a start tag?!
19209            if (DEBUG_BACKUP) {
19210                Slog.e(TAG, "Didn't find start tag during restore");
19211            }
19212            return;
19213        }
19214Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19215        // this is supposed to be TAG_PREFERRED_BACKUP
19216        if (!expectedStartTag.equals(parser.getName())) {
19217            if (DEBUG_BACKUP) {
19218                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19219            }
19220            return;
19221        }
19222
19223        // skip interfering stuff, then we're aligned with the backing implementation
19224        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19225Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19226        functor.apply(parser, userId);
19227    }
19228
19229    private interface BlobXmlRestorer {
19230        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19231    }
19232
19233    /**
19234     * Non-Binder method, support for the backup/restore mechanism: write the
19235     * full set of preferred activities in its canonical XML format.  Returns the
19236     * XML output as a byte array, or null if there is none.
19237     */
19238    @Override
19239    public byte[] getPreferredActivityBackup(int userId) {
19240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19241            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19242        }
19243
19244        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19245        try {
19246            final XmlSerializer serializer = new FastXmlSerializer();
19247            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19248            serializer.startDocument(null, true);
19249            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19250
19251            synchronized (mPackages) {
19252                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19253            }
19254
19255            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19256            serializer.endDocument();
19257            serializer.flush();
19258        } catch (Exception e) {
19259            if (DEBUG_BACKUP) {
19260                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19261            }
19262            return null;
19263        }
19264
19265        return dataStream.toByteArray();
19266    }
19267
19268    @Override
19269    public void restorePreferredActivities(byte[] backup, int userId) {
19270        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19271            throw new SecurityException("Only the system may call restorePreferredActivities()");
19272        }
19273
19274        try {
19275            final XmlPullParser parser = Xml.newPullParser();
19276            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19277            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19278                    new BlobXmlRestorer() {
19279                        @Override
19280                        public void apply(XmlPullParser parser, int userId)
19281                                throws XmlPullParserException, IOException {
19282                            synchronized (mPackages) {
19283                                mSettings.readPreferredActivitiesLPw(parser, userId);
19284                            }
19285                        }
19286                    } );
19287        } catch (Exception e) {
19288            if (DEBUG_BACKUP) {
19289                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19290            }
19291        }
19292    }
19293
19294    /**
19295     * Non-Binder method, support for the backup/restore mechanism: write the
19296     * default browser (etc) settings in its canonical XML format.  Returns the default
19297     * browser XML representation as a byte array, or null if there is none.
19298     */
19299    @Override
19300    public byte[] getDefaultAppsBackup(int userId) {
19301        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19302            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19303        }
19304
19305        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19306        try {
19307            final XmlSerializer serializer = new FastXmlSerializer();
19308            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19309            serializer.startDocument(null, true);
19310            serializer.startTag(null, TAG_DEFAULT_APPS);
19311
19312            synchronized (mPackages) {
19313                mSettings.writeDefaultAppsLPr(serializer, userId);
19314            }
19315
19316            serializer.endTag(null, TAG_DEFAULT_APPS);
19317            serializer.endDocument();
19318            serializer.flush();
19319        } catch (Exception e) {
19320            if (DEBUG_BACKUP) {
19321                Slog.e(TAG, "Unable to write default apps for backup", e);
19322            }
19323            return null;
19324        }
19325
19326        return dataStream.toByteArray();
19327    }
19328
19329    @Override
19330    public void restoreDefaultApps(byte[] backup, int userId) {
19331        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19332            throw new SecurityException("Only the system may call restoreDefaultApps()");
19333        }
19334
19335        try {
19336            final XmlPullParser parser = Xml.newPullParser();
19337            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19338            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19339                    new BlobXmlRestorer() {
19340                        @Override
19341                        public void apply(XmlPullParser parser, int userId)
19342                                throws XmlPullParserException, IOException {
19343                            synchronized (mPackages) {
19344                                mSettings.readDefaultAppsLPw(parser, userId);
19345                            }
19346                        }
19347                    } );
19348        } catch (Exception e) {
19349            if (DEBUG_BACKUP) {
19350                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19351            }
19352        }
19353    }
19354
19355    @Override
19356    public byte[] getIntentFilterVerificationBackup(int userId) {
19357        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19358            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19359        }
19360
19361        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19362        try {
19363            final XmlSerializer serializer = new FastXmlSerializer();
19364            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19365            serializer.startDocument(null, true);
19366            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19367
19368            synchronized (mPackages) {
19369                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19370            }
19371
19372            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19373            serializer.endDocument();
19374            serializer.flush();
19375        } catch (Exception e) {
19376            if (DEBUG_BACKUP) {
19377                Slog.e(TAG, "Unable to write default apps for backup", e);
19378            }
19379            return null;
19380        }
19381
19382        return dataStream.toByteArray();
19383    }
19384
19385    @Override
19386    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19387        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19388            throw new SecurityException("Only the system may call restorePreferredActivities()");
19389        }
19390
19391        try {
19392            final XmlPullParser parser = Xml.newPullParser();
19393            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19394            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19395                    new BlobXmlRestorer() {
19396                        @Override
19397                        public void apply(XmlPullParser parser, int userId)
19398                                throws XmlPullParserException, IOException {
19399                            synchronized (mPackages) {
19400                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19401                                mSettings.writeLPr();
19402                            }
19403                        }
19404                    } );
19405        } catch (Exception e) {
19406            if (DEBUG_BACKUP) {
19407                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19408            }
19409        }
19410    }
19411
19412    @Override
19413    public byte[] getPermissionGrantBackup(int userId) {
19414        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19415            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19416        }
19417
19418        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19419        try {
19420            final XmlSerializer serializer = new FastXmlSerializer();
19421            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19422            serializer.startDocument(null, true);
19423            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19424
19425            synchronized (mPackages) {
19426                serializeRuntimePermissionGrantsLPr(serializer, userId);
19427            }
19428
19429            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19430            serializer.endDocument();
19431            serializer.flush();
19432        } catch (Exception e) {
19433            if (DEBUG_BACKUP) {
19434                Slog.e(TAG, "Unable to write default apps for backup", e);
19435            }
19436            return null;
19437        }
19438
19439        return dataStream.toByteArray();
19440    }
19441
19442    @Override
19443    public void restorePermissionGrants(byte[] backup, int userId) {
19444        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19445            throw new SecurityException("Only the system may call restorePermissionGrants()");
19446        }
19447
19448        try {
19449            final XmlPullParser parser = Xml.newPullParser();
19450            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19451            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19452                    new BlobXmlRestorer() {
19453                        @Override
19454                        public void apply(XmlPullParser parser, int userId)
19455                                throws XmlPullParserException, IOException {
19456                            synchronized (mPackages) {
19457                                processRestoredPermissionGrantsLPr(parser, userId);
19458                            }
19459                        }
19460                    } );
19461        } catch (Exception e) {
19462            if (DEBUG_BACKUP) {
19463                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19464            }
19465        }
19466    }
19467
19468    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19469            throws IOException {
19470        serializer.startTag(null, TAG_ALL_GRANTS);
19471
19472        final int N = mSettings.mPackages.size();
19473        for (int i = 0; i < N; i++) {
19474            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19475            boolean pkgGrantsKnown = false;
19476
19477            PermissionsState packagePerms = ps.getPermissionsState();
19478
19479            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19480                final int grantFlags = state.getFlags();
19481                // only look at grants that are not system/policy fixed
19482                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19483                    final boolean isGranted = state.isGranted();
19484                    // And only back up the user-twiddled state bits
19485                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19486                        final String packageName = mSettings.mPackages.keyAt(i);
19487                        if (!pkgGrantsKnown) {
19488                            serializer.startTag(null, TAG_GRANT);
19489                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19490                            pkgGrantsKnown = true;
19491                        }
19492
19493                        final boolean userSet =
19494                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19495                        final boolean userFixed =
19496                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19497                        final boolean revoke =
19498                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19499
19500                        serializer.startTag(null, TAG_PERMISSION);
19501                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19502                        if (isGranted) {
19503                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19504                        }
19505                        if (userSet) {
19506                            serializer.attribute(null, ATTR_USER_SET, "true");
19507                        }
19508                        if (userFixed) {
19509                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19510                        }
19511                        if (revoke) {
19512                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19513                        }
19514                        serializer.endTag(null, TAG_PERMISSION);
19515                    }
19516                }
19517            }
19518
19519            if (pkgGrantsKnown) {
19520                serializer.endTag(null, TAG_GRANT);
19521            }
19522        }
19523
19524        serializer.endTag(null, TAG_ALL_GRANTS);
19525    }
19526
19527    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19528            throws XmlPullParserException, IOException {
19529        String pkgName = null;
19530        int outerDepth = parser.getDepth();
19531        int type;
19532        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19533                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19534            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19535                continue;
19536            }
19537
19538            final String tagName = parser.getName();
19539            if (tagName.equals(TAG_GRANT)) {
19540                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19541                if (DEBUG_BACKUP) {
19542                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19543                }
19544            } else if (tagName.equals(TAG_PERMISSION)) {
19545
19546                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19547                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19548
19549                int newFlagSet = 0;
19550                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19551                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19552                }
19553                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19554                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19555                }
19556                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19557                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19558                }
19559                if (DEBUG_BACKUP) {
19560                    Slog.v(TAG, "  + Restoring grant:"
19561                            + " pkg=" + pkgName
19562                            + " perm=" + permName
19563                            + " granted=" + isGranted
19564                            + " bits=0x" + Integer.toHexString(newFlagSet));
19565                }
19566                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19567                if (ps != null) {
19568                    // Already installed so we apply the grant immediately
19569                    if (DEBUG_BACKUP) {
19570                        Slog.v(TAG, "        + already installed; applying");
19571                    }
19572                    PermissionsState perms = ps.getPermissionsState();
19573                    BasePermission bp =
19574                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19575                    if (bp != null) {
19576                        if (isGranted) {
19577                            perms.grantRuntimePermission(bp, userId);
19578                        }
19579                        if (newFlagSet != 0) {
19580                            perms.updatePermissionFlags(
19581                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19582                        }
19583                    }
19584                } else {
19585                    // Need to wait for post-restore install to apply the grant
19586                    if (DEBUG_BACKUP) {
19587                        Slog.v(TAG, "        - not yet installed; saving for later");
19588                    }
19589                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19590                            isGranted, newFlagSet, userId);
19591                }
19592            } else {
19593                PackageManagerService.reportSettingsProblem(Log.WARN,
19594                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19595                XmlUtils.skipCurrentTag(parser);
19596            }
19597        }
19598
19599        scheduleWriteSettingsLocked();
19600        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19601    }
19602
19603    @Override
19604    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19605            int sourceUserId, int targetUserId, int flags) {
19606        mContext.enforceCallingOrSelfPermission(
19607                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19608        int callingUid = Binder.getCallingUid();
19609        enforceOwnerRights(ownerPackage, callingUid);
19610        PackageManagerServiceUtils.enforceShellRestriction(
19611                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19612        if (intentFilter.countActions() == 0) {
19613            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19614            return;
19615        }
19616        synchronized (mPackages) {
19617            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19618                    ownerPackage, targetUserId, flags);
19619            CrossProfileIntentResolver resolver =
19620                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19621            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19622            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19623            if (existing != null) {
19624                int size = existing.size();
19625                for (int i = 0; i < size; i++) {
19626                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19627                        return;
19628                    }
19629                }
19630            }
19631            resolver.addFilter(newFilter);
19632            scheduleWritePackageRestrictionsLocked(sourceUserId);
19633        }
19634    }
19635
19636    @Override
19637    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19638        mContext.enforceCallingOrSelfPermission(
19639                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19640        final int callingUid = Binder.getCallingUid();
19641        enforceOwnerRights(ownerPackage, callingUid);
19642        PackageManagerServiceUtils.enforceShellRestriction(
19643                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19644        synchronized (mPackages) {
19645            CrossProfileIntentResolver resolver =
19646                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19647            ArraySet<CrossProfileIntentFilter> set =
19648                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19649            for (CrossProfileIntentFilter filter : set) {
19650                if (filter.getOwnerPackage().equals(ownerPackage)) {
19651                    resolver.removeFilter(filter);
19652                }
19653            }
19654            scheduleWritePackageRestrictionsLocked(sourceUserId);
19655        }
19656    }
19657
19658    // Enforcing that callingUid is owning pkg on userId
19659    private void enforceOwnerRights(String pkg, int callingUid) {
19660        // The system owns everything.
19661        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19662            return;
19663        }
19664        final int callingUserId = UserHandle.getUserId(callingUid);
19665        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19666        if (pi == null) {
19667            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19668                    + callingUserId);
19669        }
19670        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19671            throw new SecurityException("Calling uid " + callingUid
19672                    + " does not own package " + pkg);
19673        }
19674    }
19675
19676    @Override
19677    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19678        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19679            return null;
19680        }
19681        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19682    }
19683
19684    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19685        UserManagerService ums = UserManagerService.getInstance();
19686        if (ums != null) {
19687            final UserInfo parent = ums.getProfileParent(userId);
19688            final int launcherUid = (parent != null) ? parent.id : userId;
19689            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19690            if (launcherComponent != null) {
19691                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19692                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19693                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19694                        .setPackage(launcherComponent.getPackageName());
19695                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19696            }
19697        }
19698    }
19699
19700    /**
19701     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19702     * then reports the most likely home activity or null if there are more than one.
19703     */
19704    private ComponentName getDefaultHomeActivity(int userId) {
19705        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19706        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19707        if (cn != null) {
19708            return cn;
19709        }
19710
19711        // Find the launcher with the highest priority and return that component if there are no
19712        // other home activity with the same priority.
19713        int lastPriority = Integer.MIN_VALUE;
19714        ComponentName lastComponent = null;
19715        final int size = allHomeCandidates.size();
19716        for (int i = 0; i < size; i++) {
19717            final ResolveInfo ri = allHomeCandidates.get(i);
19718            if (ri.priority > lastPriority) {
19719                lastComponent = ri.activityInfo.getComponentName();
19720                lastPriority = ri.priority;
19721            } else if (ri.priority == lastPriority) {
19722                // Two components found with same priority.
19723                lastComponent = null;
19724            }
19725        }
19726        return lastComponent;
19727    }
19728
19729    private Intent getHomeIntent() {
19730        Intent intent = new Intent(Intent.ACTION_MAIN);
19731        intent.addCategory(Intent.CATEGORY_HOME);
19732        intent.addCategory(Intent.CATEGORY_DEFAULT);
19733        return intent;
19734    }
19735
19736    private IntentFilter getHomeFilter() {
19737        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19738        filter.addCategory(Intent.CATEGORY_HOME);
19739        filter.addCategory(Intent.CATEGORY_DEFAULT);
19740        return filter;
19741    }
19742
19743    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19744            int userId) {
19745        Intent intent  = getHomeIntent();
19746        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19747                PackageManager.GET_META_DATA, userId);
19748        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19749                true, false, false, userId);
19750
19751        allHomeCandidates.clear();
19752        if (list != null) {
19753            for (ResolveInfo ri : list) {
19754                allHomeCandidates.add(ri);
19755            }
19756        }
19757        return (preferred == null || preferred.activityInfo == null)
19758                ? null
19759                : new ComponentName(preferred.activityInfo.packageName,
19760                        preferred.activityInfo.name);
19761    }
19762
19763    @Override
19764    public void setHomeActivity(ComponentName comp, int userId) {
19765        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19766            return;
19767        }
19768        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19769        getHomeActivitiesAsUser(homeActivities, userId);
19770
19771        boolean found = false;
19772
19773        final int size = homeActivities.size();
19774        final ComponentName[] set = new ComponentName[size];
19775        for (int i = 0; i < size; i++) {
19776            final ResolveInfo candidate = homeActivities.get(i);
19777            final ActivityInfo info = candidate.activityInfo;
19778            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19779            set[i] = activityName;
19780            if (!found && activityName.equals(comp)) {
19781                found = true;
19782            }
19783        }
19784        if (!found) {
19785            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19786                    + userId);
19787        }
19788        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19789                set, comp, userId);
19790    }
19791
19792    private @Nullable String getSetupWizardPackageName() {
19793        final Intent intent = new Intent(Intent.ACTION_MAIN);
19794        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19795
19796        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19797                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19798                        | MATCH_DISABLED_COMPONENTS,
19799                UserHandle.myUserId());
19800        if (matches.size() == 1) {
19801            return matches.get(0).getComponentInfo().packageName;
19802        } else {
19803            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19804                    + ": matches=" + matches);
19805            return null;
19806        }
19807    }
19808
19809    private @Nullable String getStorageManagerPackageName() {
19810        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19811
19812        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19813                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19814                        | MATCH_DISABLED_COMPONENTS,
19815                UserHandle.myUserId());
19816        if (matches.size() == 1) {
19817            return matches.get(0).getComponentInfo().packageName;
19818        } else {
19819            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19820                    + matches.size() + ": matches=" + matches);
19821            return null;
19822        }
19823    }
19824
19825    @Override
19826    public void setApplicationEnabledSetting(String appPackageName,
19827            int newState, int flags, int userId, String callingPackage) {
19828        if (!sUserManager.exists(userId)) return;
19829        if (callingPackage == null) {
19830            callingPackage = Integer.toString(Binder.getCallingUid());
19831        }
19832        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19833    }
19834
19835    @Override
19836    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19837        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19838        synchronized (mPackages) {
19839            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19840            if (pkgSetting != null) {
19841                pkgSetting.setUpdateAvailable(updateAvailable);
19842            }
19843        }
19844    }
19845
19846    @Override
19847    public void setComponentEnabledSetting(ComponentName componentName,
19848            int newState, int flags, int userId) {
19849        if (!sUserManager.exists(userId)) return;
19850        setEnabledSetting(componentName.getPackageName(),
19851                componentName.getClassName(), newState, flags, userId, null);
19852    }
19853
19854    private void setEnabledSetting(final String packageName, String className, int newState,
19855            final int flags, int userId, String callingPackage) {
19856        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19857              || newState == COMPONENT_ENABLED_STATE_ENABLED
19858              || newState == COMPONENT_ENABLED_STATE_DISABLED
19859              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19860              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19861            throw new IllegalArgumentException("Invalid new component state: "
19862                    + newState);
19863        }
19864        PackageSetting pkgSetting;
19865        final int callingUid = Binder.getCallingUid();
19866        final int permission;
19867        if (callingUid == Process.SYSTEM_UID) {
19868            permission = PackageManager.PERMISSION_GRANTED;
19869        } else {
19870            permission = mContext.checkCallingOrSelfPermission(
19871                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19872        }
19873        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19874                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19875        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19876        boolean sendNow = false;
19877        boolean isApp = (className == null);
19878        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19879        String componentName = isApp ? packageName : className;
19880        int packageUid = -1;
19881        ArrayList<String> components;
19882
19883        // reader
19884        synchronized (mPackages) {
19885            pkgSetting = mSettings.mPackages.get(packageName);
19886            if (pkgSetting == null) {
19887                if (!isCallerInstantApp) {
19888                    if (className == null) {
19889                        throw new IllegalArgumentException("Unknown package: " + packageName);
19890                    }
19891                    throw new IllegalArgumentException(
19892                            "Unknown component: " + packageName + "/" + className);
19893                } else {
19894                    // throw SecurityException to prevent leaking package information
19895                    throw new SecurityException(
19896                            "Attempt to change component state; "
19897                            + "pid=" + Binder.getCallingPid()
19898                            + ", uid=" + callingUid
19899                            + (className == null
19900                                    ? ", package=" + packageName
19901                                    : ", component=" + packageName + "/" + className));
19902                }
19903            }
19904        }
19905
19906        // Limit who can change which apps
19907        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19908            // Don't allow apps that don't have permission to modify other apps
19909            if (!allowedByPermission
19910                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19911                throw new SecurityException(
19912                        "Attempt to change component state; "
19913                        + "pid=" + Binder.getCallingPid()
19914                        + ", uid=" + callingUid
19915                        + (className == null
19916                                ? ", package=" + packageName
19917                                : ", component=" + packageName + "/" + className));
19918            }
19919            // Don't allow changing protected packages.
19920            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19921                throw new SecurityException("Cannot disable a protected package: " + packageName);
19922            }
19923        }
19924
19925        synchronized (mPackages) {
19926            if (callingUid == Process.SHELL_UID
19927                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19928                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19929                // unless it is a test package.
19930                int oldState = pkgSetting.getEnabled(userId);
19931                if (className == null
19932                        &&
19933                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19934                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19935                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19936                        &&
19937                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19938                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19939                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19940                    // ok
19941                } else {
19942                    throw new SecurityException(
19943                            "Shell cannot change component state for " + packageName + "/"
19944                                    + className + " to " + newState);
19945                }
19946            }
19947        }
19948        if (className == null) {
19949            // We're dealing with an application/package level state change
19950            synchronized (mPackages) {
19951                if (pkgSetting.getEnabled(userId) == newState) {
19952                    // Nothing to do
19953                    return;
19954                }
19955            }
19956            // If we're enabling a system stub, there's a little more work to do.
19957            // Prior to enabling the package, we need to decompress the APK(s) to the
19958            // data partition and then replace the version on the system partition.
19959            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19960            final boolean isSystemStub = deletedPkg.isStub
19961                    && deletedPkg.isSystem();
19962            if (isSystemStub
19963                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19964                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19965                final File codePath = decompressPackage(deletedPkg);
19966                if (codePath == null) {
19967                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19968                    return;
19969                }
19970                // TODO remove direct parsing of the package object during internal cleanup
19971                // of scan package
19972                // We need to call parse directly here for no other reason than we need
19973                // the new package in order to disable the old one [we use the information
19974                // for some internal optimization to optionally create a new package setting
19975                // object on replace]. However, we can't get the package from the scan
19976                // because the scan modifies live structures and we need to remove the
19977                // old [system] package from the system before a scan can be attempted.
19978                // Once scan is indempotent we can remove this parse and use the package
19979                // object we scanned, prior to adding it to package settings.
19980                final PackageParser pp = new PackageParser();
19981                pp.setSeparateProcesses(mSeparateProcesses);
19982                pp.setDisplayMetrics(mMetrics);
19983                pp.setCallback(mPackageParserCallback);
19984                final PackageParser.Package tmpPkg;
19985                try {
19986                    final @ParseFlags int parseFlags = mDefParseFlags
19987                            | PackageParser.PARSE_MUST_BE_APK
19988                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19989                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19990                } catch (PackageParserException e) {
19991                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19992                    return;
19993                }
19994                synchronized (mInstallLock) {
19995                    // Disable the stub and remove any package entries
19996                    removePackageLI(deletedPkg, true);
19997                    synchronized (mPackages) {
19998                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19999                    }
20000                    final PackageParser.Package pkg;
20001                    try (PackageFreezer freezer =
20002                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20003                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20004                                | PackageParser.PARSE_ENFORCE_CODE;
20005                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20006                                0 /*currentTime*/, null /*user*/);
20007                        prepareAppDataAfterInstallLIF(pkg);
20008                        synchronized (mPackages) {
20009                            try {
20010                                updateSharedLibrariesLPr(pkg, null);
20011                            } catch (PackageManagerException e) {
20012                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20013                            }
20014                            mPermissionManager.updatePermissions(
20015                                    pkg.packageName, pkg, true, mPackages.values(),
20016                                    mPermissionCallback);
20017                            mSettings.writeLPr();
20018                        }
20019                    } catch (PackageManagerException e) {
20020                        // Whoops! Something went wrong; try to roll back to the stub
20021                        Slog.w(TAG, "Failed to install compressed system package:"
20022                                + pkgSetting.name, e);
20023                        // Remove the failed install
20024                        removeCodePathLI(codePath);
20025
20026                        // Install the system package
20027                        try (PackageFreezer freezer =
20028                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20029                            synchronized (mPackages) {
20030                                // NOTE: The system package always needs to be enabled; even
20031                                // if it's for a compressed stub. If we don't, installing the
20032                                // system package fails during scan [scanning checks the disabled
20033                                // packages]. We will reverse this later, after we've "installed"
20034                                // the stub.
20035                                // This leaves us in a fragile state; the stub should never be
20036                                // enabled, so, cross your fingers and hope nothing goes wrong
20037                                // until we can disable the package later.
20038                                enableSystemPackageLPw(deletedPkg);
20039                            }
20040                            installPackageFromSystemLIF(deletedPkg.codePath,
20041                                    false /*isPrivileged*/, null /*allUserHandles*/,
20042                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20043                                    true /*writeSettings*/);
20044                        } catch (PackageManagerException pme) {
20045                            Slog.w(TAG, "Failed to restore system package:"
20046                                    + deletedPkg.packageName, pme);
20047                        } finally {
20048                            synchronized (mPackages) {
20049                                mSettings.disableSystemPackageLPw(
20050                                        deletedPkg.packageName, true /*replaced*/);
20051                                mSettings.writeLPr();
20052                            }
20053                        }
20054                        return;
20055                    }
20056                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20057                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20058                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20059                    mDexManager.notifyPackageUpdated(pkg.packageName,
20060                            pkg.baseCodePath, pkg.splitCodePaths);
20061                }
20062            }
20063            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20064                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20065                // Don't care about who enables an app.
20066                callingPackage = null;
20067            }
20068            synchronized (mPackages) {
20069                pkgSetting.setEnabled(newState, userId, callingPackage);
20070            }
20071        } else {
20072            synchronized (mPackages) {
20073                // We're dealing with a component level state change
20074                // First, verify that this is a valid class name.
20075                PackageParser.Package pkg = pkgSetting.pkg;
20076                if (pkg == null || !pkg.hasComponentClassName(className)) {
20077                    if (pkg != null &&
20078                            pkg.applicationInfo.targetSdkVersion >=
20079                                    Build.VERSION_CODES.JELLY_BEAN) {
20080                        throw new IllegalArgumentException("Component class " + className
20081                                + " does not exist in " + packageName);
20082                    } else {
20083                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20084                                + className + " does not exist in " + packageName);
20085                    }
20086                }
20087                switch (newState) {
20088                    case COMPONENT_ENABLED_STATE_ENABLED:
20089                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20090                            return;
20091                        }
20092                        break;
20093                    case COMPONENT_ENABLED_STATE_DISABLED:
20094                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20095                            return;
20096                        }
20097                        break;
20098                    case COMPONENT_ENABLED_STATE_DEFAULT:
20099                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20100                            return;
20101                        }
20102                        break;
20103                    default:
20104                        Slog.e(TAG, "Invalid new component state: " + newState);
20105                        return;
20106                }
20107            }
20108        }
20109        synchronized (mPackages) {
20110            scheduleWritePackageRestrictionsLocked(userId);
20111            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20112            final long callingId = Binder.clearCallingIdentity();
20113            try {
20114                updateInstantAppInstallerLocked(packageName);
20115            } finally {
20116                Binder.restoreCallingIdentity(callingId);
20117            }
20118            components = mPendingBroadcasts.get(userId, packageName);
20119            final boolean newPackage = components == null;
20120            if (newPackage) {
20121                components = new ArrayList<String>();
20122            }
20123            if (!components.contains(componentName)) {
20124                components.add(componentName);
20125            }
20126            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20127                sendNow = true;
20128                // Purge entry from pending broadcast list if another one exists already
20129                // since we are sending one right away.
20130                mPendingBroadcasts.remove(userId, packageName);
20131            } else {
20132                if (newPackage) {
20133                    mPendingBroadcasts.put(userId, packageName, components);
20134                }
20135                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20136                    // Schedule a message
20137                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20138                }
20139            }
20140        }
20141
20142        long callingId = Binder.clearCallingIdentity();
20143        try {
20144            if (sendNow) {
20145                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20146                sendPackageChangedBroadcast(packageName,
20147                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20148            }
20149        } finally {
20150            Binder.restoreCallingIdentity(callingId);
20151        }
20152    }
20153
20154    @Override
20155    public void flushPackageRestrictionsAsUser(int userId) {
20156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20157            return;
20158        }
20159        if (!sUserManager.exists(userId)) {
20160            return;
20161        }
20162        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20163                false /* checkShell */, "flushPackageRestrictions");
20164        synchronized (mPackages) {
20165            mSettings.writePackageRestrictionsLPr(userId);
20166            mDirtyUsers.remove(userId);
20167            if (mDirtyUsers.isEmpty()) {
20168                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20169            }
20170        }
20171    }
20172
20173    private void sendPackageChangedBroadcast(String packageName,
20174            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20175        if (DEBUG_INSTALL)
20176            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20177                    + componentNames);
20178        Bundle extras = new Bundle(4);
20179        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20180        String nameList[] = new String[componentNames.size()];
20181        componentNames.toArray(nameList);
20182        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20183        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20184        extras.putInt(Intent.EXTRA_UID, packageUid);
20185        // If this is not reporting a change of the overall package, then only send it
20186        // to registered receivers.  We don't want to launch a swath of apps for every
20187        // little component state change.
20188        final int flags = !componentNames.contains(packageName)
20189                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20190        final int userId = UserHandle.getUserId(packageUid);
20191        final boolean isInstantApp = isInstantApp(packageName, userId);
20192        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20193        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20194        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20195                userIds, instantUserIds);
20196    }
20197
20198    @Override
20199    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20200        if (!sUserManager.exists(userId)) return;
20201        final int callingUid = Binder.getCallingUid();
20202        if (getInstantAppPackageName(callingUid) != null) {
20203            return;
20204        }
20205        final int permission = mContext.checkCallingOrSelfPermission(
20206                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20207        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20208        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20209                true /* requireFullPermission */, true /* checkShell */, "stop package");
20210        // writer
20211        synchronized (mPackages) {
20212            final PackageSetting ps = mSettings.mPackages.get(packageName);
20213            if (!filterAppAccessLPr(ps, callingUid, userId)
20214                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20215                            allowedByPermission, callingUid, userId)) {
20216                scheduleWritePackageRestrictionsLocked(userId);
20217            }
20218        }
20219    }
20220
20221    @Override
20222    public String getInstallerPackageName(String packageName) {
20223        final int callingUid = Binder.getCallingUid();
20224        if (getInstantAppPackageName(callingUid) != null) {
20225            return null;
20226        }
20227        // reader
20228        synchronized (mPackages) {
20229            final PackageSetting ps = mSettings.mPackages.get(packageName);
20230            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20231                return null;
20232            }
20233            return mSettings.getInstallerPackageNameLPr(packageName);
20234        }
20235    }
20236
20237    public boolean isOrphaned(String packageName) {
20238        // reader
20239        synchronized (mPackages) {
20240            return mSettings.isOrphaned(packageName);
20241        }
20242    }
20243
20244    @Override
20245    public int getApplicationEnabledSetting(String packageName, int userId) {
20246        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20247        int callingUid = Binder.getCallingUid();
20248        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20249                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20250        // reader
20251        synchronized (mPackages) {
20252            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20253                return COMPONENT_ENABLED_STATE_DISABLED;
20254            }
20255            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20256        }
20257    }
20258
20259    @Override
20260    public int getComponentEnabledSetting(ComponentName component, int userId) {
20261        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20262        int callingUid = Binder.getCallingUid();
20263        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20264                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20265        synchronized (mPackages) {
20266            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20267                    component, TYPE_UNKNOWN, userId)) {
20268                return COMPONENT_ENABLED_STATE_DISABLED;
20269            }
20270            return mSettings.getComponentEnabledSettingLPr(component, userId);
20271        }
20272    }
20273
20274    @Override
20275    public void enterSafeMode() {
20276        enforceSystemOrRoot("Only the system can request entering safe mode");
20277
20278        if (!mSystemReady) {
20279            mSafeMode = true;
20280        }
20281    }
20282
20283    @Override
20284    public void systemReady() {
20285        enforceSystemOrRoot("Only the system can claim the system is ready");
20286
20287        mSystemReady = true;
20288        final ContentResolver resolver = mContext.getContentResolver();
20289        ContentObserver co = new ContentObserver(mHandler) {
20290            @Override
20291            public void onChange(boolean selfChange) {
20292                mEphemeralAppsDisabled =
20293                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20294                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20295            }
20296        };
20297        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20298                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20299                false, co, UserHandle.USER_SYSTEM);
20300        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20301                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20302        co.onChange(true);
20303
20304        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20305        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20306        // it is done.
20307        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20308            @Override
20309            public void onChange(boolean selfChange) {
20310                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20311                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20312                        oobEnabled == 1 ? "true" : "false");
20313            }
20314        };
20315        mContext.getContentResolver().registerContentObserver(
20316                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20317                UserHandle.USER_SYSTEM);
20318        // At boot, restore the value from the setting, which persists across reboot.
20319        privAppOobObserver.onChange(true);
20320
20321        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20322        // disabled after already being started.
20323        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20324                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20325
20326        // Read the compatibilty setting when the system is ready.
20327        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20328                mContext.getContentResolver(),
20329                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20330        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20331        if (DEBUG_SETTINGS) {
20332            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20333        }
20334
20335        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20336
20337        synchronized (mPackages) {
20338            // Verify that all of the preferred activity components actually
20339            // exist.  It is possible for applications to be updated and at
20340            // that point remove a previously declared activity component that
20341            // had been set as a preferred activity.  We try to clean this up
20342            // the next time we encounter that preferred activity, but it is
20343            // possible for the user flow to never be able to return to that
20344            // situation so here we do a sanity check to make sure we haven't
20345            // left any junk around.
20346            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20347            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20348                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20349                removed.clear();
20350                for (PreferredActivity pa : pir.filterSet()) {
20351                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20352                        removed.add(pa);
20353                    }
20354                }
20355                if (removed.size() > 0) {
20356                    for (int r=0; r<removed.size(); r++) {
20357                        PreferredActivity pa = removed.get(r);
20358                        Slog.w(TAG, "Removing dangling preferred activity: "
20359                                + pa.mPref.mComponent);
20360                        pir.removeFilter(pa);
20361                    }
20362                    mSettings.writePackageRestrictionsLPr(
20363                            mSettings.mPreferredActivities.keyAt(i));
20364                }
20365            }
20366
20367            for (int userId : UserManagerService.getInstance().getUserIds()) {
20368                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20369                    grantPermissionsUserIds = ArrayUtils.appendInt(
20370                            grantPermissionsUserIds, userId);
20371                }
20372            }
20373        }
20374        sUserManager.systemReady();
20375
20376        // If we upgraded grant all default permissions before kicking off.
20377        for (int userId : grantPermissionsUserIds) {
20378            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20379        }
20380
20381        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20382            // If we did not grant default permissions, we preload from this the
20383            // default permission exceptions lazily to ensure we don't hit the
20384            // disk on a new user creation.
20385            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20386        }
20387
20388        // Now that we've scanned all packages, and granted any default
20389        // permissions, ensure permissions are updated. Beware of dragons if you
20390        // try optimizing this.
20391        synchronized (mPackages) {
20392            mPermissionManager.updateAllPermissions(
20393                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20394                    mPermissionCallback);
20395        }
20396
20397        // Kick off any messages waiting for system ready
20398        if (mPostSystemReadyMessages != null) {
20399            for (Message msg : mPostSystemReadyMessages) {
20400                msg.sendToTarget();
20401            }
20402            mPostSystemReadyMessages = null;
20403        }
20404
20405        // Watch for external volumes that come and go over time
20406        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20407        storage.registerListener(mStorageListener);
20408
20409        mInstallerService.systemReady();
20410        mPackageDexOptimizer.systemReady();
20411
20412        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20413                StorageManagerInternal.class);
20414        StorageManagerInternal.addExternalStoragePolicy(
20415                new StorageManagerInternal.ExternalStorageMountPolicy() {
20416            @Override
20417            public int getMountMode(int uid, String packageName) {
20418                if (Process.isIsolated(uid)) {
20419                    return Zygote.MOUNT_EXTERNAL_NONE;
20420                }
20421                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20422                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20423                }
20424                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20425                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20426                }
20427                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20428                    return Zygote.MOUNT_EXTERNAL_READ;
20429                }
20430                return Zygote.MOUNT_EXTERNAL_WRITE;
20431            }
20432
20433            @Override
20434            public boolean hasExternalStorage(int uid, String packageName) {
20435                return true;
20436            }
20437        });
20438
20439        // Now that we're mostly running, clean up stale users and apps
20440        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20441        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20442
20443        mPermissionManager.systemReady();
20444    }
20445
20446    public void waitForAppDataPrepared() {
20447        if (mPrepareAppDataFuture == null) {
20448            return;
20449        }
20450        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20451        mPrepareAppDataFuture = null;
20452    }
20453
20454    @Override
20455    public boolean isSafeMode() {
20456        // allow instant applications
20457        return mSafeMode;
20458    }
20459
20460    @Override
20461    public boolean hasSystemUidErrors() {
20462        // allow instant applications
20463        return mHasSystemUidErrors;
20464    }
20465
20466    static String arrayToString(int[] array) {
20467        StringBuffer buf = new StringBuffer(128);
20468        buf.append('[');
20469        if (array != null) {
20470            for (int i=0; i<array.length; i++) {
20471                if (i > 0) buf.append(", ");
20472                buf.append(array[i]);
20473            }
20474        }
20475        buf.append(']');
20476        return buf.toString();
20477    }
20478
20479    @Override
20480    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20481            FileDescriptor err, String[] args, ShellCallback callback,
20482            ResultReceiver resultReceiver) {
20483        (new PackageManagerShellCommand(this)).exec(
20484                this, in, out, err, args, callback, resultReceiver);
20485    }
20486
20487    @Override
20488    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20489        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20490
20491        DumpState dumpState = new DumpState();
20492        boolean fullPreferred = false;
20493        boolean checkin = false;
20494
20495        String packageName = null;
20496        ArraySet<String> permissionNames = null;
20497
20498        int opti = 0;
20499        while (opti < args.length) {
20500            String opt = args[opti];
20501            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20502                break;
20503            }
20504            opti++;
20505
20506            if ("-a".equals(opt)) {
20507                // Right now we only know how to print all.
20508            } else if ("-h".equals(opt)) {
20509                pw.println("Package manager dump options:");
20510                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20511                pw.println("    --checkin: dump for a checkin");
20512                pw.println("    -f: print details of intent filters");
20513                pw.println("    -h: print this help");
20514                pw.println("  cmd may be one of:");
20515                pw.println("    l[ibraries]: list known shared libraries");
20516                pw.println("    f[eatures]: list device features");
20517                pw.println("    k[eysets]: print known keysets");
20518                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20519                pw.println("    perm[issions]: dump permissions");
20520                pw.println("    permission [name ...]: dump declaration and use of given permission");
20521                pw.println("    pref[erred]: print preferred package settings");
20522                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20523                pw.println("    prov[iders]: dump content providers");
20524                pw.println("    p[ackages]: dump installed packages");
20525                pw.println("    s[hared-users]: dump shared user IDs");
20526                pw.println("    m[essages]: print collected runtime messages");
20527                pw.println("    v[erifiers]: print package verifier info");
20528                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20529                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20530                pw.println("    version: print database version info");
20531                pw.println("    write: write current settings now");
20532                pw.println("    installs: details about install sessions");
20533                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20534                pw.println("    dexopt: dump dexopt state");
20535                pw.println("    compiler-stats: dump compiler statistics");
20536                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20537                pw.println("    <package.name>: info about given package");
20538                return;
20539            } else if ("--checkin".equals(opt)) {
20540                checkin = true;
20541            } else if ("-f".equals(opt)) {
20542                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20543            } else if ("--proto".equals(opt)) {
20544                dumpProto(fd);
20545                return;
20546            } else {
20547                pw.println("Unknown argument: " + opt + "; use -h for help");
20548            }
20549        }
20550
20551        // Is the caller requesting to dump a particular piece of data?
20552        if (opti < args.length) {
20553            String cmd = args[opti];
20554            opti++;
20555            // Is this a package name?
20556            if ("android".equals(cmd) || cmd.contains(".")) {
20557                packageName = cmd;
20558                // When dumping a single package, we always dump all of its
20559                // filter information since the amount of data will be reasonable.
20560                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20561            } else if ("check-permission".equals(cmd)) {
20562                if (opti >= args.length) {
20563                    pw.println("Error: check-permission missing permission argument");
20564                    return;
20565                }
20566                String perm = args[opti];
20567                opti++;
20568                if (opti >= args.length) {
20569                    pw.println("Error: check-permission missing package argument");
20570                    return;
20571                }
20572
20573                String pkg = args[opti];
20574                opti++;
20575                int user = UserHandle.getUserId(Binder.getCallingUid());
20576                if (opti < args.length) {
20577                    try {
20578                        user = Integer.parseInt(args[opti]);
20579                    } catch (NumberFormatException e) {
20580                        pw.println("Error: check-permission user argument is not a number: "
20581                                + args[opti]);
20582                        return;
20583                    }
20584                }
20585
20586                // Normalize package name to handle renamed packages and static libs
20587                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20588
20589                pw.println(checkPermission(perm, pkg, user));
20590                return;
20591            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20592                dumpState.setDump(DumpState.DUMP_LIBS);
20593            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20594                dumpState.setDump(DumpState.DUMP_FEATURES);
20595            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20596                if (opti >= args.length) {
20597                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20598                            | DumpState.DUMP_SERVICE_RESOLVERS
20599                            | DumpState.DUMP_RECEIVER_RESOLVERS
20600                            | DumpState.DUMP_CONTENT_RESOLVERS);
20601                } else {
20602                    while (opti < args.length) {
20603                        String name = args[opti];
20604                        if ("a".equals(name) || "activity".equals(name)) {
20605                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20606                        } else if ("s".equals(name) || "service".equals(name)) {
20607                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20608                        } else if ("r".equals(name) || "receiver".equals(name)) {
20609                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20610                        } else if ("c".equals(name) || "content".equals(name)) {
20611                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20612                        } else {
20613                            pw.println("Error: unknown resolver table type: " + name);
20614                            return;
20615                        }
20616                        opti++;
20617                    }
20618                }
20619            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20620                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20621            } else if ("permission".equals(cmd)) {
20622                if (opti >= args.length) {
20623                    pw.println("Error: permission requires permission name");
20624                    return;
20625                }
20626                permissionNames = new ArraySet<>();
20627                while (opti < args.length) {
20628                    permissionNames.add(args[opti]);
20629                    opti++;
20630                }
20631                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20632                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20633            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20634                dumpState.setDump(DumpState.DUMP_PREFERRED);
20635            } else if ("preferred-xml".equals(cmd)) {
20636                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20637                if (opti < args.length && "--full".equals(args[opti])) {
20638                    fullPreferred = true;
20639                    opti++;
20640                }
20641            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20642                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20643            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20644                dumpState.setDump(DumpState.DUMP_PACKAGES);
20645            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20646                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20647            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20648                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20649            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20650                dumpState.setDump(DumpState.DUMP_MESSAGES);
20651            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20652                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20653            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20654                    || "intent-filter-verifiers".equals(cmd)) {
20655                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20656            } else if ("version".equals(cmd)) {
20657                dumpState.setDump(DumpState.DUMP_VERSION);
20658            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20659                dumpState.setDump(DumpState.DUMP_KEYSETS);
20660            } else if ("installs".equals(cmd)) {
20661                dumpState.setDump(DumpState.DUMP_INSTALLS);
20662            } else if ("frozen".equals(cmd)) {
20663                dumpState.setDump(DumpState.DUMP_FROZEN);
20664            } else if ("volumes".equals(cmd)) {
20665                dumpState.setDump(DumpState.DUMP_VOLUMES);
20666            } else if ("dexopt".equals(cmd)) {
20667                dumpState.setDump(DumpState.DUMP_DEXOPT);
20668            } else if ("compiler-stats".equals(cmd)) {
20669                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20670            } else if ("changes".equals(cmd)) {
20671                dumpState.setDump(DumpState.DUMP_CHANGES);
20672            } else if ("write".equals(cmd)) {
20673                synchronized (mPackages) {
20674                    mSettings.writeLPr();
20675                    pw.println("Settings written.");
20676                    return;
20677                }
20678            }
20679        }
20680
20681        if (checkin) {
20682            pw.println("vers,1");
20683        }
20684
20685        // reader
20686        synchronized (mPackages) {
20687            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20688                if (!checkin) {
20689                    if (dumpState.onTitlePrinted())
20690                        pw.println();
20691                    pw.println("Database versions:");
20692                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20693                }
20694            }
20695
20696            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20697                if (!checkin) {
20698                    if (dumpState.onTitlePrinted())
20699                        pw.println();
20700                    pw.println("Verifiers:");
20701                    pw.print("  Required: ");
20702                    pw.print(mRequiredVerifierPackage);
20703                    pw.print(" (uid=");
20704                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20705                            UserHandle.USER_SYSTEM));
20706                    pw.println(")");
20707                } else if (mRequiredVerifierPackage != null) {
20708                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20709                    pw.print(",");
20710                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20711                            UserHandle.USER_SYSTEM));
20712                }
20713            }
20714
20715            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20716                    packageName == null) {
20717                if (mIntentFilterVerifierComponent != null) {
20718                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20719                    if (!checkin) {
20720                        if (dumpState.onTitlePrinted())
20721                            pw.println();
20722                        pw.println("Intent Filter Verifier:");
20723                        pw.print("  Using: ");
20724                        pw.print(verifierPackageName);
20725                        pw.print(" (uid=");
20726                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20727                                UserHandle.USER_SYSTEM));
20728                        pw.println(")");
20729                    } else if (verifierPackageName != null) {
20730                        pw.print("ifv,"); pw.print(verifierPackageName);
20731                        pw.print(",");
20732                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20733                                UserHandle.USER_SYSTEM));
20734                    }
20735                } else {
20736                    pw.println();
20737                    pw.println("No Intent Filter Verifier available!");
20738                }
20739            }
20740
20741            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20742                boolean printedHeader = false;
20743                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20744                while (it.hasNext()) {
20745                    String libName = it.next();
20746                    LongSparseArray<SharedLibraryEntry> versionedLib
20747                            = mSharedLibraries.get(libName);
20748                    if (versionedLib == null) {
20749                        continue;
20750                    }
20751                    final int versionCount = versionedLib.size();
20752                    for (int i = 0; i < versionCount; i++) {
20753                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20754                        if (!checkin) {
20755                            if (!printedHeader) {
20756                                if (dumpState.onTitlePrinted())
20757                                    pw.println();
20758                                pw.println("Libraries:");
20759                                printedHeader = true;
20760                            }
20761                            pw.print("  ");
20762                        } else {
20763                            pw.print("lib,");
20764                        }
20765                        pw.print(libEntry.info.getName());
20766                        if (libEntry.info.isStatic()) {
20767                            pw.print(" version=" + libEntry.info.getLongVersion());
20768                        }
20769                        if (!checkin) {
20770                            pw.print(" -> ");
20771                        }
20772                        if (libEntry.path != null) {
20773                            pw.print(" (jar) ");
20774                            pw.print(libEntry.path);
20775                        } else {
20776                            pw.print(" (apk) ");
20777                            pw.print(libEntry.apk);
20778                        }
20779                        pw.println();
20780                    }
20781                }
20782            }
20783
20784            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20785                if (dumpState.onTitlePrinted())
20786                    pw.println();
20787                if (!checkin) {
20788                    pw.println("Features:");
20789                }
20790
20791                synchronized (mAvailableFeatures) {
20792                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20793                        if (checkin) {
20794                            pw.print("feat,");
20795                            pw.print(feat.name);
20796                            pw.print(",");
20797                            pw.println(feat.version);
20798                        } else {
20799                            pw.print("  ");
20800                            pw.print(feat.name);
20801                            if (feat.version > 0) {
20802                                pw.print(" version=");
20803                                pw.print(feat.version);
20804                            }
20805                            pw.println();
20806                        }
20807                    }
20808                }
20809            }
20810
20811            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20812                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20813                        : "Activity Resolver Table:", "  ", packageName,
20814                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20815                    dumpState.setTitlePrinted(true);
20816                }
20817            }
20818            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20819                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20820                        : "Receiver Resolver Table:", "  ", packageName,
20821                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20822                    dumpState.setTitlePrinted(true);
20823                }
20824            }
20825            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20826                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20827                        : "Service Resolver Table:", "  ", packageName,
20828                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20829                    dumpState.setTitlePrinted(true);
20830                }
20831            }
20832            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20833                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20834                        : "Provider Resolver Table:", "  ", packageName,
20835                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20836                    dumpState.setTitlePrinted(true);
20837                }
20838            }
20839
20840            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20841                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20842                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20843                    int user = mSettings.mPreferredActivities.keyAt(i);
20844                    if (pir.dump(pw,
20845                            dumpState.getTitlePrinted()
20846                                ? "\nPreferred Activities User " + user + ":"
20847                                : "Preferred Activities User " + user + ":", "  ",
20848                            packageName, true, false)) {
20849                        dumpState.setTitlePrinted(true);
20850                    }
20851                }
20852            }
20853
20854            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20855                pw.flush();
20856                FileOutputStream fout = new FileOutputStream(fd);
20857                BufferedOutputStream str = new BufferedOutputStream(fout);
20858                XmlSerializer serializer = new FastXmlSerializer();
20859                try {
20860                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20861                    serializer.startDocument(null, true);
20862                    serializer.setFeature(
20863                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20864                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20865                    serializer.endDocument();
20866                    serializer.flush();
20867                } catch (IllegalArgumentException e) {
20868                    pw.println("Failed writing: " + e);
20869                } catch (IllegalStateException e) {
20870                    pw.println("Failed writing: " + e);
20871                } catch (IOException e) {
20872                    pw.println("Failed writing: " + e);
20873                }
20874            }
20875
20876            if (!checkin
20877                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20878                    && packageName == null) {
20879                pw.println();
20880                int count = mSettings.mPackages.size();
20881                if (count == 0) {
20882                    pw.println("No applications!");
20883                    pw.println();
20884                } else {
20885                    final String prefix = "  ";
20886                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20887                    if (allPackageSettings.size() == 0) {
20888                        pw.println("No domain preferred apps!");
20889                        pw.println();
20890                    } else {
20891                        pw.println("App verification status:");
20892                        pw.println();
20893                        count = 0;
20894                        for (PackageSetting ps : allPackageSettings) {
20895                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20896                            if (ivi == null || ivi.getPackageName() == null) continue;
20897                            pw.println(prefix + "Package: " + ivi.getPackageName());
20898                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20899                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20900                            pw.println();
20901                            count++;
20902                        }
20903                        if (count == 0) {
20904                            pw.println(prefix + "No app verification established.");
20905                            pw.println();
20906                        }
20907                        for (int userId : sUserManager.getUserIds()) {
20908                            pw.println("App linkages for user " + userId + ":");
20909                            pw.println();
20910                            count = 0;
20911                            for (PackageSetting ps : allPackageSettings) {
20912                                final long status = ps.getDomainVerificationStatusForUser(userId);
20913                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20914                                        && !DEBUG_DOMAIN_VERIFICATION) {
20915                                    continue;
20916                                }
20917                                pw.println(prefix + "Package: " + ps.name);
20918                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20919                                String statusStr = IntentFilterVerificationInfo.
20920                                        getStatusStringFromValue(status);
20921                                pw.println(prefix + "Status:  " + statusStr);
20922                                pw.println();
20923                                count++;
20924                            }
20925                            if (count == 0) {
20926                                pw.println(prefix + "No configured app linkages.");
20927                                pw.println();
20928                            }
20929                        }
20930                    }
20931                }
20932            }
20933
20934            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20935                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20936            }
20937
20938            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20939                boolean printedSomething = false;
20940                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20941                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20942                        continue;
20943                    }
20944                    if (!printedSomething) {
20945                        if (dumpState.onTitlePrinted())
20946                            pw.println();
20947                        pw.println("Registered ContentProviders:");
20948                        printedSomething = true;
20949                    }
20950                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20951                    pw.print("    "); pw.println(p.toString());
20952                }
20953                printedSomething = false;
20954                for (Map.Entry<String, PackageParser.Provider> entry :
20955                        mProvidersByAuthority.entrySet()) {
20956                    PackageParser.Provider p = entry.getValue();
20957                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20958                        continue;
20959                    }
20960                    if (!printedSomething) {
20961                        if (dumpState.onTitlePrinted())
20962                            pw.println();
20963                        pw.println("ContentProvider Authorities:");
20964                        printedSomething = true;
20965                    }
20966                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20967                    pw.print("    "); pw.println(p.toString());
20968                    if (p.info != null && p.info.applicationInfo != null) {
20969                        final String appInfo = p.info.applicationInfo.toString();
20970                        pw.print("      applicationInfo="); pw.println(appInfo);
20971                    }
20972                }
20973            }
20974
20975            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20976                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20977            }
20978
20979            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20980                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20981            }
20982
20983            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20984                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20985            }
20986
20987            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20988                if (dumpState.onTitlePrinted()) pw.println();
20989                pw.println("Package Changes:");
20990                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20991                final int K = mChangedPackages.size();
20992                for (int i = 0; i < K; i++) {
20993                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20994                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20995                    final int N = changes.size();
20996                    if (N == 0) {
20997                        pw.print("    "); pw.println("No packages changed");
20998                    } else {
20999                        for (int j = 0; j < N; j++) {
21000                            final String pkgName = changes.valueAt(j);
21001                            final int sequenceNumber = changes.keyAt(j);
21002                            pw.print("    ");
21003                            pw.print("seq=");
21004                            pw.print(sequenceNumber);
21005                            pw.print(", package=");
21006                            pw.println(pkgName);
21007                        }
21008                    }
21009                }
21010            }
21011
21012            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21013                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21014            }
21015
21016            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21017                // XXX should handle packageName != null by dumping only install data that
21018                // the given package is involved with.
21019                if (dumpState.onTitlePrinted()) pw.println();
21020
21021                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21022                ipw.println();
21023                ipw.println("Frozen packages:");
21024                ipw.increaseIndent();
21025                if (mFrozenPackages.size() == 0) {
21026                    ipw.println("(none)");
21027                } else {
21028                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21029                        ipw.println(mFrozenPackages.valueAt(i));
21030                    }
21031                }
21032                ipw.decreaseIndent();
21033            }
21034
21035            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21036                if (dumpState.onTitlePrinted()) pw.println();
21037
21038                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21039                ipw.println();
21040                ipw.println("Loaded volumes:");
21041                ipw.increaseIndent();
21042                if (mLoadedVolumes.size() == 0) {
21043                    ipw.println("(none)");
21044                } else {
21045                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21046                        ipw.println(mLoadedVolumes.valueAt(i));
21047                    }
21048                }
21049                ipw.decreaseIndent();
21050            }
21051
21052            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21053                if (dumpState.onTitlePrinted()) pw.println();
21054                dumpDexoptStateLPr(pw, packageName);
21055            }
21056
21057            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21058                if (dumpState.onTitlePrinted()) pw.println();
21059                dumpCompilerStatsLPr(pw, packageName);
21060            }
21061
21062            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21063                if (dumpState.onTitlePrinted()) pw.println();
21064                mSettings.dumpReadMessagesLPr(pw, dumpState);
21065
21066                pw.println();
21067                pw.println("Package warning messages:");
21068                dumpCriticalInfo(pw, null);
21069            }
21070
21071            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21072                dumpCriticalInfo(pw, "msg,");
21073            }
21074        }
21075
21076        // PackageInstaller should be called outside of mPackages lock
21077        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21078            // XXX should handle packageName != null by dumping only install data that
21079            // the given package is involved with.
21080            if (dumpState.onTitlePrinted()) pw.println();
21081            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21082        }
21083    }
21084
21085    private void dumpProto(FileDescriptor fd) {
21086        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21087
21088        synchronized (mPackages) {
21089            final long requiredVerifierPackageToken =
21090                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21091            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21092            proto.write(
21093                    PackageServiceDumpProto.PackageShortProto.UID,
21094                    getPackageUid(
21095                            mRequiredVerifierPackage,
21096                            MATCH_DEBUG_TRIAGED_MISSING,
21097                            UserHandle.USER_SYSTEM));
21098            proto.end(requiredVerifierPackageToken);
21099
21100            if (mIntentFilterVerifierComponent != null) {
21101                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21102                final long verifierPackageToken =
21103                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21104                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21105                proto.write(
21106                        PackageServiceDumpProto.PackageShortProto.UID,
21107                        getPackageUid(
21108                                verifierPackageName,
21109                                MATCH_DEBUG_TRIAGED_MISSING,
21110                                UserHandle.USER_SYSTEM));
21111                proto.end(verifierPackageToken);
21112            }
21113
21114            dumpSharedLibrariesProto(proto);
21115            dumpFeaturesProto(proto);
21116            mSettings.dumpPackagesProto(proto);
21117            mSettings.dumpSharedUsersProto(proto);
21118            dumpCriticalInfo(proto);
21119        }
21120        proto.flush();
21121    }
21122
21123    private void dumpFeaturesProto(ProtoOutputStream proto) {
21124        synchronized (mAvailableFeatures) {
21125            final int count = mAvailableFeatures.size();
21126            for (int i = 0; i < count; i++) {
21127                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21128            }
21129        }
21130    }
21131
21132    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21133        final int count = mSharedLibraries.size();
21134        for (int i = 0; i < count; i++) {
21135            final String libName = mSharedLibraries.keyAt(i);
21136            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21137            if (versionedLib == null) {
21138                continue;
21139            }
21140            final int versionCount = versionedLib.size();
21141            for (int j = 0; j < versionCount; j++) {
21142                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21143                final long sharedLibraryToken =
21144                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21145                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21146                final boolean isJar = (libEntry.path != null);
21147                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21148                if (isJar) {
21149                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21150                } else {
21151                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21152                }
21153                proto.end(sharedLibraryToken);
21154            }
21155        }
21156    }
21157
21158    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21159        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21160        ipw.println();
21161        ipw.println("Dexopt state:");
21162        ipw.increaseIndent();
21163        Collection<PackageParser.Package> packages = null;
21164        if (packageName != null) {
21165            PackageParser.Package targetPackage = mPackages.get(packageName);
21166            if (targetPackage != null) {
21167                packages = Collections.singletonList(targetPackage);
21168            } else {
21169                ipw.println("Unable to find package: " + packageName);
21170                return;
21171            }
21172        } else {
21173            packages = mPackages.values();
21174        }
21175
21176        for (PackageParser.Package pkg : packages) {
21177            ipw.println("[" + pkg.packageName + "]");
21178            ipw.increaseIndent();
21179            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21180                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21181            ipw.decreaseIndent();
21182        }
21183    }
21184
21185    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21186        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21187        ipw.println();
21188        ipw.println("Compiler stats:");
21189        ipw.increaseIndent();
21190        Collection<PackageParser.Package> packages = null;
21191        if (packageName != null) {
21192            PackageParser.Package targetPackage = mPackages.get(packageName);
21193            if (targetPackage != null) {
21194                packages = Collections.singletonList(targetPackage);
21195            } else {
21196                ipw.println("Unable to find package: " + packageName);
21197                return;
21198            }
21199        } else {
21200            packages = mPackages.values();
21201        }
21202
21203        for (PackageParser.Package pkg : packages) {
21204            ipw.println("[" + pkg.packageName + "]");
21205            ipw.increaseIndent();
21206
21207            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21208            if (stats == null) {
21209                ipw.println("(No recorded stats)");
21210            } else {
21211                stats.dump(ipw);
21212            }
21213            ipw.decreaseIndent();
21214        }
21215    }
21216
21217    private String dumpDomainString(String packageName) {
21218        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21219                .getList();
21220        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21221
21222        ArraySet<String> result = new ArraySet<>();
21223        if (iviList.size() > 0) {
21224            for (IntentFilterVerificationInfo ivi : iviList) {
21225                for (String host : ivi.getDomains()) {
21226                    result.add(host);
21227                }
21228            }
21229        }
21230        if (filters != null && filters.size() > 0) {
21231            for (IntentFilter filter : filters) {
21232                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21233                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21234                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21235                    result.addAll(filter.getHostsList());
21236                }
21237            }
21238        }
21239
21240        StringBuilder sb = new StringBuilder(result.size() * 16);
21241        for (String domain : result) {
21242            if (sb.length() > 0) sb.append(" ");
21243            sb.append(domain);
21244        }
21245        return sb.toString();
21246    }
21247
21248    // ------- apps on sdcard specific code -------
21249    static final boolean DEBUG_SD_INSTALL = false;
21250
21251    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21252
21253    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21254
21255    private boolean mMediaMounted = false;
21256
21257    static String getEncryptKey() {
21258        try {
21259            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21260                    SD_ENCRYPTION_KEYSTORE_NAME);
21261            if (sdEncKey == null) {
21262                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21263                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21264                if (sdEncKey == null) {
21265                    Slog.e(TAG, "Failed to create encryption keys");
21266                    return null;
21267                }
21268            }
21269            return sdEncKey;
21270        } catch (NoSuchAlgorithmException nsae) {
21271            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21272            return null;
21273        } catch (IOException ioe) {
21274            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21275            return null;
21276        }
21277    }
21278
21279    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21280            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21281        final int size = infos.size();
21282        final String[] packageNames = new String[size];
21283        final int[] packageUids = new int[size];
21284        for (int i = 0; i < size; i++) {
21285            final ApplicationInfo info = infos.get(i);
21286            packageNames[i] = info.packageName;
21287            packageUids[i] = info.uid;
21288        }
21289        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21290                finishedReceiver);
21291    }
21292
21293    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21294            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21295        sendResourcesChangedBroadcast(mediaStatus, replacing,
21296                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21297    }
21298
21299    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21300            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21301        int size = pkgList.length;
21302        if (size > 0) {
21303            // Send broadcasts here
21304            Bundle extras = new Bundle();
21305            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21306            if (uidArr != null) {
21307                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21308            }
21309            if (replacing) {
21310                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21311            }
21312            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21313                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21314            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21315        }
21316    }
21317
21318    private void loadPrivatePackages(final VolumeInfo vol) {
21319        mHandler.post(new Runnable() {
21320            @Override
21321            public void run() {
21322                loadPrivatePackagesInner(vol);
21323            }
21324        });
21325    }
21326
21327    private void loadPrivatePackagesInner(VolumeInfo vol) {
21328        final String volumeUuid = vol.fsUuid;
21329        if (TextUtils.isEmpty(volumeUuid)) {
21330            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21331            return;
21332        }
21333
21334        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21335        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21336        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21337
21338        final VersionInfo ver;
21339        final List<PackageSetting> packages;
21340        synchronized (mPackages) {
21341            ver = mSettings.findOrCreateVersion(volumeUuid);
21342            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21343        }
21344
21345        for (PackageSetting ps : packages) {
21346            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21347            synchronized (mInstallLock) {
21348                final PackageParser.Package pkg;
21349                try {
21350                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21351                    loaded.add(pkg.applicationInfo);
21352
21353                } catch (PackageManagerException e) {
21354                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21355                }
21356
21357                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21358                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21359                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21360                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21361                }
21362            }
21363        }
21364
21365        // Reconcile app data for all started/unlocked users
21366        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21367        final UserManager um = mContext.getSystemService(UserManager.class);
21368        UserManagerInternal umInternal = getUserManagerInternal();
21369        for (UserInfo user : um.getUsers()) {
21370            final int flags;
21371            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21372                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21373            } else if (umInternal.isUserRunning(user.id)) {
21374                flags = StorageManager.FLAG_STORAGE_DE;
21375            } else {
21376                continue;
21377            }
21378
21379            try {
21380                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21381                synchronized (mInstallLock) {
21382                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21383                }
21384            } catch (IllegalStateException e) {
21385                // Device was probably ejected, and we'll process that event momentarily
21386                Slog.w(TAG, "Failed to prepare storage: " + e);
21387            }
21388        }
21389
21390        synchronized (mPackages) {
21391            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21392            if (sdkUpdated) {
21393                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21394                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21395            }
21396            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21397                    mPermissionCallback);
21398
21399            // Yay, everything is now upgraded
21400            ver.forceCurrent();
21401
21402            mSettings.writeLPr();
21403        }
21404
21405        for (PackageFreezer freezer : freezers) {
21406            freezer.close();
21407        }
21408
21409        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21410        sendResourcesChangedBroadcast(true, false, loaded, null);
21411        mLoadedVolumes.add(vol.getId());
21412    }
21413
21414    private void unloadPrivatePackages(final VolumeInfo vol) {
21415        mHandler.post(new Runnable() {
21416            @Override
21417            public void run() {
21418                unloadPrivatePackagesInner(vol);
21419            }
21420        });
21421    }
21422
21423    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21424        final String volumeUuid = vol.fsUuid;
21425        if (TextUtils.isEmpty(volumeUuid)) {
21426            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21427            return;
21428        }
21429
21430        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21431        synchronized (mInstallLock) {
21432        synchronized (mPackages) {
21433            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21434            for (PackageSetting ps : packages) {
21435                if (ps.pkg == null) continue;
21436
21437                final ApplicationInfo info = ps.pkg.applicationInfo;
21438                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21439                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21440
21441                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21442                        "unloadPrivatePackagesInner")) {
21443                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21444                            false, null)) {
21445                        unloaded.add(info);
21446                    } else {
21447                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21448                    }
21449                }
21450
21451                // Try very hard to release any references to this package
21452                // so we don't risk the system server being killed due to
21453                // open FDs
21454                AttributeCache.instance().removePackage(ps.name);
21455            }
21456
21457            mSettings.writeLPr();
21458        }
21459        }
21460
21461        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21462        sendResourcesChangedBroadcast(false, false, unloaded, null);
21463        mLoadedVolumes.remove(vol.getId());
21464
21465        // Try very hard to release any references to this path so we don't risk
21466        // the system server being killed due to open FDs
21467        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21468
21469        for (int i = 0; i < 3; i++) {
21470            System.gc();
21471            System.runFinalization();
21472        }
21473    }
21474
21475    private void assertPackageKnown(String volumeUuid, String packageName)
21476            throws PackageManagerException {
21477        synchronized (mPackages) {
21478            // Normalize package name to handle renamed packages
21479            packageName = normalizePackageNameLPr(packageName);
21480
21481            final PackageSetting ps = mSettings.mPackages.get(packageName);
21482            if (ps == null) {
21483                throw new PackageManagerException("Package " + packageName + " is unknown");
21484            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21485                throw new PackageManagerException(
21486                        "Package " + packageName + " found on unknown volume " + volumeUuid
21487                                + "; expected volume " + ps.volumeUuid);
21488            }
21489        }
21490    }
21491
21492    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21493            throws PackageManagerException {
21494        synchronized (mPackages) {
21495            // Normalize package name to handle renamed packages
21496            packageName = normalizePackageNameLPr(packageName);
21497
21498            final PackageSetting ps = mSettings.mPackages.get(packageName);
21499            if (ps == null) {
21500                throw new PackageManagerException("Package " + packageName + " is unknown");
21501            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21502                throw new PackageManagerException(
21503                        "Package " + packageName + " found on unknown volume " + volumeUuid
21504                                + "; expected volume " + ps.volumeUuid);
21505            } else if (!ps.getInstalled(userId)) {
21506                throw new PackageManagerException(
21507                        "Package " + packageName + " not installed for user " + userId);
21508            }
21509        }
21510    }
21511
21512    private List<String> collectAbsoluteCodePaths() {
21513        synchronized (mPackages) {
21514            List<String> codePaths = new ArrayList<>();
21515            final int packageCount = mSettings.mPackages.size();
21516            for (int i = 0; i < packageCount; i++) {
21517                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21518                codePaths.add(ps.codePath.getAbsolutePath());
21519            }
21520            return codePaths;
21521        }
21522    }
21523
21524    /**
21525     * Examine all apps present on given mounted volume, and destroy apps that
21526     * aren't expected, either due to uninstallation or reinstallation on
21527     * another volume.
21528     */
21529    private void reconcileApps(String volumeUuid) {
21530        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21531        List<File> filesToDelete = null;
21532
21533        final File[] files = FileUtils.listFilesOrEmpty(
21534                Environment.getDataAppDirectory(volumeUuid));
21535        for (File file : files) {
21536            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21537                    && !PackageInstallerService.isStageName(file.getName());
21538            if (!isPackage) {
21539                // Ignore entries which are not packages
21540                continue;
21541            }
21542
21543            String absolutePath = file.getAbsolutePath();
21544
21545            boolean pathValid = false;
21546            final int absoluteCodePathCount = absoluteCodePaths.size();
21547            for (int i = 0; i < absoluteCodePathCount; i++) {
21548                String absoluteCodePath = absoluteCodePaths.get(i);
21549                if (absolutePath.startsWith(absoluteCodePath)) {
21550                    pathValid = true;
21551                    break;
21552                }
21553            }
21554
21555            if (!pathValid) {
21556                if (filesToDelete == null) {
21557                    filesToDelete = new ArrayList<>();
21558                }
21559                filesToDelete.add(file);
21560            }
21561        }
21562
21563        if (filesToDelete != null) {
21564            final int fileToDeleteCount = filesToDelete.size();
21565            for (int i = 0; i < fileToDeleteCount; i++) {
21566                File fileToDelete = filesToDelete.get(i);
21567                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21568                synchronized (mInstallLock) {
21569                    removeCodePathLI(fileToDelete);
21570                }
21571            }
21572        }
21573    }
21574
21575    /**
21576     * Reconcile all app data for the given user.
21577     * <p>
21578     * Verifies that directories exist and that ownership and labeling is
21579     * correct for all installed apps on all mounted volumes.
21580     */
21581    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21582        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21583        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21584            final String volumeUuid = vol.getFsUuid();
21585            synchronized (mInstallLock) {
21586                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21587            }
21588        }
21589    }
21590
21591    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21592            boolean migrateAppData) {
21593        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21594    }
21595
21596    /**
21597     * Reconcile all app data on given mounted volume.
21598     * <p>
21599     * Destroys app data that isn't expected, either due to uninstallation or
21600     * reinstallation on another volume.
21601     * <p>
21602     * Verifies that directories exist and that ownership and labeling is
21603     * correct for all installed apps.
21604     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21605     */
21606    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21607            boolean migrateAppData, boolean onlyCoreApps) {
21608        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21609                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21610        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21611
21612        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21613        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21614
21615        // First look for stale data that doesn't belong, and check if things
21616        // have changed since we did our last restorecon
21617        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21618            if (StorageManager.isFileEncryptedNativeOrEmulated()
21619                    && !StorageManager.isUserKeyUnlocked(userId)) {
21620                throw new RuntimeException(
21621                        "Yikes, someone asked us to reconcile CE storage while " + userId
21622                                + " was still locked; this would have caused massive data loss!");
21623            }
21624
21625            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21626            for (File file : files) {
21627                final String packageName = file.getName();
21628                try {
21629                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21630                } catch (PackageManagerException e) {
21631                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21632                    try {
21633                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21634                                StorageManager.FLAG_STORAGE_CE, 0);
21635                    } catch (InstallerException e2) {
21636                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21637                    }
21638                }
21639            }
21640        }
21641        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21642            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21643            for (File file : files) {
21644                final String packageName = file.getName();
21645                try {
21646                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21647                } catch (PackageManagerException e) {
21648                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21649                    try {
21650                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21651                                StorageManager.FLAG_STORAGE_DE, 0);
21652                    } catch (InstallerException e2) {
21653                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21654                    }
21655                }
21656            }
21657        }
21658
21659        // Ensure that data directories are ready to roll for all packages
21660        // installed for this volume and user
21661        final List<PackageSetting> packages;
21662        synchronized (mPackages) {
21663            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21664        }
21665        int preparedCount = 0;
21666        for (PackageSetting ps : packages) {
21667            final String packageName = ps.name;
21668            if (ps.pkg == null) {
21669                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21670                // TODO: might be due to legacy ASEC apps; we should circle back
21671                // and reconcile again once they're scanned
21672                continue;
21673            }
21674            // Skip non-core apps if requested
21675            if (onlyCoreApps && !ps.pkg.coreApp) {
21676                result.add(packageName);
21677                continue;
21678            }
21679
21680            if (ps.getInstalled(userId)) {
21681                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21682                preparedCount++;
21683            }
21684        }
21685
21686        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21687        return result;
21688    }
21689
21690    /**
21691     * Prepare app data for the given app just after it was installed or
21692     * upgraded. This method carefully only touches users that it's installed
21693     * for, and it forces a restorecon to handle any seinfo changes.
21694     * <p>
21695     * Verifies that directories exist and that ownership and labeling is
21696     * correct for all installed apps. If there is an ownership mismatch, it
21697     * will try recovering system apps by wiping data; third-party app data is
21698     * left intact.
21699     * <p>
21700     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21701     */
21702    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21703        final PackageSetting ps;
21704        synchronized (mPackages) {
21705            ps = mSettings.mPackages.get(pkg.packageName);
21706            mSettings.writeKernelMappingLPr(ps);
21707        }
21708
21709        final UserManager um = mContext.getSystemService(UserManager.class);
21710        UserManagerInternal umInternal = getUserManagerInternal();
21711        for (UserInfo user : um.getUsers()) {
21712            final int flags;
21713            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21714                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21715            } else if (umInternal.isUserRunning(user.id)) {
21716                flags = StorageManager.FLAG_STORAGE_DE;
21717            } else {
21718                continue;
21719            }
21720
21721            if (ps.getInstalled(user.id)) {
21722                // TODO: when user data is locked, mark that we're still dirty
21723                prepareAppDataLIF(pkg, user.id, flags);
21724            }
21725        }
21726    }
21727
21728    /**
21729     * Prepare app data for the given app.
21730     * <p>
21731     * Verifies that directories exist and that ownership and labeling is
21732     * correct for all installed apps. If there is an ownership mismatch, this
21733     * will try recovering system apps by wiping data; third-party app data is
21734     * left intact.
21735     */
21736    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21737        if (pkg == null) {
21738            Slog.wtf(TAG, "Package was null!", new Throwable());
21739            return;
21740        }
21741        prepareAppDataLeafLIF(pkg, userId, flags);
21742        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21743        for (int i = 0; i < childCount; i++) {
21744            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21745        }
21746    }
21747
21748    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21749            boolean maybeMigrateAppData) {
21750        prepareAppDataLIF(pkg, userId, flags);
21751
21752        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21753            // We may have just shuffled around app data directories, so
21754            // prepare them one more time
21755            prepareAppDataLIF(pkg, userId, flags);
21756        }
21757    }
21758
21759    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21760        if (DEBUG_APP_DATA) {
21761            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21762                    + Integer.toHexString(flags));
21763        }
21764
21765        final String volumeUuid = pkg.volumeUuid;
21766        final String packageName = pkg.packageName;
21767        final ApplicationInfo app = pkg.applicationInfo;
21768        final int appId = UserHandle.getAppId(app.uid);
21769
21770        Preconditions.checkNotNull(app.seInfo);
21771
21772        long ceDataInode = -1;
21773        try {
21774            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21775                    appId, app.seInfo, app.targetSdkVersion);
21776        } catch (InstallerException e) {
21777            if (app.isSystemApp()) {
21778                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21779                        + ", but trying to recover: " + e);
21780                destroyAppDataLeafLIF(pkg, userId, flags);
21781                try {
21782                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21783                            appId, app.seInfo, app.targetSdkVersion);
21784                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21785                } catch (InstallerException e2) {
21786                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21787                }
21788            } else {
21789                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21790            }
21791        }
21792
21793        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21794            // TODO: mark this structure as dirty so we persist it!
21795            synchronized (mPackages) {
21796                final PackageSetting ps = mSettings.mPackages.get(packageName);
21797                if (ps != null) {
21798                    ps.setCeDataInode(ceDataInode, userId);
21799                }
21800            }
21801        }
21802
21803        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21804    }
21805
21806    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21807        if (pkg == null) {
21808            Slog.wtf(TAG, "Package was null!", new Throwable());
21809            return;
21810        }
21811        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21812        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21813        for (int i = 0; i < childCount; i++) {
21814            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21815        }
21816    }
21817
21818    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21819        final String volumeUuid = pkg.volumeUuid;
21820        final String packageName = pkg.packageName;
21821        final ApplicationInfo app = pkg.applicationInfo;
21822
21823        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21824            // Create a native library symlink only if we have native libraries
21825            // and if the native libraries are 32 bit libraries. We do not provide
21826            // this symlink for 64 bit libraries.
21827            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21828                final String nativeLibPath = app.nativeLibraryDir;
21829                try {
21830                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21831                            nativeLibPath, userId);
21832                } catch (InstallerException e) {
21833                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21834                }
21835            }
21836        }
21837    }
21838
21839    /**
21840     * For system apps on non-FBE devices, this method migrates any existing
21841     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21842     * requested by the app.
21843     */
21844    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21845        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21846                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21847            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21848                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21849            try {
21850                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21851                        storageTarget);
21852            } catch (InstallerException e) {
21853                logCriticalInfo(Log.WARN,
21854                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21855            }
21856            return true;
21857        } else {
21858            return false;
21859        }
21860    }
21861
21862    public PackageFreezer freezePackage(String packageName, String killReason) {
21863        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21864    }
21865
21866    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21867        return new PackageFreezer(packageName, userId, killReason);
21868    }
21869
21870    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21871            String killReason) {
21872        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21873    }
21874
21875    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21876            String killReason) {
21877        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21878            return new PackageFreezer();
21879        } else {
21880            return freezePackage(packageName, userId, killReason);
21881        }
21882    }
21883
21884    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21885            String killReason) {
21886        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21887    }
21888
21889    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21890            String killReason) {
21891        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21892            return new PackageFreezer();
21893        } else {
21894            return freezePackage(packageName, userId, killReason);
21895        }
21896    }
21897
21898    /**
21899     * Class that freezes and kills the given package upon creation, and
21900     * unfreezes it upon closing. This is typically used when doing surgery on
21901     * app code/data to prevent the app from running while you're working.
21902     */
21903    private class PackageFreezer implements AutoCloseable {
21904        private final String mPackageName;
21905        private final PackageFreezer[] mChildren;
21906
21907        private final boolean mWeFroze;
21908
21909        private final AtomicBoolean mClosed = new AtomicBoolean();
21910        private final CloseGuard mCloseGuard = CloseGuard.get();
21911
21912        /**
21913         * Create and return a stub freezer that doesn't actually do anything,
21914         * typically used when someone requested
21915         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21916         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21917         */
21918        public PackageFreezer() {
21919            mPackageName = null;
21920            mChildren = null;
21921            mWeFroze = false;
21922            mCloseGuard.open("close");
21923        }
21924
21925        public PackageFreezer(String packageName, int userId, String killReason) {
21926            synchronized (mPackages) {
21927                mPackageName = packageName;
21928                mWeFroze = mFrozenPackages.add(mPackageName);
21929
21930                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21931                if (ps != null) {
21932                    killApplication(ps.name, ps.appId, userId, killReason);
21933                }
21934
21935                final PackageParser.Package p = mPackages.get(packageName);
21936                if (p != null && p.childPackages != null) {
21937                    final int N = p.childPackages.size();
21938                    mChildren = new PackageFreezer[N];
21939                    for (int i = 0; i < N; i++) {
21940                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21941                                userId, killReason);
21942                    }
21943                } else {
21944                    mChildren = null;
21945                }
21946            }
21947            mCloseGuard.open("close");
21948        }
21949
21950        @Override
21951        protected void finalize() throws Throwable {
21952            try {
21953                if (mCloseGuard != null) {
21954                    mCloseGuard.warnIfOpen();
21955                }
21956
21957                close();
21958            } finally {
21959                super.finalize();
21960            }
21961        }
21962
21963        @Override
21964        public void close() {
21965            mCloseGuard.close();
21966            if (mClosed.compareAndSet(false, true)) {
21967                synchronized (mPackages) {
21968                    if (mWeFroze) {
21969                        mFrozenPackages.remove(mPackageName);
21970                    }
21971
21972                    if (mChildren != null) {
21973                        for (PackageFreezer freezer : mChildren) {
21974                            freezer.close();
21975                        }
21976                    }
21977                }
21978            }
21979        }
21980    }
21981
21982    /**
21983     * Verify that given package is currently frozen.
21984     */
21985    private void checkPackageFrozen(String packageName) {
21986        synchronized (mPackages) {
21987            if (!mFrozenPackages.contains(packageName)) {
21988                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21989            }
21990        }
21991    }
21992
21993    @Override
21994    public int movePackage(final String packageName, final String volumeUuid) {
21995        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21996
21997        final int callingUid = Binder.getCallingUid();
21998        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21999        final int moveId = mNextMoveId.getAndIncrement();
22000        mHandler.post(new Runnable() {
22001            @Override
22002            public void run() {
22003                try {
22004                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22005                } catch (PackageManagerException e) {
22006                    Slog.w(TAG, "Failed to move " + packageName, e);
22007                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22008                }
22009            }
22010        });
22011        return moveId;
22012    }
22013
22014    private void movePackageInternal(final String packageName, final String volumeUuid,
22015            final int moveId, final int callingUid, UserHandle user)
22016                    throws PackageManagerException {
22017        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22018        final PackageManager pm = mContext.getPackageManager();
22019
22020        final boolean currentAsec;
22021        final String currentVolumeUuid;
22022        final File codeFile;
22023        final String installerPackageName;
22024        final String packageAbiOverride;
22025        final int appId;
22026        final String seinfo;
22027        final String label;
22028        final int targetSdkVersion;
22029        final PackageFreezer freezer;
22030        final int[] installedUserIds;
22031
22032        // reader
22033        synchronized (mPackages) {
22034            final PackageParser.Package pkg = mPackages.get(packageName);
22035            final PackageSetting ps = mSettings.mPackages.get(packageName);
22036            if (pkg == null
22037                    || ps == null
22038                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22039                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22040            }
22041            if (pkg.applicationInfo.isSystemApp()) {
22042                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22043                        "Cannot move system application");
22044            }
22045
22046            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22047            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22048                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22049            if (isInternalStorage && !allow3rdPartyOnInternal) {
22050                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22051                        "3rd party apps are not allowed on internal storage");
22052            }
22053
22054            if (pkg.applicationInfo.isExternalAsec()) {
22055                currentAsec = true;
22056                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22057            } else if (pkg.applicationInfo.isForwardLocked()) {
22058                currentAsec = true;
22059                currentVolumeUuid = "forward_locked";
22060            } else {
22061                currentAsec = false;
22062                currentVolumeUuid = ps.volumeUuid;
22063
22064                final File probe = new File(pkg.codePath);
22065                final File probeOat = new File(probe, "oat");
22066                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22067                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22068                            "Move only supported for modern cluster style installs");
22069                }
22070            }
22071
22072            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22073                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22074                        "Package already moved to " + volumeUuid);
22075            }
22076            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22077                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22078                        "Device admin cannot be moved");
22079            }
22080
22081            if (mFrozenPackages.contains(packageName)) {
22082                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22083                        "Failed to move already frozen package");
22084            }
22085
22086            codeFile = new File(pkg.codePath);
22087            installerPackageName = ps.installerPackageName;
22088            packageAbiOverride = ps.cpuAbiOverrideString;
22089            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22090            seinfo = pkg.applicationInfo.seInfo;
22091            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22092            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22093            freezer = freezePackage(packageName, "movePackageInternal");
22094            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22095        }
22096
22097        final Bundle extras = new Bundle();
22098        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22099        extras.putString(Intent.EXTRA_TITLE, label);
22100        mMoveCallbacks.notifyCreated(moveId, extras);
22101
22102        int installFlags;
22103        final boolean moveCompleteApp;
22104        final File measurePath;
22105
22106        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22107            installFlags = INSTALL_INTERNAL;
22108            moveCompleteApp = !currentAsec;
22109            measurePath = Environment.getDataAppDirectory(volumeUuid);
22110        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22111            installFlags = INSTALL_EXTERNAL;
22112            moveCompleteApp = false;
22113            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22114        } else {
22115            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22116            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22117                    || !volume.isMountedWritable()) {
22118                freezer.close();
22119                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22120                        "Move location not mounted private volume");
22121            }
22122
22123            Preconditions.checkState(!currentAsec);
22124
22125            installFlags = INSTALL_INTERNAL;
22126            moveCompleteApp = true;
22127            measurePath = Environment.getDataAppDirectory(volumeUuid);
22128        }
22129
22130        // If we're moving app data around, we need all the users unlocked
22131        if (moveCompleteApp) {
22132            for (int userId : installedUserIds) {
22133                if (StorageManager.isFileEncryptedNativeOrEmulated()
22134                        && !StorageManager.isUserKeyUnlocked(userId)) {
22135                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22136                            "User " + userId + " must be unlocked");
22137                }
22138            }
22139        }
22140
22141        final PackageStats stats = new PackageStats(null, -1);
22142        synchronized (mInstaller) {
22143            for (int userId : installedUserIds) {
22144                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22145                    freezer.close();
22146                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22147                            "Failed to measure package size");
22148                }
22149            }
22150        }
22151
22152        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22153                + stats.dataSize);
22154
22155        final long startFreeBytes = measurePath.getUsableSpace();
22156        final long sizeBytes;
22157        if (moveCompleteApp) {
22158            sizeBytes = stats.codeSize + stats.dataSize;
22159        } else {
22160            sizeBytes = stats.codeSize;
22161        }
22162
22163        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22164            freezer.close();
22165            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22166                    "Not enough free space to move");
22167        }
22168
22169        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22170
22171        final CountDownLatch installedLatch = new CountDownLatch(1);
22172        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22173            @Override
22174            public void onUserActionRequired(Intent intent) throws RemoteException {
22175                throw new IllegalStateException();
22176            }
22177
22178            @Override
22179            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22180                    Bundle extras) throws RemoteException {
22181                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22182                        + PackageManager.installStatusToString(returnCode, msg));
22183
22184                installedLatch.countDown();
22185                freezer.close();
22186
22187                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22188                switch (status) {
22189                    case PackageInstaller.STATUS_SUCCESS:
22190                        mMoveCallbacks.notifyStatusChanged(moveId,
22191                                PackageManager.MOVE_SUCCEEDED);
22192                        break;
22193                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22194                        mMoveCallbacks.notifyStatusChanged(moveId,
22195                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22196                        break;
22197                    default:
22198                        mMoveCallbacks.notifyStatusChanged(moveId,
22199                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22200                        break;
22201                }
22202            }
22203        };
22204
22205        final MoveInfo move;
22206        if (moveCompleteApp) {
22207            // Kick off a thread to report progress estimates
22208            new Thread() {
22209                @Override
22210                public void run() {
22211                    while (true) {
22212                        try {
22213                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22214                                break;
22215                            }
22216                        } catch (InterruptedException ignored) {
22217                        }
22218
22219                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22220                        final int progress = 10 + (int) MathUtils.constrain(
22221                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22222                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22223                    }
22224                }
22225            }.start();
22226
22227            final String dataAppName = codeFile.getName();
22228            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22229                    dataAppName, appId, seinfo, targetSdkVersion);
22230        } else {
22231            move = null;
22232        }
22233
22234        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22235
22236        final Message msg = mHandler.obtainMessage(INIT_COPY);
22237        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22238        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22239                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22240                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22241                PackageManager.INSTALL_REASON_UNKNOWN);
22242        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22243        msg.obj = params;
22244
22245        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22246                System.identityHashCode(msg.obj));
22247        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22248                System.identityHashCode(msg.obj));
22249
22250        mHandler.sendMessage(msg);
22251    }
22252
22253    @Override
22254    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22256
22257        final int realMoveId = mNextMoveId.getAndIncrement();
22258        final Bundle extras = new Bundle();
22259        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22260        mMoveCallbacks.notifyCreated(realMoveId, extras);
22261
22262        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22263            @Override
22264            public void onCreated(int moveId, Bundle extras) {
22265                // Ignored
22266            }
22267
22268            @Override
22269            public void onStatusChanged(int moveId, int status, long estMillis) {
22270                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22271            }
22272        };
22273
22274        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22275        storage.setPrimaryStorageUuid(volumeUuid, callback);
22276        return realMoveId;
22277    }
22278
22279    @Override
22280    public int getMoveStatus(int moveId) {
22281        mContext.enforceCallingOrSelfPermission(
22282                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22283        return mMoveCallbacks.mLastStatus.get(moveId);
22284    }
22285
22286    @Override
22287    public void registerMoveCallback(IPackageMoveObserver callback) {
22288        mContext.enforceCallingOrSelfPermission(
22289                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22290        mMoveCallbacks.register(callback);
22291    }
22292
22293    @Override
22294    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22295        mContext.enforceCallingOrSelfPermission(
22296                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22297        mMoveCallbacks.unregister(callback);
22298    }
22299
22300    @Override
22301    public boolean setInstallLocation(int loc) {
22302        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22303                null);
22304        if (getInstallLocation() == loc) {
22305            return true;
22306        }
22307        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22308                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22309            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22310                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22311            return true;
22312        }
22313        return false;
22314   }
22315
22316    @Override
22317    public int getInstallLocation() {
22318        // allow instant app access
22319        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22320                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22321                PackageHelper.APP_INSTALL_AUTO);
22322    }
22323
22324    /** Called by UserManagerService */
22325    void cleanUpUser(UserManagerService userManager, int userHandle) {
22326        synchronized (mPackages) {
22327            mDirtyUsers.remove(userHandle);
22328            mUserNeedsBadging.delete(userHandle);
22329            mSettings.removeUserLPw(userHandle);
22330            mPendingBroadcasts.remove(userHandle);
22331            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22332            removeUnusedPackagesLPw(userManager, userHandle);
22333        }
22334    }
22335
22336    /**
22337     * We're removing userHandle and would like to remove any downloaded packages
22338     * that are no longer in use by any other user.
22339     * @param userHandle the user being removed
22340     */
22341    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22342        final boolean DEBUG_CLEAN_APKS = false;
22343        int [] users = userManager.getUserIds();
22344        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22345        while (psit.hasNext()) {
22346            PackageSetting ps = psit.next();
22347            if (ps.pkg == null) {
22348                continue;
22349            }
22350            final String packageName = ps.pkg.packageName;
22351            // Skip over if system app
22352            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22353                continue;
22354            }
22355            if (DEBUG_CLEAN_APKS) {
22356                Slog.i(TAG, "Checking package " + packageName);
22357            }
22358            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22359            if (keep) {
22360                if (DEBUG_CLEAN_APKS) {
22361                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22362                }
22363            } else {
22364                for (int i = 0; i < users.length; i++) {
22365                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22366                        keep = true;
22367                        if (DEBUG_CLEAN_APKS) {
22368                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22369                                    + users[i]);
22370                        }
22371                        break;
22372                    }
22373                }
22374            }
22375            if (!keep) {
22376                if (DEBUG_CLEAN_APKS) {
22377                    Slog.i(TAG, "  Removing package " + packageName);
22378                }
22379                mHandler.post(new Runnable() {
22380                    public void run() {
22381                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22382                                userHandle, 0);
22383                    } //end run
22384                });
22385            }
22386        }
22387    }
22388
22389    /** Called by UserManagerService */
22390    void createNewUser(int userId, String[] disallowedPackages) {
22391        synchronized (mInstallLock) {
22392            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22393        }
22394        synchronized (mPackages) {
22395            scheduleWritePackageRestrictionsLocked(userId);
22396            scheduleWritePackageListLocked(userId);
22397            applyFactoryDefaultBrowserLPw(userId);
22398            primeDomainVerificationsLPw(userId);
22399        }
22400    }
22401
22402    void onNewUserCreated(final int userId) {
22403        synchronized(mPackages) {
22404            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22405            // If permission review for legacy apps is required, we represent
22406            // dagerous permissions for such apps as always granted runtime
22407            // permissions to keep per user flag state whether review is needed.
22408            // Hence, if a new user is added we have to propagate dangerous
22409            // permission grants for these legacy apps.
22410            if (mSettings.mPermissions.mPermissionReviewRequired) {
22411// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22412                mPermissionManager.updateAllPermissions(
22413                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22414                        mPermissionCallback);
22415            }
22416        }
22417    }
22418
22419    @Override
22420    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22421        mContext.enforceCallingOrSelfPermission(
22422                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22423                "Only package verification agents can read the verifier device identity");
22424
22425        synchronized (mPackages) {
22426            return mSettings.getVerifierDeviceIdentityLPw();
22427        }
22428    }
22429
22430    @Override
22431    public void setPermissionEnforced(String permission, boolean enforced) {
22432        // TODO: Now that we no longer change GID for storage, this should to away.
22433        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22434                "setPermissionEnforced");
22435        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22436            synchronized (mPackages) {
22437                if (mSettings.mReadExternalStorageEnforced == null
22438                        || mSettings.mReadExternalStorageEnforced != enforced) {
22439                    mSettings.mReadExternalStorageEnforced =
22440                            enforced ? Boolean.TRUE : Boolean.FALSE;
22441                    mSettings.writeLPr();
22442                }
22443            }
22444            // kill any non-foreground processes so we restart them and
22445            // grant/revoke the GID.
22446            final IActivityManager am = ActivityManager.getService();
22447            if (am != null) {
22448                final long token = Binder.clearCallingIdentity();
22449                try {
22450                    am.killProcessesBelowForeground("setPermissionEnforcement");
22451                } catch (RemoteException e) {
22452                } finally {
22453                    Binder.restoreCallingIdentity(token);
22454                }
22455            }
22456        } else {
22457            throw new IllegalArgumentException("No selective enforcement for " + permission);
22458        }
22459    }
22460
22461    @Override
22462    @Deprecated
22463    public boolean isPermissionEnforced(String permission) {
22464        // allow instant applications
22465        return true;
22466    }
22467
22468    @Override
22469    public boolean isStorageLow() {
22470        // allow instant applications
22471        final long token = Binder.clearCallingIdentity();
22472        try {
22473            final DeviceStorageMonitorInternal
22474                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22475            if (dsm != null) {
22476                return dsm.isMemoryLow();
22477            } else {
22478                return false;
22479            }
22480        } finally {
22481            Binder.restoreCallingIdentity(token);
22482        }
22483    }
22484
22485    @Override
22486    public IPackageInstaller getPackageInstaller() {
22487        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22488            return null;
22489        }
22490        return mInstallerService;
22491    }
22492
22493    @Override
22494    public IArtManager getArtManager() {
22495        return mArtManagerService;
22496    }
22497
22498    private boolean userNeedsBadging(int userId) {
22499        int index = mUserNeedsBadging.indexOfKey(userId);
22500        if (index < 0) {
22501            final UserInfo userInfo;
22502            final long token = Binder.clearCallingIdentity();
22503            try {
22504                userInfo = sUserManager.getUserInfo(userId);
22505            } finally {
22506                Binder.restoreCallingIdentity(token);
22507            }
22508            final boolean b;
22509            if (userInfo != null && userInfo.isManagedProfile()) {
22510                b = true;
22511            } else {
22512                b = false;
22513            }
22514            mUserNeedsBadging.put(userId, b);
22515            return b;
22516        }
22517        return mUserNeedsBadging.valueAt(index);
22518    }
22519
22520    @Override
22521    public KeySet getKeySetByAlias(String packageName, String alias) {
22522        if (packageName == null || alias == null) {
22523            return null;
22524        }
22525        synchronized(mPackages) {
22526            final PackageParser.Package pkg = mPackages.get(packageName);
22527            if (pkg == null) {
22528                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22529                throw new IllegalArgumentException("Unknown package: " + packageName);
22530            }
22531            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22532            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22533                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22534                throw new IllegalArgumentException("Unknown package: " + packageName);
22535            }
22536            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22537            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22538        }
22539    }
22540
22541    @Override
22542    public KeySet getSigningKeySet(String packageName) {
22543        if (packageName == null) {
22544            return null;
22545        }
22546        synchronized(mPackages) {
22547            final int callingUid = Binder.getCallingUid();
22548            final int callingUserId = UserHandle.getUserId(callingUid);
22549            final PackageParser.Package pkg = mPackages.get(packageName);
22550            if (pkg == null) {
22551                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22552                throw new IllegalArgumentException("Unknown package: " + packageName);
22553            }
22554            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22555            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22556                // filter and pretend the package doesn't exist
22557                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22558                        + ", uid:" + callingUid);
22559                throw new IllegalArgumentException("Unknown package: " + packageName);
22560            }
22561            if (pkg.applicationInfo.uid != callingUid
22562                    && Process.SYSTEM_UID != callingUid) {
22563                throw new SecurityException("May not access signing KeySet of other apps.");
22564            }
22565            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22566            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22567        }
22568    }
22569
22570    @Override
22571    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22572        final int callingUid = Binder.getCallingUid();
22573        if (getInstantAppPackageName(callingUid) != null) {
22574            return false;
22575        }
22576        if (packageName == null || ks == null) {
22577            return false;
22578        }
22579        synchronized(mPackages) {
22580            final PackageParser.Package pkg = mPackages.get(packageName);
22581            if (pkg == null
22582                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22583                            UserHandle.getUserId(callingUid))) {
22584                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22585                throw new IllegalArgumentException("Unknown package: " + packageName);
22586            }
22587            IBinder ksh = ks.getToken();
22588            if (ksh instanceof KeySetHandle) {
22589                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22590                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22591            }
22592            return false;
22593        }
22594    }
22595
22596    @Override
22597    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22598        final int callingUid = Binder.getCallingUid();
22599        if (getInstantAppPackageName(callingUid) != null) {
22600            return false;
22601        }
22602        if (packageName == null || ks == null) {
22603            return false;
22604        }
22605        synchronized(mPackages) {
22606            final PackageParser.Package pkg = mPackages.get(packageName);
22607            if (pkg == null
22608                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22609                            UserHandle.getUserId(callingUid))) {
22610                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22611                throw new IllegalArgumentException("Unknown package: " + packageName);
22612            }
22613            IBinder ksh = ks.getToken();
22614            if (ksh instanceof KeySetHandle) {
22615                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22616                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22617            }
22618            return false;
22619        }
22620    }
22621
22622    private void deletePackageIfUnusedLPr(final String packageName) {
22623        PackageSetting ps = mSettings.mPackages.get(packageName);
22624        if (ps == null) {
22625            return;
22626        }
22627        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22628            // TODO Implement atomic delete if package is unused
22629            // It is currently possible that the package will be deleted even if it is installed
22630            // after this method returns.
22631            mHandler.post(new Runnable() {
22632                public void run() {
22633                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22634                            0, PackageManager.DELETE_ALL_USERS);
22635                }
22636            });
22637        }
22638    }
22639
22640    /**
22641     * Check and throw if the given before/after packages would be considered a
22642     * downgrade.
22643     */
22644    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22645            throws PackageManagerException {
22646        if (after.getLongVersionCode() < before.getLongVersionCode()) {
22647            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22648                    "Update version code " + after.versionCode + " is older than current "
22649                    + before.getLongVersionCode());
22650        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
22651            if (after.baseRevisionCode < before.baseRevisionCode) {
22652                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22653                        "Update base revision code " + after.baseRevisionCode
22654                        + " is older than current " + before.baseRevisionCode);
22655            }
22656
22657            if (!ArrayUtils.isEmpty(after.splitNames)) {
22658                for (int i = 0; i < after.splitNames.length; i++) {
22659                    final String splitName = after.splitNames[i];
22660                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22661                    if (j != -1) {
22662                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22663                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22664                                    "Update split " + splitName + " revision code "
22665                                    + after.splitRevisionCodes[i] + " is older than current "
22666                                    + before.splitRevisionCodes[j]);
22667                        }
22668                    }
22669                }
22670            }
22671        }
22672    }
22673
22674    private static class MoveCallbacks extends Handler {
22675        private static final int MSG_CREATED = 1;
22676        private static final int MSG_STATUS_CHANGED = 2;
22677
22678        private final RemoteCallbackList<IPackageMoveObserver>
22679                mCallbacks = new RemoteCallbackList<>();
22680
22681        private final SparseIntArray mLastStatus = new SparseIntArray();
22682
22683        public MoveCallbacks(Looper looper) {
22684            super(looper);
22685        }
22686
22687        public void register(IPackageMoveObserver callback) {
22688            mCallbacks.register(callback);
22689        }
22690
22691        public void unregister(IPackageMoveObserver callback) {
22692            mCallbacks.unregister(callback);
22693        }
22694
22695        @Override
22696        public void handleMessage(Message msg) {
22697            final SomeArgs args = (SomeArgs) msg.obj;
22698            final int n = mCallbacks.beginBroadcast();
22699            for (int i = 0; i < n; i++) {
22700                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22701                try {
22702                    invokeCallback(callback, msg.what, args);
22703                } catch (RemoteException ignored) {
22704                }
22705            }
22706            mCallbacks.finishBroadcast();
22707            args.recycle();
22708        }
22709
22710        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22711                throws RemoteException {
22712            switch (what) {
22713                case MSG_CREATED: {
22714                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22715                    break;
22716                }
22717                case MSG_STATUS_CHANGED: {
22718                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22719                    break;
22720                }
22721            }
22722        }
22723
22724        private void notifyCreated(int moveId, Bundle extras) {
22725            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22726
22727            final SomeArgs args = SomeArgs.obtain();
22728            args.argi1 = moveId;
22729            args.arg2 = extras;
22730            obtainMessage(MSG_CREATED, args).sendToTarget();
22731        }
22732
22733        private void notifyStatusChanged(int moveId, int status) {
22734            notifyStatusChanged(moveId, status, -1);
22735        }
22736
22737        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22738            Slog.v(TAG, "Move " + moveId + " status " + status);
22739
22740            final SomeArgs args = SomeArgs.obtain();
22741            args.argi1 = moveId;
22742            args.argi2 = status;
22743            args.arg3 = estMillis;
22744            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22745
22746            synchronized (mLastStatus) {
22747                mLastStatus.put(moveId, status);
22748            }
22749        }
22750    }
22751
22752    private final static class OnPermissionChangeListeners extends Handler {
22753        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22754
22755        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22756                new RemoteCallbackList<>();
22757
22758        public OnPermissionChangeListeners(Looper looper) {
22759            super(looper);
22760        }
22761
22762        @Override
22763        public void handleMessage(Message msg) {
22764            switch (msg.what) {
22765                case MSG_ON_PERMISSIONS_CHANGED: {
22766                    final int uid = msg.arg1;
22767                    handleOnPermissionsChanged(uid);
22768                } break;
22769            }
22770        }
22771
22772        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22773            mPermissionListeners.register(listener);
22774
22775        }
22776
22777        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22778            mPermissionListeners.unregister(listener);
22779        }
22780
22781        public void onPermissionsChanged(int uid) {
22782            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22783                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22784            }
22785        }
22786
22787        private void handleOnPermissionsChanged(int uid) {
22788            final int count = mPermissionListeners.beginBroadcast();
22789            try {
22790                for (int i = 0; i < count; i++) {
22791                    IOnPermissionsChangeListener callback = mPermissionListeners
22792                            .getBroadcastItem(i);
22793                    try {
22794                        callback.onPermissionsChanged(uid);
22795                    } catch (RemoteException e) {
22796                        Log.e(TAG, "Permission listener is dead", e);
22797                    }
22798                }
22799            } finally {
22800                mPermissionListeners.finishBroadcast();
22801            }
22802        }
22803    }
22804
22805    private class PackageManagerNative extends IPackageManagerNative.Stub {
22806        @Override
22807        public String[] getNamesForUids(int[] uids) throws RemoteException {
22808            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22809            // massage results so they can be parsed by the native binder
22810            for (int i = results.length - 1; i >= 0; --i) {
22811                if (results[i] == null) {
22812                    results[i] = "";
22813                }
22814            }
22815            return results;
22816        }
22817
22818        // NB: this differentiates between preloads and sideloads
22819        @Override
22820        public String getInstallerForPackage(String packageName) throws RemoteException {
22821            final String installerName = getInstallerPackageName(packageName);
22822            if (!TextUtils.isEmpty(installerName)) {
22823                return installerName;
22824            }
22825            // differentiate between preload and sideload
22826            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22827            ApplicationInfo appInfo = getApplicationInfo(packageName,
22828                                    /*flags*/ 0,
22829                                    /*userId*/ callingUser);
22830            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22831                return "preload";
22832            }
22833            return "";
22834        }
22835
22836        @Override
22837        public long getVersionCodeForPackage(String packageName) throws RemoteException {
22838            try {
22839                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22840                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22841                if (pInfo != null) {
22842                    return pInfo.getLongVersionCode();
22843                }
22844            } catch (Exception e) {
22845            }
22846            return 0;
22847        }
22848    }
22849
22850    private class PackageManagerInternalImpl extends PackageManagerInternal {
22851        @Override
22852        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22853                int flagValues, int userId) {
22854            PackageManagerService.this.updatePermissionFlags(
22855                    permName, packageName, flagMask, flagValues, userId);
22856        }
22857
22858        @Override
22859        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22860            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22861        }
22862
22863        @Override
22864        public boolean isInstantApp(String packageName, int userId) {
22865            return PackageManagerService.this.isInstantApp(packageName, userId);
22866        }
22867
22868        @Override
22869        public String getInstantAppPackageName(int uid) {
22870            return PackageManagerService.this.getInstantAppPackageName(uid);
22871        }
22872
22873        @Override
22874        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22875            synchronized (mPackages) {
22876                return PackageManagerService.this.filterAppAccessLPr(
22877                        (PackageSetting) pkg.mExtras, callingUid, userId);
22878            }
22879        }
22880
22881        @Override
22882        public PackageParser.Package getPackage(String packageName) {
22883            synchronized (mPackages) {
22884                packageName = resolveInternalPackageNameLPr(
22885                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22886                return mPackages.get(packageName);
22887            }
22888        }
22889
22890        @Override
22891        public PackageParser.Package getDisabledPackage(String packageName) {
22892            synchronized (mPackages) {
22893                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22894                return (ps != null) ? ps.pkg : null;
22895            }
22896        }
22897
22898        @Override
22899        public String getKnownPackageName(int knownPackage, int userId) {
22900            switch(knownPackage) {
22901                case PackageManagerInternal.PACKAGE_BROWSER:
22902                    return getDefaultBrowserPackageName(userId);
22903                case PackageManagerInternal.PACKAGE_INSTALLER:
22904                    return mRequiredInstallerPackage;
22905                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22906                    return mSetupWizardPackage;
22907                case PackageManagerInternal.PACKAGE_SYSTEM:
22908                    return "android";
22909                case PackageManagerInternal.PACKAGE_VERIFIER:
22910                    return mRequiredVerifierPackage;
22911            }
22912            return null;
22913        }
22914
22915        @Override
22916        public boolean isResolveActivityComponent(ComponentInfo component) {
22917            return mResolveActivity.packageName.equals(component.packageName)
22918                    && mResolveActivity.name.equals(component.name);
22919        }
22920
22921        @Override
22922        public void setLocationPackagesProvider(PackagesProvider provider) {
22923            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22924        }
22925
22926        @Override
22927        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22928            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22929        }
22930
22931        @Override
22932        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22933            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22934        }
22935
22936        @Override
22937        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22938            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22939        }
22940
22941        @Override
22942        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22943            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22944        }
22945
22946        @Override
22947        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22948            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22949        }
22950
22951        @Override
22952        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22953            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22954        }
22955
22956        @Override
22957        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22958            synchronized (mPackages) {
22959                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22960            }
22961            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22962        }
22963
22964        @Override
22965        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22966            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22967                    packageName, userId);
22968        }
22969
22970        @Override
22971        public void setKeepUninstalledPackages(final List<String> packageList) {
22972            Preconditions.checkNotNull(packageList);
22973            List<String> removedFromList = null;
22974            synchronized (mPackages) {
22975                if (mKeepUninstalledPackages != null) {
22976                    final int packagesCount = mKeepUninstalledPackages.size();
22977                    for (int i = 0; i < packagesCount; i++) {
22978                        String oldPackage = mKeepUninstalledPackages.get(i);
22979                        if (packageList != null && packageList.contains(oldPackage)) {
22980                            continue;
22981                        }
22982                        if (removedFromList == null) {
22983                            removedFromList = new ArrayList<>();
22984                        }
22985                        removedFromList.add(oldPackage);
22986                    }
22987                }
22988                mKeepUninstalledPackages = new ArrayList<>(packageList);
22989                if (removedFromList != null) {
22990                    final int removedCount = removedFromList.size();
22991                    for (int i = 0; i < removedCount; i++) {
22992                        deletePackageIfUnusedLPr(removedFromList.get(i));
22993                    }
22994                }
22995            }
22996        }
22997
22998        @Override
22999        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23000            synchronized (mPackages) {
23001                return mPermissionManager.isPermissionsReviewRequired(
23002                        mPackages.get(packageName), userId);
23003            }
23004        }
23005
23006        @Override
23007        public PackageInfo getPackageInfo(
23008                String packageName, int flags, int filterCallingUid, int userId) {
23009            return PackageManagerService.this
23010                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23011                            flags, filterCallingUid, userId);
23012        }
23013
23014        @Override
23015        public int getPackageUid(String packageName, int flags, int userId) {
23016            return PackageManagerService.this
23017                    .getPackageUid(packageName, flags, userId);
23018        }
23019
23020        @Override
23021        public ApplicationInfo getApplicationInfo(
23022                String packageName, int flags, int filterCallingUid, int userId) {
23023            return PackageManagerService.this
23024                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23025        }
23026
23027        @Override
23028        public ActivityInfo getActivityInfo(
23029                ComponentName component, int flags, int filterCallingUid, int userId) {
23030            return PackageManagerService.this
23031                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23032        }
23033
23034        @Override
23035        public List<ResolveInfo> queryIntentActivities(
23036                Intent intent, int flags, int filterCallingUid, int userId) {
23037            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23038            return PackageManagerService.this
23039                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23040                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23041        }
23042
23043        @Override
23044        public List<ResolveInfo> queryIntentServices(
23045                Intent intent, int flags, int callingUid, int userId) {
23046            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23047            return PackageManagerService.this
23048                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23049                            false);
23050        }
23051
23052        @Override
23053        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23054                int userId) {
23055            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23056        }
23057
23058        @Override
23059        public void setDeviceAndProfileOwnerPackages(
23060                int deviceOwnerUserId, String deviceOwnerPackage,
23061                SparseArray<String> profileOwnerPackages) {
23062            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23063                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23064        }
23065
23066        @Override
23067        public boolean isPackageDataProtected(int userId, String packageName) {
23068            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23069        }
23070
23071        @Override
23072        public boolean isPackageEphemeral(int userId, String packageName) {
23073            synchronized (mPackages) {
23074                final PackageSetting ps = mSettings.mPackages.get(packageName);
23075                return ps != null ? ps.getInstantApp(userId) : false;
23076            }
23077        }
23078
23079        @Override
23080        public boolean wasPackageEverLaunched(String packageName, int userId) {
23081            synchronized (mPackages) {
23082                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23083            }
23084        }
23085
23086        @Override
23087        public void grantRuntimePermission(String packageName, String permName, int userId,
23088                boolean overridePolicy) {
23089            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23090                    permName, packageName, overridePolicy, getCallingUid(), userId,
23091                    mPermissionCallback);
23092        }
23093
23094        @Override
23095        public void revokeRuntimePermission(String packageName, String permName, int userId,
23096                boolean overridePolicy) {
23097            mPermissionManager.revokeRuntimePermission(
23098                    permName, packageName, overridePolicy, getCallingUid(), userId,
23099                    mPermissionCallback);
23100        }
23101
23102        @Override
23103        public String getNameForUid(int uid) {
23104            return PackageManagerService.this.getNameForUid(uid);
23105        }
23106
23107        @Override
23108        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23109                Intent origIntent, String resolvedType, String callingPackage,
23110                Bundle verificationBundle, int userId) {
23111            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23112                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23113                    userId);
23114        }
23115
23116        @Override
23117        public void grantEphemeralAccess(int userId, Intent intent,
23118                int targetAppId, int ephemeralAppId) {
23119            synchronized (mPackages) {
23120                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23121                        targetAppId, ephemeralAppId);
23122            }
23123        }
23124
23125        @Override
23126        public boolean isInstantAppInstallerComponent(ComponentName component) {
23127            synchronized (mPackages) {
23128                return mInstantAppInstallerActivity != null
23129                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23130            }
23131        }
23132
23133        @Override
23134        public void pruneInstantApps() {
23135            mInstantAppRegistry.pruneInstantApps();
23136        }
23137
23138        @Override
23139        public String getSetupWizardPackageName() {
23140            return mSetupWizardPackage;
23141        }
23142
23143        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23144            if (policy != null) {
23145                mExternalSourcesPolicy = policy;
23146            }
23147        }
23148
23149        @Override
23150        public boolean isPackagePersistent(String packageName) {
23151            synchronized (mPackages) {
23152                PackageParser.Package pkg = mPackages.get(packageName);
23153                return pkg != null
23154                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23155                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23156                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23157                        : false;
23158            }
23159        }
23160
23161        @Override
23162        public boolean isLegacySystemApp(Package pkg) {
23163            synchronized (mPackages) {
23164                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23165                return mPromoteSystemApps
23166                        && ps.isSystem()
23167                        && mExistingSystemPackages.contains(ps.name);
23168            }
23169        }
23170
23171        @Override
23172        public List<PackageInfo> getOverlayPackages(int userId) {
23173            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23174            synchronized (mPackages) {
23175                for (PackageParser.Package p : mPackages.values()) {
23176                    if (p.mOverlayTarget != null) {
23177                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23178                        if (pkg != null) {
23179                            overlayPackages.add(pkg);
23180                        }
23181                    }
23182                }
23183            }
23184            return overlayPackages;
23185        }
23186
23187        @Override
23188        public List<String> getTargetPackageNames(int userId) {
23189            List<String> targetPackages = new ArrayList<>();
23190            synchronized (mPackages) {
23191                for (PackageParser.Package p : mPackages.values()) {
23192                    if (p.mOverlayTarget == null) {
23193                        targetPackages.add(p.packageName);
23194                    }
23195                }
23196            }
23197            return targetPackages;
23198        }
23199
23200        @Override
23201        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23202                @Nullable List<String> overlayPackageNames) {
23203            synchronized (mPackages) {
23204                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23205                    Slog.e(TAG, "failed to find package " + targetPackageName);
23206                    return false;
23207                }
23208                ArrayList<String> overlayPaths = null;
23209                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23210                    final int N = overlayPackageNames.size();
23211                    overlayPaths = new ArrayList<>(N);
23212                    for (int i = 0; i < N; i++) {
23213                        final String packageName = overlayPackageNames.get(i);
23214                        final PackageParser.Package pkg = mPackages.get(packageName);
23215                        if (pkg == null) {
23216                            Slog.e(TAG, "failed to find package " + packageName);
23217                            return false;
23218                        }
23219                        overlayPaths.add(pkg.baseCodePath);
23220                    }
23221                }
23222
23223                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23224                ps.setOverlayPaths(overlayPaths, userId);
23225                return true;
23226            }
23227        }
23228
23229        @Override
23230        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23231                int flags, int userId, boolean resolveForStart) {
23232            return resolveIntentInternal(
23233                    intent, resolvedType, flags, userId, resolveForStart);
23234        }
23235
23236        @Override
23237        public ResolveInfo resolveService(Intent intent, String resolvedType,
23238                int flags, int userId, int callingUid) {
23239            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23240        }
23241
23242        @Override
23243        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23244            return PackageManagerService.this.resolveContentProviderInternal(
23245                    name, flags, userId);
23246        }
23247
23248        @Override
23249        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23250            synchronized (mPackages) {
23251                mIsolatedOwners.put(isolatedUid, ownerUid);
23252            }
23253        }
23254
23255        @Override
23256        public void removeIsolatedUid(int isolatedUid) {
23257            synchronized (mPackages) {
23258                mIsolatedOwners.delete(isolatedUid);
23259            }
23260        }
23261
23262        @Override
23263        public int getUidTargetSdkVersion(int uid) {
23264            synchronized (mPackages) {
23265                return getUidTargetSdkVersionLockedLPr(uid);
23266            }
23267        }
23268
23269        @Override
23270        public boolean canAccessInstantApps(int callingUid, int userId) {
23271            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23272        }
23273
23274        @Override
23275        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23276            synchronized (mPackages) {
23277                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23278            }
23279        }
23280
23281        @Override
23282        public void notifyPackageUse(String packageName, int reason) {
23283            synchronized (mPackages) {
23284                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23285            }
23286        }
23287    }
23288
23289    @Override
23290    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23291        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23292        synchronized (mPackages) {
23293            final long identity = Binder.clearCallingIdentity();
23294            try {
23295                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23296                        packageNames, userId);
23297            } finally {
23298                Binder.restoreCallingIdentity(identity);
23299            }
23300        }
23301    }
23302
23303    @Override
23304    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23305        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23306        synchronized (mPackages) {
23307            final long identity = Binder.clearCallingIdentity();
23308            try {
23309                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23310                        packageNames, userId);
23311            } finally {
23312                Binder.restoreCallingIdentity(identity);
23313            }
23314        }
23315    }
23316
23317    private static void enforceSystemOrPhoneCaller(String tag) {
23318        int callingUid = Binder.getCallingUid();
23319        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23320            throw new SecurityException(
23321                    "Cannot call " + tag + " from UID " + callingUid);
23322        }
23323    }
23324
23325    boolean isHistoricalPackageUsageAvailable() {
23326        return mPackageUsage.isHistoricalPackageUsageAvailable();
23327    }
23328
23329    /**
23330     * Return a <b>copy</b> of the collection of packages known to the package manager.
23331     * @return A copy of the values of mPackages.
23332     */
23333    Collection<PackageParser.Package> getPackages() {
23334        synchronized (mPackages) {
23335            return new ArrayList<>(mPackages.values());
23336        }
23337    }
23338
23339    /**
23340     * Logs process start information (including base APK hash) to the security log.
23341     * @hide
23342     */
23343    @Override
23344    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23345            String apkFile, int pid) {
23346        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23347            return;
23348        }
23349        if (!SecurityLog.isLoggingEnabled()) {
23350            return;
23351        }
23352        Bundle data = new Bundle();
23353        data.putLong("startTimestamp", System.currentTimeMillis());
23354        data.putString("processName", processName);
23355        data.putInt("uid", uid);
23356        data.putString("seinfo", seinfo);
23357        data.putString("apkFile", apkFile);
23358        data.putInt("pid", pid);
23359        Message msg = mProcessLoggingHandler.obtainMessage(
23360                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23361        msg.setData(data);
23362        mProcessLoggingHandler.sendMessage(msg);
23363    }
23364
23365    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23366        return mCompilerStats.getPackageStats(pkgName);
23367    }
23368
23369    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23370        return getOrCreateCompilerPackageStats(pkg.packageName);
23371    }
23372
23373    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23374        return mCompilerStats.getOrCreatePackageStats(pkgName);
23375    }
23376
23377    public void deleteCompilerPackageStats(String pkgName) {
23378        mCompilerStats.deletePackageStats(pkgName);
23379    }
23380
23381    @Override
23382    public int getInstallReason(String packageName, int userId) {
23383        final int callingUid = Binder.getCallingUid();
23384        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23385                true /* requireFullPermission */, false /* checkShell */,
23386                "get install reason");
23387        synchronized (mPackages) {
23388            final PackageSetting ps = mSettings.mPackages.get(packageName);
23389            if (filterAppAccessLPr(ps, callingUid, userId)) {
23390                return PackageManager.INSTALL_REASON_UNKNOWN;
23391            }
23392            if (ps != null) {
23393                return ps.getInstallReason(userId);
23394            }
23395        }
23396        return PackageManager.INSTALL_REASON_UNKNOWN;
23397    }
23398
23399    @Override
23400    public boolean canRequestPackageInstalls(String packageName, int userId) {
23401        return canRequestPackageInstallsInternal(packageName, 0, userId,
23402                true /* throwIfPermNotDeclared*/);
23403    }
23404
23405    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23406            boolean throwIfPermNotDeclared) {
23407        int callingUid = Binder.getCallingUid();
23408        int uid = getPackageUid(packageName, 0, userId);
23409        if (callingUid != uid && callingUid != Process.ROOT_UID
23410                && callingUid != Process.SYSTEM_UID) {
23411            throw new SecurityException(
23412                    "Caller uid " + callingUid + " does not own package " + packageName);
23413        }
23414        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23415        if (info == null) {
23416            return false;
23417        }
23418        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23419            return false;
23420        }
23421        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23422        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23423        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23424            if (throwIfPermNotDeclared) {
23425                throw new SecurityException("Need to declare " + appOpPermission
23426                        + " to call this api");
23427            } else {
23428                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23429                return false;
23430            }
23431        }
23432        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23433            return false;
23434        }
23435        if (mExternalSourcesPolicy != null) {
23436            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23437            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23438                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23439            }
23440        }
23441        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23442    }
23443
23444    @Override
23445    public ComponentName getInstantAppResolverSettingsComponent() {
23446        return mInstantAppResolverSettingsComponent;
23447    }
23448
23449    @Override
23450    public ComponentName getInstantAppInstallerComponent() {
23451        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23452            return null;
23453        }
23454        return mInstantAppInstallerActivity == null
23455                ? null : mInstantAppInstallerActivity.getComponentName();
23456    }
23457
23458    @Override
23459    public String getInstantAppAndroidId(String packageName, int userId) {
23460        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23461                "getInstantAppAndroidId");
23462        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23463                true /* requireFullPermission */, false /* checkShell */,
23464                "getInstantAppAndroidId");
23465        // Make sure the target is an Instant App.
23466        if (!isInstantApp(packageName, userId)) {
23467            return null;
23468        }
23469        synchronized (mPackages) {
23470            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23471        }
23472    }
23473
23474    boolean canHaveOatDir(String packageName) {
23475        synchronized (mPackages) {
23476            PackageParser.Package p = mPackages.get(packageName);
23477            if (p == null) {
23478                return false;
23479            }
23480            return p.canHaveOatDir();
23481        }
23482    }
23483
23484    private String getOatDir(PackageParser.Package pkg) {
23485        if (!pkg.canHaveOatDir()) {
23486            return null;
23487        }
23488        File codePath = new File(pkg.codePath);
23489        if (codePath.isDirectory()) {
23490            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23491        }
23492        return null;
23493    }
23494
23495    void deleteOatArtifactsOfPackage(String packageName) {
23496        final String[] instructionSets;
23497        final List<String> codePaths;
23498        final String oatDir;
23499        final PackageParser.Package pkg;
23500        synchronized (mPackages) {
23501            pkg = mPackages.get(packageName);
23502        }
23503        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23504        codePaths = pkg.getAllCodePaths();
23505        oatDir = getOatDir(pkg);
23506
23507        for (String codePath : codePaths) {
23508            for (String isa : instructionSets) {
23509                try {
23510                    mInstaller.deleteOdex(codePath, isa, oatDir);
23511                } catch (InstallerException e) {
23512                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23513                }
23514            }
23515        }
23516    }
23517
23518    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23519        Set<String> unusedPackages = new HashSet<>();
23520        long currentTimeInMillis = System.currentTimeMillis();
23521        synchronized (mPackages) {
23522            for (PackageParser.Package pkg : mPackages.values()) {
23523                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23524                if (ps == null) {
23525                    continue;
23526                }
23527                PackageDexUsage.PackageUseInfo packageUseInfo =
23528                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23529                if (PackageManagerServiceUtils
23530                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23531                                downgradeTimeThresholdMillis, packageUseInfo,
23532                                pkg.getLatestPackageUseTimeInMills(),
23533                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23534                    unusedPackages.add(pkg.packageName);
23535                }
23536            }
23537        }
23538        return unusedPackages;
23539    }
23540}
23541
23542interface PackageSender {
23543    /**
23544     * @param userIds User IDs where the action occurred on a full application
23545     * @param instantUserIds User IDs where the action occurred on an instant application
23546     */
23547    void sendPackageBroadcast(final String action, final String pkg,
23548        final Bundle extras, final int flags, final String targetPkg,
23549        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
23550    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23551        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
23552}
23553