PackageManagerService.java revision f35375b56c39006182d572791c80c4e79f6e24ee
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_NEWER_SDK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
57import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.AppOpsManager;
122import android.app.IActivityManager;
123import android.app.ResourcesManager;
124import android.app.admin.IDevicePolicyManager;
125import android.app.admin.SecurityLog;
126import android.app.backup.IBackupManager;
127import android.content.BroadcastReceiver;
128import android.content.ComponentName;
129import android.content.ContentResolver;
130import android.content.Context;
131import android.content.IIntentReceiver;
132import android.content.Intent;
133import android.content.IntentFilter;
134import android.content.IntentSender;
135import android.content.IntentSender.SendIntentException;
136import android.content.ServiceConnection;
137import android.content.pm.ActivityInfo;
138import android.content.pm.ApplicationInfo;
139import android.content.pm.AppsQueryHelper;
140import android.content.pm.AuxiliaryResolveInfo;
141import android.content.pm.ChangedPackages;
142import android.content.pm.ComponentInfo;
143import android.content.pm.FallbackCategoryProvider;
144import android.content.pm.FeatureInfo;
145import android.content.pm.IDexModuleRegisterCallback;
146import android.content.pm.IOnPermissionsChangeListener;
147import android.content.pm.IPackageDataObserver;
148import android.content.pm.IPackageDeleteObserver;
149import android.content.pm.IPackageDeleteObserver2;
150import android.content.pm.IPackageInstallObserver2;
151import android.content.pm.IPackageInstaller;
152import android.content.pm.IPackageManager;
153import android.content.pm.IPackageManagerNative;
154import android.content.pm.IPackageMoveObserver;
155import android.content.pm.IPackageStatsObserver;
156import android.content.pm.InstantAppInfo;
157import android.content.pm.InstantAppRequest;
158import android.content.pm.InstantAppResolveInfo;
159import android.content.pm.InstrumentationInfo;
160import android.content.pm.IntentFilterVerificationInfo;
161import android.content.pm.KeySet;
162import android.content.pm.PackageCleanItem;
163import android.content.pm.PackageInfo;
164import android.content.pm.PackageInfoLite;
165import android.content.pm.PackageInstaller;
166import android.content.pm.PackageManager;
167import android.content.pm.PackageManagerInternal;
168import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
169import android.content.pm.PackageManager.PackageInfoFlags;
170import android.content.pm.PackageParser;
171import android.content.pm.PackageParser.ActivityIntentInfo;
172import android.content.pm.PackageParser.Package;
173import android.content.pm.PackageParser.PackageLite;
174import android.content.pm.PackageParser.PackageParserException;
175import android.content.pm.PackageParser.ParseFlags;
176import android.content.pm.PackageParser.ServiceIntentInfo;
177import android.content.pm.PackageStats;
178import android.content.pm.PackageUserState;
179import android.content.pm.ParceledListSlice;
180import android.content.pm.PermissionGroupInfo;
181import android.content.pm.PermissionInfo;
182import android.content.pm.ProviderInfo;
183import android.content.pm.ResolveInfo;
184import android.content.pm.ServiceInfo;
185import android.content.pm.SharedLibraryInfo;
186import android.content.pm.Signature;
187import android.content.pm.UserInfo;
188import android.content.pm.VerifierDeviceIdentity;
189import android.content.pm.VerifierInfo;
190import android.content.pm.VersionedPackage;
191import android.content.pm.dex.IArtManager;
192import android.content.res.Resources;
193import android.database.ContentObserver;
194import android.graphics.Bitmap;
195import android.hardware.display.DisplayManager;
196import android.net.Uri;
197import android.os.Binder;
198import android.os.Build;
199import android.os.Bundle;
200import android.os.Debug;
201import android.os.Environment;
202import android.os.Environment.UserEnvironment;
203import android.os.FileUtils;
204import android.os.Handler;
205import android.os.IBinder;
206import android.os.Looper;
207import android.os.Message;
208import android.os.Parcel;
209import android.os.ParcelFileDescriptor;
210import android.os.PatternMatcher;
211import android.os.Process;
212import android.os.RemoteCallbackList;
213import android.os.RemoteException;
214import android.os.ResultReceiver;
215import android.os.SELinux;
216import android.os.ServiceManager;
217import android.os.ShellCallback;
218import android.os.SystemClock;
219import android.os.SystemProperties;
220import android.os.Trace;
221import android.os.UserHandle;
222import android.os.UserManager;
223import android.os.UserManagerInternal;
224import android.os.storage.IStorageManager;
225import android.os.storage.StorageEventListener;
226import android.os.storage.StorageManager;
227import android.os.storage.StorageManagerInternal;
228import android.os.storage.VolumeInfo;
229import android.os.storage.VolumeRecord;
230import android.provider.Settings.Global;
231import android.provider.Settings.Secure;
232import android.security.KeyStore;
233import android.security.SystemKeyStore;
234import android.service.pm.PackageServiceDumpProto;
235import android.system.ErrnoException;
236import android.system.Os;
237import android.text.TextUtils;
238import android.text.format.DateUtils;
239import android.util.ArrayMap;
240import android.util.ArraySet;
241import android.util.Base64;
242import android.util.DisplayMetrics;
243import android.util.EventLog;
244import android.util.ExceptionUtils;
245import android.util.Log;
246import android.util.LogPrinter;
247import android.util.LongSparseArray;
248import android.util.LongSparseLongArray;
249import android.util.MathUtils;
250import android.util.PackageUtils;
251import android.util.Pair;
252import android.util.PrintStreamPrinter;
253import android.util.Slog;
254import android.util.SparseArray;
255import android.util.SparseBooleanArray;
256import android.util.SparseIntArray;
257import android.util.TimingsTraceLog;
258import android.util.Xml;
259import android.util.jar.StrictJarFile;
260import android.util.proto.ProtoOutputStream;
261import android.view.Display;
262
263import com.android.internal.R;
264import com.android.internal.annotations.GuardedBy;
265import com.android.internal.app.IMediaContainerService;
266import com.android.internal.app.ResolverActivity;
267import com.android.internal.content.NativeLibraryHelper;
268import com.android.internal.content.PackageHelper;
269import com.android.internal.logging.MetricsLogger;
270import com.android.internal.os.IParcelFileDescriptorFactory;
271import com.android.internal.os.SomeArgs;
272import com.android.internal.os.Zygote;
273import com.android.internal.telephony.CarrierAppUtils;
274import com.android.internal.util.ArrayUtils;
275import com.android.internal.util.ConcurrentUtils;
276import com.android.internal.util.DumpUtils;
277import com.android.internal.util.FastXmlSerializer;
278import com.android.internal.util.IndentingPrintWriter;
279import com.android.internal.util.Preconditions;
280import com.android.internal.util.XmlUtils;
281import com.android.server.AttributeCache;
282import com.android.server.DeviceIdleController;
283import com.android.server.EventLogTags;
284import com.android.server.FgThread;
285import com.android.server.IntentResolver;
286import com.android.server.LocalServices;
287import com.android.server.LockGuard;
288import com.android.server.ServiceThread;
289import com.android.server.SystemConfig;
290import com.android.server.SystemServerInitThreadPool;
291import com.android.server.Watchdog;
292import com.android.server.net.NetworkPolicyManagerInternal;
293import com.android.server.pm.Installer.InstallerException;
294import com.android.server.pm.Settings.DatabaseVersion;
295import com.android.server.pm.Settings.VersionInfo;
296import com.android.server.pm.dex.ArtManagerService;
297import com.android.server.pm.dex.DexLogger;
298import com.android.server.pm.dex.DexManager;
299import com.android.server.pm.dex.DexoptOptions;
300import com.android.server.pm.dex.PackageDexUsage;
301import com.android.server.pm.permission.BasePermission;
302import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
303import com.android.server.pm.permission.PermissionManagerService;
304import com.android.server.pm.permission.PermissionManagerInternal;
305import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
306import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
307import com.android.server.pm.permission.PermissionsState;
308import com.android.server.pm.permission.PermissionsState.PermissionState;
309import com.android.server.storage.DeviceStorageMonitorInternal;
310
311import dalvik.system.CloseGuard;
312import dalvik.system.VMRuntime;
313
314import libcore.io.IoUtils;
315
316import org.xmlpull.v1.XmlPullParser;
317import org.xmlpull.v1.XmlPullParserException;
318import org.xmlpull.v1.XmlSerializer;
319
320import java.io.BufferedOutputStream;
321import java.io.ByteArrayInputStream;
322import java.io.ByteArrayOutputStream;
323import java.io.File;
324import java.io.FileDescriptor;
325import java.io.FileInputStream;
326import java.io.FileOutputStream;
327import java.io.FilenameFilter;
328import java.io.IOException;
329import java.io.PrintWriter;
330import java.lang.annotation.Retention;
331import java.lang.annotation.RetentionPolicy;
332import java.nio.charset.StandardCharsets;
333import java.security.DigestInputStream;
334import java.security.MessageDigest;
335import java.security.NoSuchAlgorithmException;
336import java.security.PublicKey;
337import java.security.SecureRandom;
338import java.security.cert.Certificate;
339import java.security.cert.CertificateException;
340import java.util.ArrayList;
341import java.util.Arrays;
342import java.util.Collection;
343import java.util.Collections;
344import java.util.Comparator;
345import java.util.HashMap;
346import java.util.HashSet;
347import java.util.Iterator;
348import java.util.LinkedHashSet;
349import java.util.List;
350import java.util.Map;
351import java.util.Objects;
352import java.util.Set;
353import java.util.concurrent.CountDownLatch;
354import java.util.concurrent.Future;
355import java.util.concurrent.TimeUnit;
356import java.util.concurrent.atomic.AtomicBoolean;
357import java.util.concurrent.atomic.AtomicInteger;
358
359/**
360 * Keep track of all those APKs everywhere.
361 * <p>
362 * Internally there are two important locks:
363 * <ul>
364 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
365 * and other related state. It is a fine-grained lock that should only be held
366 * momentarily, as it's one of the most contended locks in the system.
367 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
368 * operations typically involve heavy lifting of application data on disk. Since
369 * {@code installd} is single-threaded, and it's operations can often be slow,
370 * this lock should never be acquired while already holding {@link #mPackages}.
371 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
372 * holding {@link #mInstallLock}.
373 * </ul>
374 * Many internal methods rely on the caller to hold the appropriate locks, and
375 * this contract is expressed through method name suffixes:
376 * <ul>
377 * <li>fooLI(): the caller must hold {@link #mInstallLock}
378 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
379 * being modified must be frozen
380 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
381 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
382 * </ul>
383 * <p>
384 * Because this class is very central to the platform's security; please run all
385 * CTS and unit tests whenever making modifications:
386 *
387 * <pre>
388 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
389 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
390 * </pre>
391 */
392public class PackageManagerService extends IPackageManager.Stub
393        implements PackageSender {
394    static final String TAG = "PackageManager";
395    public static final boolean DEBUG_SETTINGS = false;
396    static final boolean DEBUG_PREFERRED = false;
397    static final boolean DEBUG_UPGRADE = false;
398    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
399    private static final boolean DEBUG_BACKUP = false;
400    public static final boolean DEBUG_INSTALL = false;
401    public static final boolean DEBUG_REMOVE = false;
402    private static final boolean DEBUG_BROADCASTS = false;
403    private static final boolean DEBUG_SHOW_INFO = false;
404    private static final boolean DEBUG_PACKAGE_INFO = false;
405    private static final boolean DEBUG_INTENT_MATCHING = false;
406    public static final boolean DEBUG_PACKAGE_SCANNING = false;
407    private static final boolean DEBUG_VERIFY = false;
408    private static final boolean DEBUG_FILTERS = false;
409    public static final boolean DEBUG_PERMISSIONS = false;
410    private static final boolean DEBUG_SHARED_LIBRARIES = false;
411    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
412
413    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
414    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
415    // user, but by default initialize to this.
416    public static final boolean DEBUG_DEXOPT = false;
417
418    private static final boolean DEBUG_ABI_SELECTION = false;
419    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
420    private static final boolean DEBUG_TRIAGED_MISSING = false;
421    private static final boolean DEBUG_APP_DATA = false;
422
423    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
424    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
425
426    private static final boolean HIDE_EPHEMERAL_APIS = false;
427
428    private static final boolean ENABLE_FREE_CACHE_V2 =
429            SystemProperties.getBoolean("fw.free_cache_v2", true);
430
431    private static final int RADIO_UID = Process.PHONE_UID;
432    private static final int LOG_UID = Process.LOG_UID;
433    private static final int NFC_UID = Process.NFC_UID;
434    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
435    private static final int SHELL_UID = Process.SHELL_UID;
436
437    // Suffix used during package installation when copying/moving
438    // package apks to install directory.
439    private static final String INSTALL_PACKAGE_SUFFIX = "-";
440
441    static final int SCAN_NO_DEX = 1<<0;
442    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
443    static final int SCAN_NEW_INSTALL = 1<<2;
444    static final int SCAN_UPDATE_TIME = 1<<3;
445    static final int SCAN_BOOTING = 1<<4;
446    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
447    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
448    static final int SCAN_REQUIRE_KNOWN = 1<<7;
449    static final int SCAN_MOVE = 1<<8;
450    static final int SCAN_INITIAL = 1<<9;
451    static final int SCAN_CHECK_ONLY = 1<<10;
452    static final int SCAN_DONT_KILL_APP = 1<<11;
453    static final int SCAN_IGNORE_FROZEN = 1<<12;
454    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
455    static final int SCAN_AS_INSTANT_APP = 1<<14;
456    static final int SCAN_AS_FULL_APP = 1<<15;
457    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
458    static final int SCAN_AS_SYSTEM = 1<<17;
459    static final int SCAN_AS_PRIVILEGED = 1<<18;
460    static final int SCAN_AS_OEM = 1<<19;
461    static final int SCAN_AS_VENDOR = 1<<20;
462
463    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
464            SCAN_NO_DEX,
465            SCAN_UPDATE_SIGNATURE,
466            SCAN_NEW_INSTALL,
467            SCAN_UPDATE_TIME,
468            SCAN_BOOTING,
469            SCAN_TRUSTED_OVERLAY,
470            SCAN_DELETE_DATA_ON_FAILURES,
471            SCAN_REQUIRE_KNOWN,
472            SCAN_MOVE,
473            SCAN_INITIAL,
474            SCAN_CHECK_ONLY,
475            SCAN_DONT_KILL_APP,
476            SCAN_IGNORE_FROZEN,
477            SCAN_FIRST_BOOT_OR_UPGRADE,
478            SCAN_AS_INSTANT_APP,
479            SCAN_AS_FULL_APP,
480            SCAN_AS_VIRTUAL_PRELOAD,
481    })
482    @Retention(RetentionPolicy.SOURCE)
483    public @interface ScanFlags {}
484
485    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
486    /** Extension of the compressed packages */
487    public final static String COMPRESSED_EXTENSION = ".gz";
488    /** Suffix of stub packages on the system partition */
489    public final static String STUB_SUFFIX = "-Stub";
490
491    private static final int[] EMPTY_INT_ARRAY = new int[0];
492
493    private static final int TYPE_UNKNOWN = 0;
494    private static final int TYPE_ACTIVITY = 1;
495    private static final int TYPE_RECEIVER = 2;
496    private static final int TYPE_SERVICE = 3;
497    private static final int TYPE_PROVIDER = 4;
498    @IntDef(prefix = { "TYPE_" }, value = {
499            TYPE_UNKNOWN,
500            TYPE_ACTIVITY,
501            TYPE_RECEIVER,
502            TYPE_SERVICE,
503            TYPE_PROVIDER,
504    })
505    @Retention(RetentionPolicy.SOURCE)
506    public @interface ComponentType {}
507
508    /**
509     * Timeout (in milliseconds) after which the watchdog should declare that
510     * our handler thread is wedged.  The usual default for such things is one
511     * minute but we sometimes do very lengthy I/O operations on this thread,
512     * such as installing multi-gigabyte applications, so ours needs to be longer.
513     */
514    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
515
516    /**
517     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
518     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
519     * settings entry if available, otherwise we use the hardcoded default.  If it's been
520     * more than this long since the last fstrim, we force one during the boot sequence.
521     *
522     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
523     * one gets run at the next available charging+idle time.  This final mandatory
524     * no-fstrim check kicks in only of the other scheduling criteria is never met.
525     */
526    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
527
528    /**
529     * Whether verification is enabled by default.
530     */
531    private static final boolean DEFAULT_VERIFY_ENABLE = true;
532
533    /**
534     * The default maximum time to wait for the verification agent to return in
535     * milliseconds.
536     */
537    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
538
539    /**
540     * The default response for package verification timeout.
541     *
542     * This can be either PackageManager.VERIFICATION_ALLOW or
543     * PackageManager.VERIFICATION_REJECT.
544     */
545    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
546
547    public static final String PLATFORM_PACKAGE_NAME = "android";
548
549    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
550
551    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
552            DEFAULT_CONTAINER_PACKAGE,
553            "com.android.defcontainer.DefaultContainerService");
554
555    private static final String KILL_APP_REASON_GIDS_CHANGED =
556            "permission grant or revoke changed gids";
557
558    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
559            "permissions revoked";
560
561    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
562
563    private static final String PACKAGE_SCHEME = "package";
564
565    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
566
567    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
568
569    /** Canonical intent used to identify what counts as a "web browser" app */
570    private static final Intent sBrowserIntent;
571    static {
572        sBrowserIntent = new Intent();
573        sBrowserIntent.setAction(Intent.ACTION_VIEW);
574        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
575        sBrowserIntent.setData(Uri.parse("http:"));
576    }
577
578    /**
579     * The set of all protected actions [i.e. those actions for which a high priority
580     * intent filter is disallowed].
581     */
582    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
583    static {
584        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
585        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
586        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
587        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
588    }
589
590    // Compilation reasons.
591    public static final int REASON_FIRST_BOOT = 0;
592    public static final int REASON_BOOT = 1;
593    public static final int REASON_INSTALL = 2;
594    public static final int REASON_BACKGROUND_DEXOPT = 3;
595    public static final int REASON_AB_OTA = 4;
596    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
597    public static final int REASON_SHARED = 6;
598
599    public static final int REASON_LAST = REASON_SHARED;
600
601    /**
602     * Version number for the package parser cache. Increment this whenever the format or
603     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
604     */
605    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
606
607    /**
608     * Whether the package parser cache is enabled.
609     */
610    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
611
612    /**
613     * Permissions required in order to receive instant application lifecycle broadcasts.
614     */
615    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
616            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
617
618    final ServiceThread mHandlerThread;
619
620    final PackageHandler mHandler;
621
622    private final ProcessLoggingHandler mProcessLoggingHandler;
623
624    /**
625     * Messages for {@link #mHandler} that need to wait for system ready before
626     * being dispatched.
627     */
628    private ArrayList<Message> mPostSystemReadyMessages;
629
630    final int mSdkVersion = Build.VERSION.SDK_INT;
631
632    final Context mContext;
633    final boolean mFactoryTest;
634    final boolean mOnlyCore;
635    final DisplayMetrics mMetrics;
636    final int mDefParseFlags;
637    final String[] mSeparateProcesses;
638    final boolean mIsUpgrade;
639    final boolean mIsPreNUpgrade;
640    final boolean mIsPreNMR1Upgrade;
641
642    // Have we told the Activity Manager to whitelist the default container service by uid yet?
643    @GuardedBy("mPackages")
644    boolean mDefaultContainerWhitelisted = false;
645
646    @GuardedBy("mPackages")
647    private boolean mDexOptDialogShown;
648
649    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
650    // LOCK HELD.  Can be called with mInstallLock held.
651    @GuardedBy("mInstallLock")
652    final Installer mInstaller;
653
654    /** Directory where installed applications are stored */
655    private static final File sAppInstallDir =
656            new File(Environment.getDataDirectory(), "app");
657    /** Directory where installed application's 32-bit native libraries are copied. */
658    private static final File sAppLib32InstallDir =
659            new File(Environment.getDataDirectory(), "app-lib");
660    /** Directory where code and non-resource assets of forward-locked applications are stored */
661    private static final File sDrmAppPrivateInstallDir =
662            new File(Environment.getDataDirectory(), "app-private");
663
664    // ----------------------------------------------------------------
665
666    // Lock for state used when installing and doing other long running
667    // operations.  Methods that must be called with this lock held have
668    // the suffix "LI".
669    final Object mInstallLock = new Object();
670
671    // ----------------------------------------------------------------
672
673    // Keys are String (package name), values are Package.  This also serves
674    // as the lock for the global state.  Methods that must be called with
675    // this lock held have the prefix "LP".
676    @GuardedBy("mPackages")
677    final ArrayMap<String, PackageParser.Package> mPackages =
678            new ArrayMap<String, PackageParser.Package>();
679
680    final ArrayMap<String, Set<String>> mKnownCodebase =
681            new ArrayMap<String, Set<String>>();
682
683    // Keys are isolated uids and values are the uid of the application
684    // that created the isolated proccess.
685    @GuardedBy("mPackages")
686    final SparseIntArray mIsolatedOwners = new SparseIntArray();
687
688    /**
689     * Tracks new system packages [received in an OTA] that we expect to
690     * find updated user-installed versions. Keys are package name, values
691     * are package location.
692     */
693    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
694    /**
695     * Tracks high priority intent filters for protected actions. During boot, certain
696     * filter actions are protected and should never be allowed to have a high priority
697     * intent filter for them. However, there is one, and only one exception -- the
698     * setup wizard. It must be able to define a high priority intent filter for these
699     * actions to ensure there are no escapes from the wizard. We need to delay processing
700     * of these during boot as we need to look at all of the system packages in order
701     * to know which component is the setup wizard.
702     */
703    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
704    /**
705     * Whether or not processing protected filters should be deferred.
706     */
707    private boolean mDeferProtectedFilters = true;
708
709    /**
710     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
711     */
712    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
713    /**
714     * Whether or not system app permissions should be promoted from install to runtime.
715     */
716    boolean mPromoteSystemApps;
717
718    @GuardedBy("mPackages")
719    final Settings mSettings;
720
721    /**
722     * Set of package names that are currently "frozen", which means active
723     * surgery is being done on the code/data for that package. The platform
724     * will refuse to launch frozen packages to avoid race conditions.
725     *
726     * @see PackageFreezer
727     */
728    @GuardedBy("mPackages")
729    final ArraySet<String> mFrozenPackages = new ArraySet<>();
730
731    final ProtectedPackages mProtectedPackages;
732
733    @GuardedBy("mLoadedVolumes")
734    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
735
736    boolean mFirstBoot;
737
738    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
739
740    @GuardedBy("mAvailableFeatures")
741    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
742
743    private final InstantAppRegistry mInstantAppRegistry;
744
745    @GuardedBy("mPackages")
746    int mChangedPackagesSequenceNumber;
747    /**
748     * List of changed [installed, removed or updated] packages.
749     * mapping from user id -> sequence number -> package name
750     */
751    @GuardedBy("mPackages")
752    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
753    /**
754     * The sequence number of the last change to a package.
755     * mapping from user id -> package name -> sequence number
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
759
760    class PackageParserCallback implements PackageParser.Callback {
761        @Override public final boolean hasFeature(String feature) {
762            return PackageManagerService.this.hasSystemFeature(feature, 0);
763        }
764
765        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
766                Collection<PackageParser.Package> allPackages, String targetPackageName) {
767            List<PackageParser.Package> overlayPackages = null;
768            for (PackageParser.Package p : allPackages) {
769                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
770                    if (overlayPackages == null) {
771                        overlayPackages = new ArrayList<PackageParser.Package>();
772                    }
773                    overlayPackages.add(p);
774                }
775            }
776            if (overlayPackages != null) {
777                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
778                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
779                        return p1.mOverlayPriority - p2.mOverlayPriority;
780                    }
781                };
782                Collections.sort(overlayPackages, cmp);
783            }
784            return overlayPackages;
785        }
786
787        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
788                String targetPackageName, String targetPath) {
789            if ("android".equals(targetPackageName)) {
790                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
791                // native AssetManager.
792                return null;
793            }
794            List<PackageParser.Package> overlayPackages =
795                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
796            if (overlayPackages == null || overlayPackages.isEmpty()) {
797                return null;
798            }
799            List<String> overlayPathList = null;
800            for (PackageParser.Package overlayPackage : overlayPackages) {
801                if (targetPath == null) {
802                    if (overlayPathList == null) {
803                        overlayPathList = new ArrayList<String>();
804                    }
805                    overlayPathList.add(overlayPackage.baseCodePath);
806                    continue;
807                }
808
809                try {
810                    // Creates idmaps for system to parse correctly the Android manifest of the
811                    // target package.
812                    //
813                    // OverlayManagerService will update each of them with a correct gid from its
814                    // target package app id.
815                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
816                            UserHandle.getSharedAppGid(
817                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                } catch (InstallerException e) {
823                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
824                            overlayPackage.baseCodePath);
825                }
826            }
827            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
828        }
829
830        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
831            synchronized (mPackages) {
832                return getStaticOverlayPathsLocked(
833                        mPackages.values(), targetPackageName, targetPath);
834            }
835        }
836
837        @Override public final String[] getOverlayApks(String targetPackageName) {
838            return getStaticOverlayPaths(targetPackageName, null);
839        }
840
841        @Override public final String[] getOverlayPaths(String targetPackageName,
842                String targetPath) {
843            return getStaticOverlayPaths(targetPackageName, targetPath);
844        }
845    }
846
847    class ParallelPackageParserCallback extends PackageParserCallback {
848        List<PackageParser.Package> mOverlayPackages = null;
849
850        void findStaticOverlayPackages() {
851            synchronized (mPackages) {
852                for (PackageParser.Package p : mPackages.values()) {
853                    if (p.mIsStaticOverlay) {
854                        if (mOverlayPackages == null) {
855                            mOverlayPackages = new ArrayList<PackageParser.Package>();
856                        }
857                        mOverlayPackages.add(p);
858                    }
859                }
860            }
861        }
862
863        @Override
864        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
865            // We can trust mOverlayPackages without holding mPackages because package uninstall
866            // can't happen while running parallel parsing.
867            // Moreover holding mPackages on each parsing thread causes dead-lock.
868            return mOverlayPackages == null ? null :
869                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
870        }
871    }
872
873    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
874    final ParallelPackageParserCallback mParallelPackageParserCallback =
875            new ParallelPackageParserCallback();
876
877    public static final class SharedLibraryEntry {
878        public final @Nullable String path;
879        public final @Nullable String apk;
880        public final @NonNull SharedLibraryInfo info;
881
882        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
883                String declaringPackageName, long declaringPackageVersionCode) {
884            path = _path;
885            apk = _apk;
886            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
887                    declaringPackageName, declaringPackageVersionCode), null);
888        }
889    }
890
891    // Currently known shared libraries.
892    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
893    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
894            new ArrayMap<>();
895
896    // All available activities, for your resolving pleasure.
897    final ActivityIntentResolver mActivities =
898            new ActivityIntentResolver();
899
900    // All available receivers, for your resolving pleasure.
901    final ActivityIntentResolver mReceivers =
902            new ActivityIntentResolver();
903
904    // All available services, for your resolving pleasure.
905    final ServiceIntentResolver mServices = new ServiceIntentResolver();
906
907    // All available providers, for your resolving pleasure.
908    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
909
910    // Mapping from provider base names (first directory in content URI codePath)
911    // to the provider information.
912    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
913            new ArrayMap<String, PackageParser.Provider>();
914
915    // Mapping from instrumentation class names to info about them.
916    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
917            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
918
919    // Packages whose data we have transfered into another package, thus
920    // should no longer exist.
921    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
922
923    // Broadcast actions that are only available to the system.
924    @GuardedBy("mProtectedBroadcasts")
925    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
926
927    /** List of packages waiting for verification. */
928    final SparseArray<PackageVerificationState> mPendingVerification
929            = new SparseArray<PackageVerificationState>();
930
931    final PackageInstallerService mInstallerService;
932
933    final ArtManagerService mArtManagerService;
934
935    private final PackageDexOptimizer mPackageDexOptimizer;
936    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
937    // is used by other apps).
938    private final DexManager mDexManager;
939
940    private AtomicInteger mNextMoveId = new AtomicInteger();
941    private final MoveCallbacks mMoveCallbacks;
942
943    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
944
945    // Cache of users who need badging.
946    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
947
948    /** Token for keys in mPendingVerification. */
949    private int mPendingVerificationToken = 0;
950
951    volatile boolean mSystemReady;
952    volatile boolean mSafeMode;
953    volatile boolean mHasSystemUidErrors;
954    private volatile boolean mEphemeralAppsDisabled;
955
956    ApplicationInfo mAndroidApplication;
957    final ActivityInfo mResolveActivity = new ActivityInfo();
958    final ResolveInfo mResolveInfo = new ResolveInfo();
959    ComponentName mResolveComponentName;
960    PackageParser.Package mPlatformPackage;
961    ComponentName mCustomResolverComponentName;
962
963    boolean mResolverReplaced = false;
964
965    private final @Nullable ComponentName mIntentFilterVerifierComponent;
966    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
967
968    private int mIntentFilterVerificationToken = 0;
969
970    /** The service connection to the ephemeral resolver */
971    final EphemeralResolverConnection mInstantAppResolverConnection;
972    /** Component used to show resolver settings for Instant Apps */
973    final ComponentName mInstantAppResolverSettingsComponent;
974
975    /** Activity used to install instant applications */
976    ActivityInfo mInstantAppInstallerActivity;
977    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
978
979    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
980            = new SparseArray<IntentFilterVerificationState>();
981
982    // TODO remove this and go through mPermissonManager directly
983    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
984    private final PermissionManagerInternal mPermissionManager;
985
986    // List of packages names to keep cached, even if they are uninstalled for all users
987    private List<String> mKeepUninstalledPackages;
988
989    private UserManagerInternal mUserManagerInternal;
990
991    private DeviceIdleController.LocalService mDeviceIdleController;
992
993    private File mCacheDir;
994
995    private Future<?> mPrepareAppDataFuture;
996
997    private static class IFVerificationParams {
998        PackageParser.Package pkg;
999        boolean replacing;
1000        int userId;
1001        int verifierUid;
1002
1003        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1004                int _userId, int _verifierUid) {
1005            pkg = _pkg;
1006            replacing = _replacing;
1007            userId = _userId;
1008            replacing = _replacing;
1009            verifierUid = _verifierUid;
1010        }
1011    }
1012
1013    private interface IntentFilterVerifier<T extends IntentFilter> {
1014        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1015                                               T filter, String packageName);
1016        void startVerifications(int userId);
1017        void receiveVerificationResponse(int verificationId);
1018    }
1019
1020    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1021        private Context mContext;
1022        private ComponentName mIntentFilterVerifierComponent;
1023        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1024
1025        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1026            mContext = context;
1027            mIntentFilterVerifierComponent = verifierComponent;
1028        }
1029
1030        private String getDefaultScheme() {
1031            return IntentFilter.SCHEME_HTTPS;
1032        }
1033
1034        @Override
1035        public void startVerifications(int userId) {
1036            // Launch verifications requests
1037            int count = mCurrentIntentFilterVerifications.size();
1038            for (int n=0; n<count; n++) {
1039                int verificationId = mCurrentIntentFilterVerifications.get(n);
1040                final IntentFilterVerificationState ivs =
1041                        mIntentFilterVerificationStates.get(verificationId);
1042
1043                String packageName = ivs.getPackageName();
1044
1045                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1046                final int filterCount = filters.size();
1047                ArraySet<String> domainsSet = new ArraySet<>();
1048                for (int m=0; m<filterCount; m++) {
1049                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1050                    domainsSet.addAll(filter.getHostsList());
1051                }
1052                synchronized (mPackages) {
1053                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1054                            packageName, domainsSet) != null) {
1055                        scheduleWriteSettingsLocked();
1056                    }
1057                }
1058                sendVerificationRequest(verificationId, ivs);
1059            }
1060            mCurrentIntentFilterVerifications.clear();
1061        }
1062
1063        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1064            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1065            verificationIntent.putExtra(
1066                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1067                    verificationId);
1068            verificationIntent.putExtra(
1069                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1070                    getDefaultScheme());
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1073                    ivs.getHostsString());
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1076                    ivs.getPackageName());
1077            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1078            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1079
1080            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1081            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1082                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1083                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1084
1085            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1086            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1087                    "Sending IntentFilter verification broadcast");
1088        }
1089
1090        public void receiveVerificationResponse(int verificationId) {
1091            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1092
1093            final boolean verified = ivs.isVerified();
1094
1095            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1096            final int count = filters.size();
1097            if (DEBUG_DOMAIN_VERIFICATION) {
1098                Slog.i(TAG, "Received verification response " + verificationId
1099                        + " for " + count + " filters, verified=" + verified);
1100            }
1101            for (int n=0; n<count; n++) {
1102                PackageParser.ActivityIntentInfo filter = filters.get(n);
1103                filter.setVerified(verified);
1104
1105                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1106                        + " verified with result:" + verified + " and hosts:"
1107                        + ivs.getHostsString());
1108            }
1109
1110            mIntentFilterVerificationStates.remove(verificationId);
1111
1112            final String packageName = ivs.getPackageName();
1113            IntentFilterVerificationInfo ivi = null;
1114
1115            synchronized (mPackages) {
1116                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1117            }
1118            if (ivi == null) {
1119                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1120                        + verificationId + " packageName:" + packageName);
1121                return;
1122            }
1123            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1124                    "Updating IntentFilterVerificationInfo for package " + packageName
1125                            +" verificationId:" + verificationId);
1126
1127            synchronized (mPackages) {
1128                if (verified) {
1129                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1130                } else {
1131                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1132                }
1133                scheduleWriteSettingsLocked();
1134
1135                final int userId = ivs.getUserId();
1136                if (userId != UserHandle.USER_ALL) {
1137                    final int userStatus =
1138                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1139
1140                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1141                    boolean needUpdate = false;
1142
1143                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1144                    // already been set by the User thru the Disambiguation dialog
1145                    switch (userStatus) {
1146                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1147                            if (verified) {
1148                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1149                            } else {
1150                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1151                            }
1152                            needUpdate = true;
1153                            break;
1154
1155                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1156                            if (verified) {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1158                                needUpdate = true;
1159                            }
1160                            break;
1161
1162                        default:
1163                            // Nothing to do
1164                    }
1165
1166                    if (needUpdate) {
1167                        mSettings.updateIntentFilterVerificationStatusLPw(
1168                                packageName, updatedStatus, userId);
1169                        scheduleWritePackageRestrictionsLocked(userId);
1170                    }
1171                }
1172            }
1173        }
1174
1175        @Override
1176        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1177                    ActivityIntentInfo filter, String packageName) {
1178            if (!hasValidDomains(filter)) {
1179                return false;
1180            }
1181            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1182            if (ivs == null) {
1183                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1184                        packageName);
1185            }
1186            if (DEBUG_DOMAIN_VERIFICATION) {
1187                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1188            }
1189            ivs.addFilter(filter);
1190            return true;
1191        }
1192
1193        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1194                int userId, int verificationId, String packageName) {
1195            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1196                    verifierUid, userId, packageName);
1197            ivs.setPendingState();
1198            synchronized (mPackages) {
1199                mIntentFilterVerificationStates.append(verificationId, ivs);
1200                mCurrentIntentFilterVerifications.add(verificationId);
1201            }
1202            return ivs;
1203        }
1204    }
1205
1206    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1207        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1208                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1209                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1210    }
1211
1212    // Set of pending broadcasts for aggregating enable/disable of components.
1213    static class PendingPackageBroadcasts {
1214        // for each user id, a map of <package name -> components within that package>
1215        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1216
1217        public PendingPackageBroadcasts() {
1218            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1219        }
1220
1221        public ArrayList<String> get(int userId, String packageName) {
1222            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1223            return packages.get(packageName);
1224        }
1225
1226        public void put(int userId, String packageName, ArrayList<String> components) {
1227            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1228            packages.put(packageName, components);
1229        }
1230
1231        public void remove(int userId, String packageName) {
1232            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1233            if (packages != null) {
1234                packages.remove(packageName);
1235            }
1236        }
1237
1238        public void remove(int userId) {
1239            mUidMap.remove(userId);
1240        }
1241
1242        public int userIdCount() {
1243            return mUidMap.size();
1244        }
1245
1246        public int userIdAt(int n) {
1247            return mUidMap.keyAt(n);
1248        }
1249
1250        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1251            return mUidMap.get(userId);
1252        }
1253
1254        public int size() {
1255            // total number of pending broadcast entries across all userIds
1256            int num = 0;
1257            for (int i = 0; i< mUidMap.size(); i++) {
1258                num += mUidMap.valueAt(i).size();
1259            }
1260            return num;
1261        }
1262
1263        public void clear() {
1264            mUidMap.clear();
1265        }
1266
1267        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1268            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1269            if (map == null) {
1270                map = new ArrayMap<String, ArrayList<String>>();
1271                mUidMap.put(userId, map);
1272            }
1273            return map;
1274        }
1275    }
1276    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1277
1278    // Service Connection to remote media container service to copy
1279    // package uri's from external media onto secure containers
1280    // or internal storage.
1281    private IMediaContainerService mContainerService = null;
1282
1283    static final int SEND_PENDING_BROADCAST = 1;
1284    static final int MCS_BOUND = 3;
1285    static final int END_COPY = 4;
1286    static final int INIT_COPY = 5;
1287    static final int MCS_UNBIND = 6;
1288    static final int START_CLEANING_PACKAGE = 7;
1289    static final int FIND_INSTALL_LOC = 8;
1290    static final int POST_INSTALL = 9;
1291    static final int MCS_RECONNECT = 10;
1292    static final int MCS_GIVE_UP = 11;
1293    static final int WRITE_SETTINGS = 13;
1294    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1295    static final int PACKAGE_VERIFIED = 15;
1296    static final int CHECK_PENDING_VERIFICATION = 16;
1297    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1298    static final int INTENT_FILTER_VERIFIED = 18;
1299    static final int WRITE_PACKAGE_LIST = 19;
1300    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1301
1302    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1303
1304    // Delay time in millisecs
1305    static final int BROADCAST_DELAY = 10 * 1000;
1306
1307    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1308            2 * 60 * 60 * 1000L; /* two hours */
1309
1310    static UserManagerService sUserManager;
1311
1312    // Stores a list of users whose package restrictions file needs to be updated
1313    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1314
1315    final private DefaultContainerConnection mDefContainerConn =
1316            new DefaultContainerConnection();
1317    class DefaultContainerConnection implements ServiceConnection {
1318        public void onServiceConnected(ComponentName name, IBinder service) {
1319            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1320            final IMediaContainerService imcs = IMediaContainerService.Stub
1321                    .asInterface(Binder.allowBlocking(service));
1322            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1323        }
1324
1325        public void onServiceDisconnected(ComponentName name) {
1326            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1327        }
1328    }
1329
1330    // Recordkeeping of restore-after-install operations that are currently in flight
1331    // between the Package Manager and the Backup Manager
1332    static class PostInstallData {
1333        public InstallArgs args;
1334        public PackageInstalledInfo res;
1335
1336        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1337            args = _a;
1338            res = _r;
1339        }
1340    }
1341
1342    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1343    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1344
1345    // XML tags for backup/restore of various bits of state
1346    private static final String TAG_PREFERRED_BACKUP = "pa";
1347    private static final String TAG_DEFAULT_APPS = "da";
1348    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1349
1350    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1351    private static final String TAG_ALL_GRANTS = "rt-grants";
1352    private static final String TAG_GRANT = "grant";
1353    private static final String ATTR_PACKAGE_NAME = "pkg";
1354
1355    private static final String TAG_PERMISSION = "perm";
1356    private static final String ATTR_PERMISSION_NAME = "name";
1357    private static final String ATTR_IS_GRANTED = "g";
1358    private static final String ATTR_USER_SET = "set";
1359    private static final String ATTR_USER_FIXED = "fixed";
1360    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1361
1362    // System/policy permission grants are not backed up
1363    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1364            FLAG_PERMISSION_POLICY_FIXED
1365            | FLAG_PERMISSION_SYSTEM_FIXED
1366            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1367
1368    // And we back up these user-adjusted states
1369    private static final int USER_RUNTIME_GRANT_MASK =
1370            FLAG_PERMISSION_USER_SET
1371            | FLAG_PERMISSION_USER_FIXED
1372            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1373
1374    final @Nullable String mRequiredVerifierPackage;
1375    final @NonNull String mRequiredInstallerPackage;
1376    final @NonNull String mRequiredUninstallerPackage;
1377    final @Nullable String mSetupWizardPackage;
1378    final @Nullable String mStorageManagerPackage;
1379    final @NonNull String mServicesSystemSharedLibraryPackageName;
1380    final @NonNull String mSharedSystemSharedLibraryPackageName;
1381
1382    private final PackageUsage mPackageUsage = new PackageUsage();
1383    private final CompilerStats mCompilerStats = new CompilerStats();
1384
1385    class PackageHandler extends Handler {
1386        private boolean mBound = false;
1387        final ArrayList<HandlerParams> mPendingInstalls =
1388            new ArrayList<HandlerParams>();
1389
1390        private boolean connectToService() {
1391            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1392                    " DefaultContainerService");
1393            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1394            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1395            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1396                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1397                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1398                mBound = true;
1399                return true;
1400            }
1401            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1402            return false;
1403        }
1404
1405        private void disconnectService() {
1406            mContainerService = null;
1407            mBound = false;
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            mContext.unbindService(mDefContainerConn);
1410            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411        }
1412
1413        PackageHandler(Looper looper) {
1414            super(looper);
1415        }
1416
1417        public void handleMessage(Message msg) {
1418            try {
1419                doHandleMessage(msg);
1420            } finally {
1421                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422            }
1423        }
1424
1425        void doHandleMessage(Message msg) {
1426            switch (msg.what) {
1427                case INIT_COPY: {
1428                    HandlerParams params = (HandlerParams) msg.obj;
1429                    int idx = mPendingInstalls.size();
1430                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1431                    // If a bind was already initiated we dont really
1432                    // need to do anything. The pending install
1433                    // will be processed later on.
1434                    if (!mBound) {
1435                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1436                                System.identityHashCode(mHandler));
1437                        // If this is the only one pending we might
1438                        // have to bind to the service again.
1439                        if (!connectToService()) {
1440                            Slog.e(TAG, "Failed to bind to media container service");
1441                            params.serviceError();
1442                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1443                                    System.identityHashCode(mHandler));
1444                            if (params.traceMethod != null) {
1445                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1446                                        params.traceCookie);
1447                            }
1448                            return;
1449                        } else {
1450                            // Once we bind to the service, the first
1451                            // pending request will be processed.
1452                            mPendingInstalls.add(idx, params);
1453                        }
1454                    } else {
1455                        mPendingInstalls.add(idx, params);
1456                        // Already bound to the service. Just make
1457                        // sure we trigger off processing the first request.
1458                        if (idx == 0) {
1459                            mHandler.sendEmptyMessage(MCS_BOUND);
1460                        }
1461                    }
1462                    break;
1463                }
1464                case MCS_BOUND: {
1465                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1466                    if (msg.obj != null) {
1467                        mContainerService = (IMediaContainerService) msg.obj;
1468                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1469                                System.identityHashCode(mHandler));
1470                    }
1471                    if (mContainerService == null) {
1472                        if (!mBound) {
1473                            // Something seriously wrong since we are not bound and we are not
1474                            // waiting for connection. Bail out.
1475                            Slog.e(TAG, "Cannot bind to media container service");
1476                            for (HandlerParams params : mPendingInstalls) {
1477                                // Indicate service bind error
1478                                params.serviceError();
1479                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1480                                        System.identityHashCode(params));
1481                                if (params.traceMethod != null) {
1482                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1483                                            params.traceMethod, params.traceCookie);
1484                                }
1485                                return;
1486                            }
1487                            mPendingInstalls.clear();
1488                        } else {
1489                            Slog.w(TAG, "Waiting to connect to media container service");
1490                        }
1491                    } else if (mPendingInstalls.size() > 0) {
1492                        HandlerParams params = mPendingInstalls.get(0);
1493                        if (params != null) {
1494                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1495                                    System.identityHashCode(params));
1496                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1497                            if (params.startCopy()) {
1498                                // We are done...  look for more work or to
1499                                // go idle.
1500                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1501                                        "Checking for more work or unbind...");
1502                                // Delete pending install
1503                                if (mPendingInstalls.size() > 0) {
1504                                    mPendingInstalls.remove(0);
1505                                }
1506                                if (mPendingInstalls.size() == 0) {
1507                                    if (mBound) {
1508                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1509                                                "Posting delayed MCS_UNBIND");
1510                                        removeMessages(MCS_UNBIND);
1511                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1512                                        // Unbind after a little delay, to avoid
1513                                        // continual thrashing.
1514                                        sendMessageDelayed(ubmsg, 10000);
1515                                    }
1516                                } else {
1517                                    // There are more pending requests in queue.
1518                                    // Just post MCS_BOUND message to trigger processing
1519                                    // of next pending install.
1520                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1521                                            "Posting MCS_BOUND for next work");
1522                                    mHandler.sendEmptyMessage(MCS_BOUND);
1523                                }
1524                            }
1525                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1526                        }
1527                    } else {
1528                        // Should never happen ideally.
1529                        Slog.w(TAG, "Empty queue");
1530                    }
1531                    break;
1532                }
1533                case MCS_RECONNECT: {
1534                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1535                    if (mPendingInstalls.size() > 0) {
1536                        if (mBound) {
1537                            disconnectService();
1538                        }
1539                        if (!connectToService()) {
1540                            Slog.e(TAG, "Failed to bind to media container service");
1541                            for (HandlerParams params : mPendingInstalls) {
1542                                // Indicate service bind error
1543                                params.serviceError();
1544                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1545                                        System.identityHashCode(params));
1546                            }
1547                            mPendingInstalls.clear();
1548                        }
1549                    }
1550                    break;
1551                }
1552                case MCS_UNBIND: {
1553                    // If there is no actual work left, then time to unbind.
1554                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1555
1556                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1557                        if (mBound) {
1558                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1559
1560                            disconnectService();
1561                        }
1562                    } else if (mPendingInstalls.size() > 0) {
1563                        // There are more pending requests in queue.
1564                        // Just post MCS_BOUND message to trigger processing
1565                        // of next pending install.
1566                        mHandler.sendEmptyMessage(MCS_BOUND);
1567                    }
1568
1569                    break;
1570                }
1571                case MCS_GIVE_UP: {
1572                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1573                    HandlerParams params = mPendingInstalls.remove(0);
1574                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1575                            System.identityHashCode(params));
1576                    break;
1577                }
1578                case SEND_PENDING_BROADCAST: {
1579                    String packages[];
1580                    ArrayList<String> components[];
1581                    int size = 0;
1582                    int uids[];
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        if (mPendingBroadcasts == null) {
1586                            return;
1587                        }
1588                        size = mPendingBroadcasts.size();
1589                        if (size <= 0) {
1590                            // Nothing to be done. Just return
1591                            return;
1592                        }
1593                        packages = new String[size];
1594                        components = new ArrayList[size];
1595                        uids = new int[size];
1596                        int i = 0;  // filling out the above arrays
1597
1598                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1599                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1600                            Iterator<Map.Entry<String, ArrayList<String>>> it
1601                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1602                                            .entrySet().iterator();
1603                            while (it.hasNext() && i < size) {
1604                                Map.Entry<String, ArrayList<String>> ent = it.next();
1605                                packages[i] = ent.getKey();
1606                                components[i] = ent.getValue();
1607                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1608                                uids[i] = (ps != null)
1609                                        ? UserHandle.getUid(packageUserId, ps.appId)
1610                                        : -1;
1611                                i++;
1612                            }
1613                        }
1614                        size = i;
1615                        mPendingBroadcasts.clear();
1616                    }
1617                    // Send broadcasts
1618                    for (int i = 0; i < size; i++) {
1619                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1620                    }
1621                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1622                    break;
1623                }
1624                case START_CLEANING_PACKAGE: {
1625                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1626                    final String packageName = (String)msg.obj;
1627                    final int userId = msg.arg1;
1628                    final boolean andCode = msg.arg2 != 0;
1629                    synchronized (mPackages) {
1630                        if (userId == UserHandle.USER_ALL) {
1631                            int[] users = sUserManager.getUserIds();
1632                            for (int user : users) {
1633                                mSettings.addPackageToCleanLPw(
1634                                        new PackageCleanItem(user, packageName, andCode));
1635                            }
1636                        } else {
1637                            mSettings.addPackageToCleanLPw(
1638                                    new PackageCleanItem(userId, packageName, andCode));
1639                        }
1640                    }
1641                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1642                    startCleaningPackages();
1643                } break;
1644                case POST_INSTALL: {
1645                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1646
1647                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1648                    final boolean didRestore = (msg.arg2 != 0);
1649                    mRunningInstalls.delete(msg.arg1);
1650
1651                    if (data != null) {
1652                        InstallArgs args = data.args;
1653                        PackageInstalledInfo parentRes = data.res;
1654
1655                        final boolean grantPermissions = (args.installFlags
1656                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1657                        final boolean killApp = (args.installFlags
1658                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1659                        final boolean virtualPreload = ((args.installFlags
1660                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1661                        final String[] grantedPermissions = args.installGrantPermissions;
1662
1663                        // Handle the parent package
1664                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1665                                virtualPreload, grantedPermissions, didRestore,
1666                                args.installerPackageName, args.observer);
1667
1668                        // Handle the child packages
1669                        final int childCount = (parentRes.addedChildPackages != null)
1670                                ? parentRes.addedChildPackages.size() : 0;
1671                        for (int i = 0; i < childCount; i++) {
1672                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1673                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1674                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1675                                    args.installerPackageName, args.observer);
1676                        }
1677
1678                        // Log tracing if needed
1679                        if (args.traceMethod != null) {
1680                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1681                                    args.traceCookie);
1682                        }
1683                    } else {
1684                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1685                    }
1686
1687                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1688                } break;
1689                case WRITE_SETTINGS: {
1690                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1691                    synchronized (mPackages) {
1692                        removeMessages(WRITE_SETTINGS);
1693                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1694                        mSettings.writeLPr();
1695                        mDirtyUsers.clear();
1696                    }
1697                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1698                } break;
1699                case WRITE_PACKAGE_RESTRICTIONS: {
1700                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1701                    synchronized (mPackages) {
1702                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1703                        for (int userId : mDirtyUsers) {
1704                            mSettings.writePackageRestrictionsLPr(userId);
1705                        }
1706                        mDirtyUsers.clear();
1707                    }
1708                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1709                } break;
1710                case WRITE_PACKAGE_LIST: {
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1712                    synchronized (mPackages) {
1713                        removeMessages(WRITE_PACKAGE_LIST);
1714                        mSettings.writePackageListLPr(msg.arg1);
1715                    }
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1717                } break;
1718                case CHECK_PENDING_VERIFICATION: {
1719                    final int verificationId = msg.arg1;
1720                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1721
1722                    if ((state != null) && !state.timeoutExtended()) {
1723                        final InstallArgs args = state.getInstallArgs();
1724                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1725
1726                        Slog.i(TAG, "Verification timed out for " + originUri);
1727                        mPendingVerification.remove(verificationId);
1728
1729                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1730
1731                        final UserHandle user = args.getUser();
1732                        if (getDefaultVerificationResponse(user)
1733                                == PackageManager.VERIFICATION_ALLOW) {
1734                            Slog.i(TAG, "Continuing with installation of " + originUri);
1735                            state.setVerifierResponse(Binder.getCallingUid(),
1736                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1737                            broadcastPackageVerified(verificationId, originUri,
1738                                    PackageManager.VERIFICATION_ALLOW, user);
1739                            try {
1740                                ret = args.copyApk(mContainerService, true);
1741                            } catch (RemoteException e) {
1742                                Slog.e(TAG, "Could not contact the ContainerService");
1743                            }
1744                        } else {
1745                            broadcastPackageVerified(verificationId, originUri,
1746                                    PackageManager.VERIFICATION_REJECT, user);
1747                        }
1748
1749                        Trace.asyncTraceEnd(
1750                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1751
1752                        processPendingInstall(args, ret);
1753                        mHandler.sendEmptyMessage(MCS_UNBIND);
1754                    }
1755                    break;
1756                }
1757                case PACKAGE_VERIFIED: {
1758                    final int verificationId = msg.arg1;
1759
1760                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1761                    if (state == null) {
1762                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1763                        break;
1764                    }
1765
1766                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1767
1768                    state.setVerifierResponse(response.callerUid, response.code);
1769
1770                    if (state.isVerificationComplete()) {
1771                        mPendingVerification.remove(verificationId);
1772
1773                        final InstallArgs args = state.getInstallArgs();
1774                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1775
1776                        int ret;
1777                        if (state.isInstallAllowed()) {
1778                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1779                            broadcastPackageVerified(verificationId, originUri,
1780                                    response.code, state.getInstallArgs().getUser());
1781                            try {
1782                                ret = args.copyApk(mContainerService, true);
1783                            } catch (RemoteException e) {
1784                                Slog.e(TAG, "Could not contact the ContainerService");
1785                            }
1786                        } else {
1787                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1788                        }
1789
1790                        Trace.asyncTraceEnd(
1791                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1792
1793                        processPendingInstall(args, ret);
1794                        mHandler.sendEmptyMessage(MCS_UNBIND);
1795                    }
1796
1797                    break;
1798                }
1799                case START_INTENT_FILTER_VERIFICATIONS: {
1800                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1801                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1802                            params.replacing, params.pkg);
1803                    break;
1804                }
1805                case INTENT_FILTER_VERIFIED: {
1806                    final int verificationId = msg.arg1;
1807
1808                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1809                            verificationId);
1810                    if (state == null) {
1811                        Slog.w(TAG, "Invalid IntentFilter verification token "
1812                                + verificationId + " received");
1813                        break;
1814                    }
1815
1816                    final int userId = state.getUserId();
1817
1818                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1819                            "Processing IntentFilter verification with token:"
1820                            + verificationId + " and userId:" + userId);
1821
1822                    final IntentFilterVerificationResponse response =
1823                            (IntentFilterVerificationResponse) msg.obj;
1824
1825                    state.setVerifierResponse(response.callerUid, response.code);
1826
1827                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1828                            "IntentFilter verification with token:" + verificationId
1829                            + " and userId:" + userId
1830                            + " is settings verifier response with response code:"
1831                            + response.code);
1832
1833                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1834                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1835                                + response.getFailedDomainsString());
1836                    }
1837
1838                    if (state.isVerificationComplete()) {
1839                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1840                    } else {
1841                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                                "IntentFilter verification with token:" + verificationId
1843                                + " was not said to be complete");
1844                    }
1845
1846                    break;
1847                }
1848                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1849                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1850                            mInstantAppResolverConnection,
1851                            (InstantAppRequest) msg.obj,
1852                            mInstantAppInstallerActivity,
1853                            mHandler);
1854                }
1855            }
1856        }
1857    }
1858
1859    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1860        @Override
1861        public void onGidsChanged(int appId, int userId) {
1862            mHandler.post(new Runnable() {
1863                @Override
1864                public void run() {
1865                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1866                }
1867            });
1868        }
1869        @Override
1870        public void onPermissionGranted(int uid, int userId) {
1871            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1872
1873            // Not critical; if this is lost, the application has to request again.
1874            synchronized (mPackages) {
1875                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1876            }
1877        }
1878        @Override
1879        public void onInstallPermissionGranted() {
1880            synchronized (mPackages) {
1881                scheduleWriteSettingsLocked();
1882            }
1883        }
1884        @Override
1885        public void onPermissionRevoked(int uid, int userId) {
1886            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1887
1888            synchronized (mPackages) {
1889                // Critical; after this call the application should never have the permission
1890                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1891            }
1892
1893            final int appId = UserHandle.getAppId(uid);
1894            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1895        }
1896        @Override
1897        public void onInstallPermissionRevoked() {
1898            synchronized (mPackages) {
1899                scheduleWriteSettingsLocked();
1900            }
1901        }
1902        @Override
1903        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1904            synchronized (mPackages) {
1905                for (int userId : updatedUserIds) {
1906                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1907                }
1908            }
1909        }
1910        @Override
1911        public void onInstallPermissionUpdated() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionRemoved() {
1918            synchronized (mPackages) {
1919                mSettings.writeLPr();
1920            }
1921        }
1922    };
1923
1924    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1925            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1926            boolean launchedForRestore, String installerPackage,
1927            IPackageInstallObserver2 installObserver) {
1928        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1929            // Send the removed broadcasts
1930            if (res.removedInfo != null) {
1931                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1932            }
1933
1934            // Now that we successfully installed the package, grant runtime
1935            // permissions if requested before broadcasting the install. Also
1936            // for legacy apps in permission review mode we clear the permission
1937            // review flag which is used to emulate runtime permissions for
1938            // legacy apps.
1939            if (grantPermissions) {
1940                final int callingUid = Binder.getCallingUid();
1941                mPermissionManager.grantRequestedRuntimePermissions(
1942                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1943                        mPermissionCallback);
1944            }
1945
1946            final boolean update = res.removedInfo != null
1947                    && res.removedInfo.removedPackage != null;
1948            final String installerPackageName =
1949                    res.installerPackageName != null
1950                            ? res.installerPackageName
1951                            : res.removedInfo != null
1952                                    ? res.removedInfo.installerPackageName
1953                                    : null;
1954
1955            // If this is the first time we have child packages for a disabled privileged
1956            // app that had no children, we grant requested runtime permissions to the new
1957            // children if the parent on the system image had them already granted.
1958            if (res.pkg.parentPackage != null) {
1959                final int callingUid = Binder.getCallingUid();
1960                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1961                        res.pkg, callingUid, mPermissionCallback);
1962            }
1963
1964            synchronized (mPackages) {
1965                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1966            }
1967
1968            final String packageName = res.pkg.applicationInfo.packageName;
1969
1970            // Determine the set of users who are adding this package for
1971            // the first time vs. those who are seeing an update.
1972            int[] firstUserIds = EMPTY_INT_ARRAY;
1973            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1974            int[] updateUserIds = EMPTY_INT_ARRAY;
1975            int[] instantUserIds = EMPTY_INT_ARRAY;
1976            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1977            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1978            for (int newUser : res.newUsers) {
1979                final boolean isInstantApp = ps.getInstantApp(newUser);
1980                if (allNewUsers) {
1981                    if (isInstantApp) {
1982                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1983                    } else {
1984                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1985                    }
1986                    continue;
1987                }
1988                boolean isNew = true;
1989                for (int origUser : res.origUsers) {
1990                    if (origUser == newUser) {
1991                        isNew = false;
1992                        break;
1993                    }
1994                }
1995                if (isNew) {
1996                    if (isInstantApp) {
1997                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1998                    } else {
1999                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2000                    }
2001                } else {
2002                    if (isInstantApp) {
2003                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2004                    } else {
2005                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2006                    }
2007                }
2008            }
2009
2010            // Send installed broadcasts if the package is not a static shared lib.
2011            if (res.pkg.staticSharedLibName == null) {
2012                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2013
2014                // Send added for users that see the package for the first time
2015                // sendPackageAddedForNewUsers also deals with system apps
2016                int appId = UserHandle.getAppId(res.uid);
2017                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2018                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2019                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2020
2021                // Send added for users that don't see the package for the first time
2022                Bundle extras = new Bundle(1);
2023                extras.putInt(Intent.EXTRA_UID, res.uid);
2024                if (update) {
2025                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2026                }
2027                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2028                        extras, 0 /*flags*/,
2029                        null /*targetPackage*/, null /*finishedReceiver*/,
2030                        updateUserIds, instantUserIds);
2031                if (installerPackageName != null) {
2032                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2033                            extras, 0 /*flags*/,
2034                            installerPackageName, null /*finishedReceiver*/,
2035                            updateUserIds, instantUserIds);
2036                }
2037
2038                // Send replaced for users that don't see the package for the first time
2039                if (update) {
2040                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2041                            packageName, extras, 0 /*flags*/,
2042                            null /*targetPackage*/, null /*finishedReceiver*/,
2043                            updateUserIds, instantUserIds);
2044                    if (installerPackageName != null) {
2045                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2046                                extras, 0 /*flags*/,
2047                                installerPackageName, null /*finishedReceiver*/,
2048                                updateUserIds, instantUserIds);
2049                    }
2050                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2051                            null /*package*/, null /*extras*/, 0 /*flags*/,
2052                            packageName /*targetPackage*/,
2053                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2054                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2055                    // First-install and we did a restore, so we're responsible for the
2056                    // first-launch broadcast.
2057                    if (DEBUG_BACKUP) {
2058                        Slog.i(TAG, "Post-restore of " + packageName
2059                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2060                    }
2061                    sendFirstLaunchBroadcast(packageName, installerPackage,
2062                            firstUserIds, firstInstantUserIds);
2063                }
2064
2065                // Send broadcast package appeared if forward locked/external for all users
2066                // treat asec-hosted packages like removable media on upgrade
2067                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2068                    if (DEBUG_INSTALL) {
2069                        Slog.i(TAG, "upgrading pkg " + res.pkg
2070                                + " is ASEC-hosted -> AVAILABLE");
2071                    }
2072                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2073                    ArrayList<String> pkgList = new ArrayList<>(1);
2074                    pkgList.add(packageName);
2075                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2076                }
2077            }
2078
2079            // Work that needs to happen on first install within each user
2080            if (firstUserIds != null && firstUserIds.length > 0) {
2081                synchronized (mPackages) {
2082                    for (int userId : firstUserIds) {
2083                        // If this app is a browser and it's newly-installed for some
2084                        // users, clear any default-browser state in those users. The
2085                        // app's nature doesn't depend on the user, so we can just check
2086                        // its browser nature in any user and generalize.
2087                        if (packageIsBrowser(packageName, userId)) {
2088                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2089                        }
2090
2091                        // We may also need to apply pending (restored) runtime
2092                        // permission grants within these users.
2093                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2094                    }
2095                }
2096            }
2097
2098            // Log current value of "unknown sources" setting
2099            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2100                    getUnknownSourcesSettings());
2101
2102            // Remove the replaced package's older resources safely now
2103            // We delete after a gc for applications  on sdcard.
2104            if (res.removedInfo != null && res.removedInfo.args != null) {
2105                Runtime.getRuntime().gc();
2106                synchronized (mInstallLock) {
2107                    res.removedInfo.args.doPostDeleteLI(true);
2108                }
2109            } else {
2110                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2111                // and not block here.
2112                VMRuntime.getRuntime().requestConcurrentGC();
2113            }
2114
2115            // Notify DexManager that the package was installed for new users.
2116            // The updated users should already be indexed and the package code paths
2117            // should not change.
2118            // Don't notify the manager for ephemeral apps as they are not expected to
2119            // survive long enough to benefit of background optimizations.
2120            for (int userId : firstUserIds) {
2121                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2122                // There's a race currently where some install events may interleave with an uninstall.
2123                // This can lead to package info being null (b/36642664).
2124                if (info != null) {
2125                    mDexManager.notifyPackageInstalled(info, userId);
2126                }
2127            }
2128        }
2129
2130        // If someone is watching installs - notify them
2131        if (installObserver != null) {
2132            try {
2133                Bundle extras = extrasForInstallResult(res);
2134                installObserver.onPackageInstalled(res.name, res.returnCode,
2135                        res.returnMsg, extras);
2136            } catch (RemoteException e) {
2137                Slog.i(TAG, "Observer no longer exists.");
2138            }
2139        }
2140    }
2141
2142    private StorageEventListener mStorageListener = new StorageEventListener() {
2143        @Override
2144        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2145            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2146                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2147                    final String volumeUuid = vol.getFsUuid();
2148
2149                    // Clean up any users or apps that were removed or recreated
2150                    // while this volume was missing
2151                    sUserManager.reconcileUsers(volumeUuid);
2152                    reconcileApps(volumeUuid);
2153
2154                    // Clean up any install sessions that expired or were
2155                    // cancelled while this volume was missing
2156                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2157
2158                    loadPrivatePackages(vol);
2159
2160                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2161                    unloadPrivatePackages(vol);
2162                }
2163            }
2164        }
2165
2166        @Override
2167        public void onVolumeForgotten(String fsUuid) {
2168            if (TextUtils.isEmpty(fsUuid)) {
2169                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2170                return;
2171            }
2172
2173            // Remove any apps installed on the forgotten volume
2174            synchronized (mPackages) {
2175                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2176                for (PackageSetting ps : packages) {
2177                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2178                    deletePackageVersioned(new VersionedPackage(ps.name,
2179                            PackageManager.VERSION_CODE_HIGHEST),
2180                            new LegacyPackageDeleteObserver(null).getBinder(),
2181                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2182                    // Try very hard to release any references to this package
2183                    // so we don't risk the system server being killed due to
2184                    // open FDs
2185                    AttributeCache.instance().removePackage(ps.name);
2186                }
2187
2188                mSettings.onVolumeForgotten(fsUuid);
2189                mSettings.writeLPr();
2190            }
2191        }
2192    };
2193
2194    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2195        Bundle extras = null;
2196        switch (res.returnCode) {
2197            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2198                extras = new Bundle();
2199                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2200                        res.origPermission);
2201                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2202                        res.origPackage);
2203                break;
2204            }
2205            case PackageManager.INSTALL_SUCCEEDED: {
2206                extras = new Bundle();
2207                extras.putBoolean(Intent.EXTRA_REPLACING,
2208                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2209                break;
2210            }
2211        }
2212        return extras;
2213    }
2214
2215    void scheduleWriteSettingsLocked() {
2216        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2217            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2218        }
2219    }
2220
2221    void scheduleWritePackageListLocked(int userId) {
2222        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2223            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2224            msg.arg1 = userId;
2225            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2226        }
2227    }
2228
2229    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2230        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2231        scheduleWritePackageRestrictionsLocked(userId);
2232    }
2233
2234    void scheduleWritePackageRestrictionsLocked(int userId) {
2235        final int[] userIds = (userId == UserHandle.USER_ALL)
2236                ? sUserManager.getUserIds() : new int[]{userId};
2237        for (int nextUserId : userIds) {
2238            if (!sUserManager.exists(nextUserId)) return;
2239            mDirtyUsers.add(nextUserId);
2240            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2241                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2242            }
2243        }
2244    }
2245
2246    public static PackageManagerService main(Context context, Installer installer,
2247            boolean factoryTest, boolean onlyCore) {
2248        // Self-check for initial settings.
2249        PackageManagerServiceCompilerMapping.checkProperties();
2250
2251        PackageManagerService m = new PackageManagerService(context, installer,
2252                factoryTest, onlyCore);
2253        m.enableSystemUserPackages();
2254        ServiceManager.addService("package", m);
2255        final PackageManagerNative pmn = m.new PackageManagerNative();
2256        ServiceManager.addService("package_native", pmn);
2257        return m;
2258    }
2259
2260    private void enableSystemUserPackages() {
2261        if (!UserManager.isSplitSystemUser()) {
2262            return;
2263        }
2264        // For system user, enable apps based on the following conditions:
2265        // - app is whitelisted or belong to one of these groups:
2266        //   -- system app which has no launcher icons
2267        //   -- system app which has INTERACT_ACROSS_USERS permission
2268        //   -- system IME app
2269        // - app is not in the blacklist
2270        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2271        Set<String> enableApps = new ArraySet<>();
2272        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2273                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2274                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2275        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2276        enableApps.addAll(wlApps);
2277        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2278                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2279        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2280        enableApps.removeAll(blApps);
2281        Log.i(TAG, "Applications installed for system user: " + enableApps);
2282        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2283                UserHandle.SYSTEM);
2284        final int allAppsSize = allAps.size();
2285        synchronized (mPackages) {
2286            for (int i = 0; i < allAppsSize; i++) {
2287                String pName = allAps.get(i);
2288                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2289                // Should not happen, but we shouldn't be failing if it does
2290                if (pkgSetting == null) {
2291                    continue;
2292                }
2293                boolean install = enableApps.contains(pName);
2294                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2295                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2296                            + " for system user");
2297                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2298                }
2299            }
2300            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2301        }
2302    }
2303
2304    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2305        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2306                Context.DISPLAY_SERVICE);
2307        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2308    }
2309
2310    /**
2311     * Requests that files preopted on a secondary system partition be copied to the data partition
2312     * if possible.  Note that the actual copying of the files is accomplished by init for security
2313     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2314     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2315     */
2316    private static void requestCopyPreoptedFiles() {
2317        final int WAIT_TIME_MS = 100;
2318        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2319        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2320            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2321            // We will wait for up to 100 seconds.
2322            final long timeStart = SystemClock.uptimeMillis();
2323            final long timeEnd = timeStart + 100 * 1000;
2324            long timeNow = timeStart;
2325            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2326                try {
2327                    Thread.sleep(WAIT_TIME_MS);
2328                } catch (InterruptedException e) {
2329                    // Do nothing
2330                }
2331                timeNow = SystemClock.uptimeMillis();
2332                if (timeNow > timeEnd) {
2333                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2334                    Slog.wtf(TAG, "cppreopt did not finish!");
2335                    break;
2336                }
2337            }
2338
2339            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2340        }
2341    }
2342
2343    public PackageManagerService(Context context, Installer installer,
2344            boolean factoryTest, boolean onlyCore) {
2345        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2346        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2347        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2348                SystemClock.uptimeMillis());
2349
2350        if (mSdkVersion <= 0) {
2351            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2352        }
2353
2354        mContext = context;
2355
2356        mFactoryTest = factoryTest;
2357        mOnlyCore = onlyCore;
2358        mMetrics = new DisplayMetrics();
2359        mInstaller = installer;
2360
2361        // Create sub-components that provide services / data. Order here is important.
2362        synchronized (mInstallLock) {
2363        synchronized (mPackages) {
2364            // Expose private service for system components to use.
2365            LocalServices.addService(
2366                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2367            sUserManager = new UserManagerService(context, this,
2368                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2369            mPermissionManager = PermissionManagerService.create(context,
2370                    new DefaultPermissionGrantedCallback() {
2371                        @Override
2372                        public void onDefaultRuntimePermissionsGranted(int userId) {
2373                            synchronized(mPackages) {
2374                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2375                            }
2376                        }
2377                    }, mPackages /*externalLock*/);
2378            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2379            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2380        }
2381        }
2382        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2391                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2392        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2393                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2394
2395        String separateProcesses = SystemProperties.get("debug.separate_processes");
2396        if (separateProcesses != null && separateProcesses.length() > 0) {
2397            if ("*".equals(separateProcesses)) {
2398                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2399                mSeparateProcesses = null;
2400                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2401            } else {
2402                mDefParseFlags = 0;
2403                mSeparateProcesses = separateProcesses.split(",");
2404                Slog.w(TAG, "Running with debug.separate_processes: "
2405                        + separateProcesses);
2406            }
2407        } else {
2408            mDefParseFlags = 0;
2409            mSeparateProcesses = null;
2410        }
2411
2412        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2413                "*dexopt*");
2414        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2415                installer, mInstallLock);
2416        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2417                dexManagerListener);
2418        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2419
2420        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2421                FgThread.get().getLooper());
2422
2423        getDefaultDisplayMetrics(context, mMetrics);
2424
2425        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2426        SystemConfig systemConfig = SystemConfig.getInstance();
2427        mAvailableFeatures = systemConfig.getAvailableFeatures();
2428        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2429
2430        mProtectedPackages = new ProtectedPackages(mContext);
2431
2432        synchronized (mInstallLock) {
2433        // writer
2434        synchronized (mPackages) {
2435            mHandlerThread = new ServiceThread(TAG,
2436                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2437            mHandlerThread.start();
2438            mHandler = new PackageHandler(mHandlerThread.getLooper());
2439            mProcessLoggingHandler = new ProcessLoggingHandler();
2440            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2441            mInstantAppRegistry = new InstantAppRegistry(this);
2442
2443            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2444            final int builtInLibCount = libConfig.size();
2445            for (int i = 0; i < builtInLibCount; i++) {
2446                String name = libConfig.keyAt(i);
2447                String path = libConfig.valueAt(i);
2448                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2449                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2450            }
2451
2452            SELinuxMMAC.readInstallPolicy();
2453
2454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2455            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2457
2458            // Clean up orphaned packages for which the code path doesn't exist
2459            // and they are an update to a system app - caused by bug/32321269
2460            final int packageSettingCount = mSettings.mPackages.size();
2461            for (int i = packageSettingCount - 1; i >= 0; i--) {
2462                PackageSetting ps = mSettings.mPackages.valueAt(i);
2463                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2464                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2465                    mSettings.mPackages.removeAt(i);
2466                    mSettings.enableSystemPackageLPw(ps.name);
2467                }
2468            }
2469
2470            if (mFirstBoot) {
2471                requestCopyPreoptedFiles();
2472            }
2473
2474            String customResolverActivity = Resources.getSystem().getString(
2475                    R.string.config_customResolverActivity);
2476            if (TextUtils.isEmpty(customResolverActivity)) {
2477                customResolverActivity = null;
2478            } else {
2479                mCustomResolverComponentName = ComponentName.unflattenFromString(
2480                        customResolverActivity);
2481            }
2482
2483            long startTime = SystemClock.uptimeMillis();
2484
2485            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2486                    startTime);
2487
2488            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2489            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2490
2491            if (bootClassPath == null) {
2492                Slog.w(TAG, "No BOOTCLASSPATH found!");
2493            }
2494
2495            if (systemServerClassPath == null) {
2496                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2497            }
2498
2499            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2500
2501            final VersionInfo ver = mSettings.getInternalVersion();
2502            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2503            if (mIsUpgrade) {
2504                logCriticalInfo(Log.INFO,
2505                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2506            }
2507
2508            // when upgrading from pre-M, promote system app permissions from install to runtime
2509            mPromoteSystemApps =
2510                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2511
2512            // When upgrading from pre-N, we need to handle package extraction like first boot,
2513            // as there is no profiling data available.
2514            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2515
2516            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2517
2518            // save off the names of pre-existing system packages prior to scanning; we don't
2519            // want to automatically grant runtime permissions for new system apps
2520            if (mPromoteSystemApps) {
2521                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2522                while (pkgSettingIter.hasNext()) {
2523                    PackageSetting ps = pkgSettingIter.next();
2524                    if (isSystemApp(ps)) {
2525                        mExistingSystemPackages.add(ps.name);
2526                    }
2527                }
2528            }
2529
2530            mCacheDir = preparePackageParserCache(mIsUpgrade);
2531
2532            // Set flag to monitor and not change apk file paths when
2533            // scanning install directories.
2534            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2535
2536            if (mIsUpgrade || mFirstBoot) {
2537                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2538            }
2539
2540            // Collect vendor overlay packages. (Do this before scanning any apps.)
2541            // For security and version matching reason, only consider
2542            // overlay packages if they reside in the right directory.
2543            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2544                    mDefParseFlags
2545                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2546                    scanFlags
2547                    | SCAN_AS_SYSTEM
2548                    | SCAN_TRUSTED_OVERLAY,
2549                    0);
2550
2551            mParallelPackageParserCallback.findStaticOverlayPackages();
2552
2553            // Find base frameworks (resource packages without code).
2554            scanDirTracedLI(frameworkDir,
2555                    mDefParseFlags
2556                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2557                    scanFlags
2558                    | SCAN_NO_DEX
2559                    | SCAN_AS_SYSTEM
2560                    | SCAN_AS_PRIVILEGED,
2561                    0);
2562
2563            // Collected privileged system packages.
2564            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2565            scanDirTracedLI(privilegedAppDir,
2566                    mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2568                    scanFlags
2569                    | SCAN_AS_SYSTEM
2570                    | SCAN_AS_PRIVILEGED,
2571                    0);
2572
2573            // Collect ordinary system packages.
2574            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2575            scanDirTracedLI(systemAppDir,
2576                    mDefParseFlags
2577                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2578                    scanFlags
2579                    | SCAN_AS_SYSTEM,
2580                    0);
2581
2582            // Collected privileged vendor packages.
2583                File privilegedVendorAppDir = new File(Environment.getVendorDirectory(),
2584                        "priv-app");
2585            try {
2586                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2587            } catch (IOException e) {
2588                // failed to look up canonical path, continue with original one
2589            }
2590            scanDirTracedLI(privilegedVendorAppDir,
2591                    mDefParseFlags
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2593                    scanFlags
2594                    | SCAN_AS_SYSTEM
2595                    | SCAN_AS_VENDOR
2596                    | SCAN_AS_PRIVILEGED,
2597                    0);
2598
2599            // Collect ordinary vendor packages.
2600            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2601            try {
2602                vendorAppDir = vendorAppDir.getCanonicalFile();
2603            } catch (IOException e) {
2604                // failed to look up canonical path, continue with original one
2605            }
2606            scanDirTracedLI(vendorAppDir,
2607                    mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2609                    scanFlags
2610                    | SCAN_AS_SYSTEM
2611                    | SCAN_AS_VENDOR,
2612                    0);
2613
2614            // Collect all OEM packages.
2615            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2616            scanDirTracedLI(oemAppDir,
2617                    mDefParseFlags
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2619                    scanFlags
2620                    | SCAN_AS_SYSTEM
2621                    | SCAN_AS_OEM,
2622                    0);
2623
2624            // Prune any system packages that no longer exist.
2625            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2626            // Stub packages must either be replaced with full versions in the /data
2627            // partition or be disabled.
2628            final List<String> stubSystemApps = new ArrayList<>();
2629            if (!mOnlyCore) {
2630                // do this first before mucking with mPackages for the "expecting better" case
2631                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2632                while (pkgIterator.hasNext()) {
2633                    final PackageParser.Package pkg = pkgIterator.next();
2634                    if (pkg.isStub) {
2635                        stubSystemApps.add(pkg.packageName);
2636                    }
2637                }
2638
2639                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2640                while (psit.hasNext()) {
2641                    PackageSetting ps = psit.next();
2642
2643                    /*
2644                     * If this is not a system app, it can't be a
2645                     * disable system app.
2646                     */
2647                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2648                        continue;
2649                    }
2650
2651                    /*
2652                     * If the package is scanned, it's not erased.
2653                     */
2654                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2655                    if (scannedPkg != null) {
2656                        /*
2657                         * If the system app is both scanned and in the
2658                         * disabled packages list, then it must have been
2659                         * added via OTA. Remove it from the currently
2660                         * scanned package so the previously user-installed
2661                         * application can be scanned.
2662                         */
2663                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2664                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2665                                    + ps.name + "; removing system app.  Last known codePath="
2666                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2667                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2668                                    + scannedPkg.getLongVersionCode());
2669                            removePackageLI(scannedPkg, true);
2670                            mExpectingBetter.put(ps.name, ps.codePath);
2671                        }
2672
2673                        continue;
2674                    }
2675
2676                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2677                        psit.remove();
2678                        logCriticalInfo(Log.WARN, "System package " + ps.name
2679                                + " no longer exists; it's data will be wiped");
2680                        // Actual deletion of code and data will be handled by later
2681                        // reconciliation step
2682                    } else {
2683                        // we still have a disabled system package, but, it still might have
2684                        // been removed. check the code path still exists and check there's
2685                        // still a package. the latter can happen if an OTA keeps the same
2686                        // code path, but, changes the package name.
2687                        final PackageSetting disabledPs =
2688                                mSettings.getDisabledSystemPkgLPr(ps.name);
2689                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2690                                || disabledPs.pkg == null) {
2691                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2692                        }
2693                    }
2694                }
2695            }
2696
2697            //look for any incomplete package installations
2698            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2699            for (int i = 0; i < deletePkgsList.size(); i++) {
2700                // Actual deletion of code and data will be handled by later
2701                // reconciliation step
2702                final String packageName = deletePkgsList.get(i).name;
2703                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2704                synchronized (mPackages) {
2705                    mSettings.removePackageLPw(packageName);
2706                }
2707            }
2708
2709            //delete tmp files
2710            deleteTempPackageFiles();
2711
2712            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2713
2714            // Remove any shared userIDs that have no associated packages
2715            mSettings.pruneSharedUsersLPw();
2716            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2717            final int systemPackagesCount = mPackages.size();
2718            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2719                    + " ms, packageCount: " + systemPackagesCount
2720                    + " , timePerPackage: "
2721                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2722                    + " , cached: " + cachedSystemApps);
2723            if (mIsUpgrade && systemPackagesCount > 0) {
2724                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2725                        ((int) systemScanTime) / systemPackagesCount);
2726            }
2727            if (!mOnlyCore) {
2728                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2729                        SystemClock.uptimeMillis());
2730                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2731
2732                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2733                        | PackageParser.PARSE_FORWARD_LOCK,
2734                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2735
2736                // Remove disable package settings for updated system apps that were
2737                // removed via an OTA. If the update is no longer present, remove the
2738                // app completely. Otherwise, revoke their system privileges.
2739                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2740                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2741                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2742
2743                    final String msg;
2744                    if (deletedPkg == null) {
2745                        // should have found an update, but, we didn't; remove everything
2746                        msg = "Updated system package " + deletedAppName
2747                                + " no longer exists; removing its data";
2748                        // Actual deletion of code and data will be handled by later
2749                        // reconciliation step
2750                    } else {
2751                        // found an update; revoke system privileges
2752                        msg = "Updated system package + " + deletedAppName
2753                                + " no longer exists; revoking system privileges";
2754
2755                        // Don't do anything if a stub is removed from the system image. If
2756                        // we were to remove the uncompressed version from the /data partition,
2757                        // this is where it'd be done.
2758
2759                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2760                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2761                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2762                    }
2763                    logCriticalInfo(Log.WARN, msg);
2764                }
2765
2766                /*
2767                 * Make sure all system apps that we expected to appear on
2768                 * the userdata partition actually showed up. If they never
2769                 * appeared, crawl back and revive the system version.
2770                 */
2771                for (int i = 0; i < mExpectingBetter.size(); i++) {
2772                    final String packageName = mExpectingBetter.keyAt(i);
2773                    if (!mPackages.containsKey(packageName)) {
2774                        final File scanFile = mExpectingBetter.valueAt(i);
2775
2776                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2777                                + " but never showed up; reverting to system");
2778
2779                        final @ParseFlags int reparseFlags;
2780                        final @ScanFlags int rescanFlags;
2781                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2782                            reparseFlags =
2783                                    mDefParseFlags |
2784                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2785                            rescanFlags =
2786                                    scanFlags
2787                                    | SCAN_AS_SYSTEM
2788                                    | SCAN_AS_PRIVILEGED;
2789                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2790                            reparseFlags =
2791                                    mDefParseFlags |
2792                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2793                            rescanFlags =
2794                                    scanFlags
2795                                    | SCAN_AS_SYSTEM;
2796                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2797                            reparseFlags =
2798                                    mDefParseFlags |
2799                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2800                            rescanFlags =
2801                                    scanFlags
2802                                    | SCAN_AS_SYSTEM
2803                                    | SCAN_AS_VENDOR
2804                                    | SCAN_AS_PRIVILEGED;
2805                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2806                            reparseFlags =
2807                                    mDefParseFlags |
2808                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2809                            rescanFlags =
2810                                    scanFlags
2811                                    | SCAN_AS_SYSTEM
2812                                    | SCAN_AS_VENDOR;
2813                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2814                            reparseFlags =
2815                                    mDefParseFlags |
2816                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2817                            rescanFlags =
2818                                    scanFlags
2819                                    | SCAN_AS_SYSTEM
2820                                    | SCAN_AS_OEM;
2821                        } else {
2822                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2823                            continue;
2824                        }
2825
2826                        mSettings.enableSystemPackageLPw(packageName);
2827
2828                        try {
2829                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2830                        } catch (PackageManagerException e) {
2831                            Slog.e(TAG, "Failed to parse original system package: "
2832                                    + e.getMessage());
2833                        }
2834                    }
2835                }
2836
2837                // Uncompress and install any stubbed system applications.
2838                // This must be done last to ensure all stubs are replaced or disabled.
2839                decompressSystemApplications(stubSystemApps, scanFlags);
2840
2841                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2842                                - cachedSystemApps;
2843
2844                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2845                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2846                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2847                        + " ms, packageCount: " + dataPackagesCount
2848                        + " , timePerPackage: "
2849                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2850                        + " , cached: " + cachedNonSystemApps);
2851                if (mIsUpgrade && dataPackagesCount > 0) {
2852                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2853                            ((int) dataScanTime) / dataPackagesCount);
2854                }
2855            }
2856            mExpectingBetter.clear();
2857
2858            // Resolve the storage manager.
2859            mStorageManagerPackage = getStorageManagerPackageName();
2860
2861            // Resolve protected action filters. Only the setup wizard is allowed to
2862            // have a high priority filter for these actions.
2863            mSetupWizardPackage = getSetupWizardPackageName();
2864            if (mProtectedFilters.size() > 0) {
2865                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2866                    Slog.i(TAG, "No setup wizard;"
2867                        + " All protected intents capped to priority 0");
2868                }
2869                for (ActivityIntentInfo filter : mProtectedFilters) {
2870                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2871                        if (DEBUG_FILTERS) {
2872                            Slog.i(TAG, "Found setup wizard;"
2873                                + " allow priority " + filter.getPriority() + ";"
2874                                + " package: " + filter.activity.info.packageName
2875                                + " activity: " + filter.activity.className
2876                                + " priority: " + filter.getPriority());
2877                        }
2878                        // skip setup wizard; allow it to keep the high priority filter
2879                        continue;
2880                    }
2881                    if (DEBUG_FILTERS) {
2882                        Slog.i(TAG, "Protected action; cap priority to 0;"
2883                                + " package: " + filter.activity.info.packageName
2884                                + " activity: " + filter.activity.className
2885                                + " origPrio: " + filter.getPriority());
2886                    }
2887                    filter.setPriority(0);
2888                }
2889            }
2890            mDeferProtectedFilters = false;
2891            mProtectedFilters.clear();
2892
2893            // Now that we know all of the shared libraries, update all clients to have
2894            // the correct library paths.
2895            updateAllSharedLibrariesLPw(null);
2896
2897            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2898                // NOTE: We ignore potential failures here during a system scan (like
2899                // the rest of the commands above) because there's precious little we
2900                // can do about it. A settings error is reported, though.
2901                final List<String> changedAbiCodePath =
2902                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2903                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2904                    for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
2905                        final String codePathString = changedAbiCodePath.get(i);
2906                        try {
2907                            mInstaller.rmdex(codePathString,
2908                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2909                        } catch (InstallerException ignored) {
2910                        }
2911                    }
2912                }
2913            }
2914
2915            // Now that we know all the packages we are keeping,
2916            // read and update their last usage times.
2917            mPackageUsage.read(mPackages);
2918            mCompilerStats.read();
2919
2920            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2921                    SystemClock.uptimeMillis());
2922            Slog.i(TAG, "Time to scan packages: "
2923                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2924                    + " seconds");
2925
2926            // If the platform SDK has changed since the last time we booted,
2927            // we need to re-grant app permission to catch any new ones that
2928            // appear.  This is really a hack, and means that apps can in some
2929            // cases get permissions that the user didn't initially explicitly
2930            // allow...  it would be nice to have some better way to handle
2931            // this situation.
2932            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2933            if (sdkUpdated) {
2934                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2935                        + mSdkVersion + "; regranting permissions for internal storage");
2936            }
2937            mPermissionManager.updateAllPermissions(
2938                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2939                    mPermissionCallback);
2940            ver.sdkVersion = mSdkVersion;
2941
2942            // If this is the first boot or an update from pre-M, and it is a normal
2943            // boot, then we need to initialize the default preferred apps across
2944            // all defined users.
2945            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2946                for (UserInfo user : sUserManager.getUsers(true)) {
2947                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2948                    applyFactoryDefaultBrowserLPw(user.id);
2949                    primeDomainVerificationsLPw(user.id);
2950                }
2951            }
2952
2953            // Prepare storage for system user really early during boot,
2954            // since core system apps like SettingsProvider and SystemUI
2955            // can't wait for user to start
2956            final int storageFlags;
2957            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2958                storageFlags = StorageManager.FLAG_STORAGE_DE;
2959            } else {
2960                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2961            }
2962            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2963                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2964                    true /* onlyCoreApps */);
2965            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2966                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2967                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2968                traceLog.traceBegin("AppDataFixup");
2969                try {
2970                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2971                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2972                } catch (InstallerException e) {
2973                    Slog.w(TAG, "Trouble fixing GIDs", e);
2974                }
2975                traceLog.traceEnd();
2976
2977                traceLog.traceBegin("AppDataPrepare");
2978                if (deferPackages == null || deferPackages.isEmpty()) {
2979                    return;
2980                }
2981                int count = 0;
2982                for (String pkgName : deferPackages) {
2983                    PackageParser.Package pkg = null;
2984                    synchronized (mPackages) {
2985                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2986                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2987                            pkg = ps.pkg;
2988                        }
2989                    }
2990                    if (pkg != null) {
2991                        synchronized (mInstallLock) {
2992                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2993                                    true /* maybeMigrateAppData */);
2994                        }
2995                        count++;
2996                    }
2997                }
2998                traceLog.traceEnd();
2999                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3000            }, "prepareAppData");
3001
3002            // If this is first boot after an OTA, and a normal boot, then
3003            // we need to clear code cache directories.
3004            // Note that we do *not* clear the application profiles. These remain valid
3005            // across OTAs and are used to drive profile verification (post OTA) and
3006            // profile compilation (without waiting to collect a fresh set of profiles).
3007            if (mIsUpgrade && !onlyCore) {
3008                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3009                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3010                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3011                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3012                        // No apps are running this early, so no need to freeze
3013                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3014                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3015                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3016                    }
3017                }
3018                ver.fingerprint = Build.FINGERPRINT;
3019            }
3020
3021            checkDefaultBrowser();
3022
3023            // clear only after permissions and other defaults have been updated
3024            mExistingSystemPackages.clear();
3025            mPromoteSystemApps = false;
3026
3027            // All the changes are done during package scanning.
3028            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3029
3030            // can downgrade to reader
3031            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3032            mSettings.writeLPr();
3033            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3035                    SystemClock.uptimeMillis());
3036
3037            if (!mOnlyCore) {
3038                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3039                mRequiredInstallerPackage = getRequiredInstallerLPr();
3040                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3041                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3042                if (mIntentFilterVerifierComponent != null) {
3043                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3044                            mIntentFilterVerifierComponent);
3045                } else {
3046                    mIntentFilterVerifier = null;
3047                }
3048                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3049                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3050                        SharedLibraryInfo.VERSION_UNDEFINED);
3051                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3052                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3053                        SharedLibraryInfo.VERSION_UNDEFINED);
3054            } else {
3055                mRequiredVerifierPackage = null;
3056                mRequiredInstallerPackage = null;
3057                mRequiredUninstallerPackage = null;
3058                mIntentFilterVerifierComponent = null;
3059                mIntentFilterVerifier = null;
3060                mServicesSystemSharedLibraryPackageName = null;
3061                mSharedSystemSharedLibraryPackageName = null;
3062            }
3063
3064            mInstallerService = new PackageInstallerService(context, this);
3065            mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock);
3066            final Pair<ComponentName, String> instantAppResolverComponent =
3067                    getInstantAppResolverLPr();
3068            if (instantAppResolverComponent != null) {
3069                if (DEBUG_EPHEMERAL) {
3070                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3071                }
3072                mInstantAppResolverConnection = new EphemeralResolverConnection(
3073                        mContext, instantAppResolverComponent.first,
3074                        instantAppResolverComponent.second);
3075                mInstantAppResolverSettingsComponent =
3076                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3077            } else {
3078                mInstantAppResolverConnection = null;
3079                mInstantAppResolverSettingsComponent = null;
3080            }
3081            updateInstantAppInstallerLocked(null);
3082
3083            // Read and update the usage of dex files.
3084            // Do this at the end of PM init so that all the packages have their
3085            // data directory reconciled.
3086            // At this point we know the code paths of the packages, so we can validate
3087            // the disk file and build the internal cache.
3088            // The usage file is expected to be small so loading and verifying it
3089            // should take a fairly small time compare to the other activities (e.g. package
3090            // scanning).
3091            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3092            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3093            for (int userId : currentUserIds) {
3094                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3095            }
3096            mDexManager.load(userPackages);
3097            if (mIsUpgrade) {
3098                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3099                        (int) (SystemClock.uptimeMillis() - startTime));
3100            }
3101        } // synchronized (mPackages)
3102        } // synchronized (mInstallLock)
3103
3104        // Now after opening every single application zip, make sure they
3105        // are all flushed.  Not really needed, but keeps things nice and
3106        // tidy.
3107        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3108        Runtime.getRuntime().gc();
3109        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3110
3111        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3112        FallbackCategoryProvider.loadFallbacks();
3113        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3114
3115        // The initial scanning above does many calls into installd while
3116        // holding the mPackages lock, but we're mostly interested in yelling
3117        // once we have a booted system.
3118        mInstaller.setWarnIfHeld(mPackages);
3119
3120        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3121    }
3122
3123    /**
3124     * Uncompress and install stub applications.
3125     * <p>In order to save space on the system partition, some applications are shipped in a
3126     * compressed form. In addition the compressed bits for the full application, the
3127     * system image contains a tiny stub comprised of only the Android manifest.
3128     * <p>During the first boot, attempt to uncompress and install the full application. If
3129     * the application can't be installed for any reason, disable the stub and prevent
3130     * uncompressing the full application during future boots.
3131     * <p>In order to forcefully attempt an installation of a full application, go to app
3132     * settings and enable the application.
3133     */
3134    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3135        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3136            final String pkgName = stubSystemApps.get(i);
3137            // skip if the system package is already disabled
3138            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3139                stubSystemApps.remove(i);
3140                continue;
3141            }
3142            // skip if the package isn't installed (?!); this should never happen
3143            final PackageParser.Package pkg = mPackages.get(pkgName);
3144            if (pkg == null) {
3145                stubSystemApps.remove(i);
3146                continue;
3147            }
3148            // skip if the package has been disabled by the user
3149            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3150            if (ps != null) {
3151                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3152                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3153                    stubSystemApps.remove(i);
3154                    continue;
3155                }
3156            }
3157
3158            if (DEBUG_COMPRESSION) {
3159                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3160            }
3161
3162            // uncompress the binary to its eventual destination on /data
3163            final File scanFile = decompressPackage(pkg);
3164            if (scanFile == null) {
3165                continue;
3166            }
3167
3168            // install the package to replace the stub on /system
3169            try {
3170                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3171                removePackageLI(pkg, true /*chatty*/);
3172                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3173                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3174                        UserHandle.USER_SYSTEM, "android");
3175                stubSystemApps.remove(i);
3176                continue;
3177            } catch (PackageManagerException e) {
3178                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3179            }
3180
3181            // any failed attempt to install the package will be cleaned up later
3182        }
3183
3184        // disable any stub still left; these failed to install the full application
3185        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3186            final String pkgName = stubSystemApps.get(i);
3187            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3188            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3189                    UserHandle.USER_SYSTEM, "android");
3190            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3191        }
3192    }
3193
3194    /**
3195     * Decompresses the given package on the system image onto
3196     * the /data partition.
3197     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3198     */
3199    private File decompressPackage(PackageParser.Package pkg) {
3200        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3201        if (compressedFiles == null || compressedFiles.length == 0) {
3202            if (DEBUG_COMPRESSION) {
3203                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3204            }
3205            return null;
3206        }
3207        final File dstCodePath =
3208                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3209        int ret = PackageManager.INSTALL_SUCCEEDED;
3210        try {
3211            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3212            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3213            for (File srcFile : compressedFiles) {
3214                final String srcFileName = srcFile.getName();
3215                final String dstFileName = srcFileName.substring(
3216                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3217                final File dstFile = new File(dstCodePath, dstFileName);
3218                ret = decompressFile(srcFile, dstFile);
3219                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3220                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3221                            + "; pkg: " + pkg.packageName
3222                            + ", file: " + dstFileName);
3223                    break;
3224                }
3225            }
3226        } catch (ErrnoException e) {
3227            logCriticalInfo(Log.ERROR, "Failed to decompress"
3228                    + "; pkg: " + pkg.packageName
3229                    + ", err: " + e.errno);
3230        }
3231        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3232            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3233            NativeLibraryHelper.Handle handle = null;
3234            try {
3235                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3236                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3237                        null /*abiOverride*/);
3238            } catch (IOException e) {
3239                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3240                        + "; pkg: " + pkg.packageName);
3241                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3242            } finally {
3243                IoUtils.closeQuietly(handle);
3244            }
3245        }
3246        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3247            if (dstCodePath == null || !dstCodePath.exists()) {
3248                return null;
3249            }
3250            removeCodePathLI(dstCodePath);
3251            return null;
3252        }
3253
3254        return dstCodePath;
3255    }
3256
3257    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3258        // we're only interested in updating the installer appliction when 1) it's not
3259        // already set or 2) the modified package is the installer
3260        if (mInstantAppInstallerActivity != null
3261                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3262                        .equals(modifiedPackage)) {
3263            return;
3264        }
3265        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3266    }
3267
3268    private static File preparePackageParserCache(boolean isUpgrade) {
3269        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3270            return null;
3271        }
3272
3273        // Disable package parsing on eng builds to allow for faster incremental development.
3274        if (Build.IS_ENG) {
3275            return null;
3276        }
3277
3278        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3279            Slog.i(TAG, "Disabling package parser cache due to system property.");
3280            return null;
3281        }
3282
3283        // The base directory for the package parser cache lives under /data/system/.
3284        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3285                "package_cache");
3286        if (cacheBaseDir == null) {
3287            return null;
3288        }
3289
3290        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3291        // This also serves to "GC" unused entries when the package cache version changes (which
3292        // can only happen during upgrades).
3293        if (isUpgrade) {
3294            FileUtils.deleteContents(cacheBaseDir);
3295        }
3296
3297
3298        // Return the versioned package cache directory. This is something like
3299        // "/data/system/package_cache/1"
3300        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3301
3302        // The following is a workaround to aid development on non-numbered userdebug
3303        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3304        // the system partition is newer.
3305        //
3306        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3307        // that starts with "eng." to signify that this is an engineering build and not
3308        // destined for release.
3309        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3310            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3311
3312            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3313            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3314            // in general and should not be used for production changes. In this specific case,
3315            // we know that they will work.
3316            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3317            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3318                FileUtils.deleteContents(cacheBaseDir);
3319                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3320            }
3321        }
3322
3323        return cacheDir;
3324    }
3325
3326    @Override
3327    public boolean isFirstBoot() {
3328        // allow instant applications
3329        return mFirstBoot;
3330    }
3331
3332    @Override
3333    public boolean isOnlyCoreApps() {
3334        // allow instant applications
3335        return mOnlyCore;
3336    }
3337
3338    @Override
3339    public boolean isUpgrade() {
3340        // allow instant applications
3341        // The system property allows testing ota flow when upgraded to the same image.
3342        return mIsUpgrade || SystemProperties.getBoolean(
3343                "persist.pm.mock-upgrade", false /* default */);
3344    }
3345
3346    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3347        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3348
3349        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3350                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3351                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3352        if (matches.size() == 1) {
3353            return matches.get(0).getComponentInfo().packageName;
3354        } else if (matches.size() == 0) {
3355            Log.e(TAG, "There should probably be a verifier, but, none were found");
3356            return null;
3357        }
3358        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3359    }
3360
3361    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3362        synchronized (mPackages) {
3363            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3364            if (libraryEntry == null) {
3365                throw new IllegalStateException("Missing required shared library:" + name);
3366            }
3367            return libraryEntry.apk;
3368        }
3369    }
3370
3371    private @NonNull String getRequiredInstallerLPr() {
3372        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3373        intent.addCategory(Intent.CATEGORY_DEFAULT);
3374        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3375
3376        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3377                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3378                UserHandle.USER_SYSTEM);
3379        if (matches.size() == 1) {
3380            ResolveInfo resolveInfo = matches.get(0);
3381            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3382                throw new RuntimeException("The installer must be a privileged app");
3383            }
3384            return matches.get(0).getComponentInfo().packageName;
3385        } else {
3386            throw new RuntimeException("There must be exactly one installer; found " + matches);
3387        }
3388    }
3389
3390    private @NonNull String getRequiredUninstallerLPr() {
3391        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3392        intent.addCategory(Intent.CATEGORY_DEFAULT);
3393        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3394
3395        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3396                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3397                UserHandle.USER_SYSTEM);
3398        if (resolveInfo == null ||
3399                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3400            throw new RuntimeException("There must be exactly one uninstaller; found "
3401                    + resolveInfo);
3402        }
3403        return resolveInfo.getComponentInfo().packageName;
3404    }
3405
3406    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3407        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3408
3409        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3410                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3411                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3412        ResolveInfo best = null;
3413        final int N = matches.size();
3414        for (int i = 0; i < N; i++) {
3415            final ResolveInfo cur = matches.get(i);
3416            final String packageName = cur.getComponentInfo().packageName;
3417            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3418                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3419                continue;
3420            }
3421
3422            if (best == null || cur.priority > best.priority) {
3423                best = cur;
3424            }
3425        }
3426
3427        if (best != null) {
3428            return best.getComponentInfo().getComponentName();
3429        }
3430        Slog.w(TAG, "Intent filter verifier not found");
3431        return null;
3432    }
3433
3434    @Override
3435    public @Nullable ComponentName getInstantAppResolverComponent() {
3436        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3437            return null;
3438        }
3439        synchronized (mPackages) {
3440            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3441            if (instantAppResolver == null) {
3442                return null;
3443            }
3444            return instantAppResolver.first;
3445        }
3446    }
3447
3448    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3449        final String[] packageArray =
3450                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3451        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3452            if (DEBUG_EPHEMERAL) {
3453                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3454            }
3455            return null;
3456        }
3457
3458        final int callingUid = Binder.getCallingUid();
3459        final int resolveFlags =
3460                MATCH_DIRECT_BOOT_AWARE
3461                | MATCH_DIRECT_BOOT_UNAWARE
3462                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3463        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3464        final Intent resolverIntent = new Intent(actionName);
3465        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3466                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3467        // temporarily look for the old action
3468        if (resolvers.size() == 0) {
3469            if (DEBUG_EPHEMERAL) {
3470                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3471            }
3472            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3473            resolverIntent.setAction(actionName);
3474            resolvers = queryIntentServicesInternal(resolverIntent, null,
3475                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3476        }
3477        final int N = resolvers.size();
3478        if (N == 0) {
3479            if (DEBUG_EPHEMERAL) {
3480                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3481            }
3482            return null;
3483        }
3484
3485        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3486        for (int i = 0; i < N; i++) {
3487            final ResolveInfo info = resolvers.get(i);
3488
3489            if (info.serviceInfo == null) {
3490                continue;
3491            }
3492
3493            final String packageName = info.serviceInfo.packageName;
3494            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3495                if (DEBUG_EPHEMERAL) {
3496                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3497                            + " pkg: " + packageName + ", info:" + info);
3498                }
3499                continue;
3500            }
3501
3502            if (DEBUG_EPHEMERAL) {
3503                Slog.v(TAG, "Ephemeral resolver found;"
3504                        + " pkg: " + packageName + ", info:" + info);
3505            }
3506            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3507        }
3508        if (DEBUG_EPHEMERAL) {
3509            Slog.v(TAG, "Ephemeral resolver NOT found");
3510        }
3511        return null;
3512    }
3513
3514    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3515        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3516        intent.addCategory(Intent.CATEGORY_DEFAULT);
3517        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3518
3519        final int resolveFlags =
3520                MATCH_DIRECT_BOOT_AWARE
3521                | MATCH_DIRECT_BOOT_UNAWARE
3522                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3523        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3524                resolveFlags, UserHandle.USER_SYSTEM);
3525        // temporarily look for the old action
3526        if (matches.isEmpty()) {
3527            if (DEBUG_EPHEMERAL) {
3528                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3529            }
3530            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3531            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3532                    resolveFlags, UserHandle.USER_SYSTEM);
3533        }
3534        Iterator<ResolveInfo> iter = matches.iterator();
3535        while (iter.hasNext()) {
3536            final ResolveInfo rInfo = iter.next();
3537            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3538            if (ps != null) {
3539                final PermissionsState permissionsState = ps.getPermissionsState();
3540                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3541                    continue;
3542                }
3543            }
3544            iter.remove();
3545        }
3546        if (matches.size() == 0) {
3547            return null;
3548        } else if (matches.size() == 1) {
3549            return (ActivityInfo) matches.get(0).getComponentInfo();
3550        } else {
3551            throw new RuntimeException(
3552                    "There must be at most one ephemeral installer; found " + matches);
3553        }
3554    }
3555
3556    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3557            @NonNull ComponentName resolver) {
3558        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3559                .addCategory(Intent.CATEGORY_DEFAULT)
3560                .setPackage(resolver.getPackageName());
3561        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3562        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3563                UserHandle.USER_SYSTEM);
3564        // temporarily look for the old action
3565        if (matches.isEmpty()) {
3566            if (DEBUG_EPHEMERAL) {
3567                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3568            }
3569            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3570            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3571                    UserHandle.USER_SYSTEM);
3572        }
3573        if (matches.isEmpty()) {
3574            return null;
3575        }
3576        return matches.get(0).getComponentInfo().getComponentName();
3577    }
3578
3579    private void primeDomainVerificationsLPw(int userId) {
3580        if (DEBUG_DOMAIN_VERIFICATION) {
3581            Slog.d(TAG, "Priming domain verifications in user " + userId);
3582        }
3583
3584        SystemConfig systemConfig = SystemConfig.getInstance();
3585        ArraySet<String> packages = systemConfig.getLinkedApps();
3586
3587        for (String packageName : packages) {
3588            PackageParser.Package pkg = mPackages.get(packageName);
3589            if (pkg != null) {
3590                if (!pkg.isSystem()) {
3591                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3592                    continue;
3593                }
3594
3595                ArraySet<String> domains = null;
3596                for (PackageParser.Activity a : pkg.activities) {
3597                    for (ActivityIntentInfo filter : a.intents) {
3598                        if (hasValidDomains(filter)) {
3599                            if (domains == null) {
3600                                domains = new ArraySet<String>();
3601                            }
3602                            domains.addAll(filter.getHostsList());
3603                        }
3604                    }
3605                }
3606
3607                if (domains != null && domains.size() > 0) {
3608                    if (DEBUG_DOMAIN_VERIFICATION) {
3609                        Slog.v(TAG, "      + " + packageName);
3610                    }
3611                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3612                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3613                    // and then 'always' in the per-user state actually used for intent resolution.
3614                    final IntentFilterVerificationInfo ivi;
3615                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3616                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3617                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3618                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3619                } else {
3620                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3621                            + "' does not handle web links");
3622                }
3623            } else {
3624                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3625            }
3626        }
3627
3628        scheduleWritePackageRestrictionsLocked(userId);
3629        scheduleWriteSettingsLocked();
3630    }
3631
3632    private void applyFactoryDefaultBrowserLPw(int userId) {
3633        // The default browser app's package name is stored in a string resource,
3634        // with a product-specific overlay used for vendor customization.
3635        String browserPkg = mContext.getResources().getString(
3636                com.android.internal.R.string.default_browser);
3637        if (!TextUtils.isEmpty(browserPkg)) {
3638            // non-empty string => required to be a known package
3639            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3640            if (ps == null) {
3641                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3642                browserPkg = null;
3643            } else {
3644                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3645            }
3646        }
3647
3648        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3649        // default.  If there's more than one, just leave everything alone.
3650        if (browserPkg == null) {
3651            calculateDefaultBrowserLPw(userId);
3652        }
3653    }
3654
3655    private void calculateDefaultBrowserLPw(int userId) {
3656        List<String> allBrowsers = resolveAllBrowserApps(userId);
3657        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3658        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3659    }
3660
3661    private List<String> resolveAllBrowserApps(int userId) {
3662        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3663        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3664                PackageManager.MATCH_ALL, userId);
3665
3666        final int count = list.size();
3667        List<String> result = new ArrayList<String>(count);
3668        for (int i=0; i<count; i++) {
3669            ResolveInfo info = list.get(i);
3670            if (info.activityInfo == null
3671                    || !info.handleAllWebDataURI
3672                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3673                    || result.contains(info.activityInfo.packageName)) {
3674                continue;
3675            }
3676            result.add(info.activityInfo.packageName);
3677        }
3678
3679        return result;
3680    }
3681
3682    private boolean packageIsBrowser(String packageName, int userId) {
3683        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3684                PackageManager.MATCH_ALL, userId);
3685        final int N = list.size();
3686        for (int i = 0; i < N; i++) {
3687            ResolveInfo info = list.get(i);
3688            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3689                return true;
3690            }
3691        }
3692        return false;
3693    }
3694
3695    private void checkDefaultBrowser() {
3696        final int myUserId = UserHandle.myUserId();
3697        final String packageName = getDefaultBrowserPackageName(myUserId);
3698        if (packageName != null) {
3699            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3700            if (info == null) {
3701                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3702                synchronized (mPackages) {
3703                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3704                }
3705            }
3706        }
3707    }
3708
3709    @Override
3710    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3711            throws RemoteException {
3712        try {
3713            return super.onTransact(code, data, reply, flags);
3714        } catch (RuntimeException e) {
3715            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3716                Slog.wtf(TAG, "Package Manager Crash", e);
3717            }
3718            throw e;
3719        }
3720    }
3721
3722    static int[] appendInts(int[] cur, int[] add) {
3723        if (add == null) return cur;
3724        if (cur == null) return add;
3725        final int N = add.length;
3726        for (int i=0; i<N; i++) {
3727            cur = appendInt(cur, add[i]);
3728        }
3729        return cur;
3730    }
3731
3732    /**
3733     * Returns whether or not a full application can see an instant application.
3734     * <p>
3735     * Currently, there are three cases in which this can occur:
3736     * <ol>
3737     * <li>The calling application is a "special" process. Special processes
3738     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3739     * <li>The calling application has the permission
3740     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3741     * <li>The calling application is the default launcher on the
3742     *     system partition.</li>
3743     * </ol>
3744     */
3745    private boolean canViewInstantApps(int callingUid, int userId) {
3746        if (callingUid < Process.FIRST_APPLICATION_UID) {
3747            return true;
3748        }
3749        if (mContext.checkCallingOrSelfPermission(
3750                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3751            return true;
3752        }
3753        if (mContext.checkCallingOrSelfPermission(
3754                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3755            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3756            if (homeComponent != null
3757                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3758                return true;
3759            }
3760        }
3761        return false;
3762    }
3763
3764    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3765        if (!sUserManager.exists(userId)) return null;
3766        if (ps == null) {
3767            return null;
3768        }
3769        PackageParser.Package p = ps.pkg;
3770        if (p == null) {
3771            return null;
3772        }
3773        final int callingUid = Binder.getCallingUid();
3774        // Filter out ephemeral app metadata:
3775        //   * The system/shell/root can see metadata for any app
3776        //   * An installed app can see metadata for 1) other installed apps
3777        //     and 2) ephemeral apps that have explicitly interacted with it
3778        //   * Ephemeral apps can only see their own data and exposed installed apps
3779        //   * Holding a signature permission allows seeing instant apps
3780        if (filterAppAccessLPr(ps, callingUid, userId)) {
3781            return null;
3782        }
3783
3784        final PermissionsState permissionsState = ps.getPermissionsState();
3785
3786        // Compute GIDs only if requested
3787        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3788                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3789        // Compute granted permissions only if package has requested permissions
3790        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3791                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3792        final PackageUserState state = ps.readUserState(userId);
3793
3794        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3795                && ps.isSystem()) {
3796            flags |= MATCH_ANY_USER;
3797        }
3798
3799        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3800                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3801
3802        if (packageInfo == null) {
3803            return null;
3804        }
3805
3806        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3807                resolveExternalPackageNameLPr(p);
3808
3809        return packageInfo;
3810    }
3811
3812    @Override
3813    public void checkPackageStartable(String packageName, int userId) {
3814        final int callingUid = Binder.getCallingUid();
3815        if (getInstantAppPackageName(callingUid) != null) {
3816            throw new SecurityException("Instant applications don't have access to this method");
3817        }
3818        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3819        synchronized (mPackages) {
3820            final PackageSetting ps = mSettings.mPackages.get(packageName);
3821            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3822                throw new SecurityException("Package " + packageName + " was not found!");
3823            }
3824
3825            if (!ps.getInstalled(userId)) {
3826                throw new SecurityException(
3827                        "Package " + packageName + " was not installed for user " + userId + "!");
3828            }
3829
3830            if (mSafeMode && !ps.isSystem()) {
3831                throw new SecurityException("Package " + packageName + " not a system app!");
3832            }
3833
3834            if (mFrozenPackages.contains(packageName)) {
3835                throw new SecurityException("Package " + packageName + " is currently frozen!");
3836            }
3837
3838            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3839                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3840            }
3841        }
3842    }
3843
3844    @Override
3845    public boolean isPackageAvailable(String packageName, int userId) {
3846        if (!sUserManager.exists(userId)) return false;
3847        final int callingUid = Binder.getCallingUid();
3848        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3849                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3850        synchronized (mPackages) {
3851            PackageParser.Package p = mPackages.get(packageName);
3852            if (p != null) {
3853                final PackageSetting ps = (PackageSetting) p.mExtras;
3854                if (filterAppAccessLPr(ps, callingUid, userId)) {
3855                    return false;
3856                }
3857                if (ps != null) {
3858                    final PackageUserState state = ps.readUserState(userId);
3859                    if (state != null) {
3860                        return PackageParser.isAvailable(state);
3861                    }
3862                }
3863            }
3864        }
3865        return false;
3866    }
3867
3868    @Override
3869    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3870        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3871                flags, Binder.getCallingUid(), userId);
3872    }
3873
3874    @Override
3875    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3876            int flags, int userId) {
3877        return getPackageInfoInternal(versionedPackage.getPackageName(),
3878                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3879    }
3880
3881    /**
3882     * Important: The provided filterCallingUid is used exclusively to filter out packages
3883     * that can be seen based on user state. It's typically the original caller uid prior
3884     * to clearing. Because it can only be provided by trusted code, it's value can be
3885     * trusted and will be used as-is; unlike userId which will be validated by this method.
3886     */
3887    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3888            int flags, int filterCallingUid, int userId) {
3889        if (!sUserManager.exists(userId)) return null;
3890        flags = updateFlagsForPackage(flags, userId, packageName);
3891        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3892                false /* requireFullPermission */, false /* checkShell */, "get package info");
3893
3894        // reader
3895        synchronized (mPackages) {
3896            // Normalize package name to handle renamed packages and static libs
3897            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3898
3899            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3900            if (matchFactoryOnly) {
3901                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3902                if (ps != null) {
3903                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3904                        return null;
3905                    }
3906                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3907                        return null;
3908                    }
3909                    return generatePackageInfo(ps, flags, userId);
3910                }
3911            }
3912
3913            PackageParser.Package p = mPackages.get(packageName);
3914            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3915                return null;
3916            }
3917            if (DEBUG_PACKAGE_INFO)
3918                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3919            if (p != null) {
3920                final PackageSetting ps = (PackageSetting) p.mExtras;
3921                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3922                    return null;
3923                }
3924                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3925                    return null;
3926                }
3927                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3928            }
3929            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3930                final PackageSetting ps = mSettings.mPackages.get(packageName);
3931                if (ps == null) return null;
3932                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3933                    return null;
3934                }
3935                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3936                    return null;
3937                }
3938                return generatePackageInfo(ps, flags, userId);
3939            }
3940        }
3941        return null;
3942    }
3943
3944    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3945        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3946            return true;
3947        }
3948        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3949            return true;
3950        }
3951        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3952            return true;
3953        }
3954        return false;
3955    }
3956
3957    private boolean isComponentVisibleToInstantApp(
3958            @Nullable ComponentName component, @ComponentType int type) {
3959        if (type == TYPE_ACTIVITY) {
3960            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3961            return activity != null
3962                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3963                    : false;
3964        } else if (type == TYPE_RECEIVER) {
3965            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3966            return activity != null
3967                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3968                    : false;
3969        } else if (type == TYPE_SERVICE) {
3970            final PackageParser.Service service = mServices.mServices.get(component);
3971            return service != null
3972                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3973                    : false;
3974        } else if (type == TYPE_PROVIDER) {
3975            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3976            return provider != null
3977                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3978                    : false;
3979        } else if (type == TYPE_UNKNOWN) {
3980            return isComponentVisibleToInstantApp(component);
3981        }
3982        return false;
3983    }
3984
3985    /**
3986     * Returns whether or not access to the application should be filtered.
3987     * <p>
3988     * Access may be limited based upon whether the calling or target applications
3989     * are instant applications.
3990     *
3991     * @see #canAccessInstantApps(int)
3992     */
3993    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3994            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3995        // if we're in an isolated process, get the real calling UID
3996        if (Process.isIsolated(callingUid)) {
3997            callingUid = mIsolatedOwners.get(callingUid);
3998        }
3999        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4000        final boolean callerIsInstantApp = instantAppPkgName != null;
4001        if (ps == null) {
4002            if (callerIsInstantApp) {
4003                // pretend the application exists, but, needs to be filtered
4004                return true;
4005            }
4006            return false;
4007        }
4008        // if the target and caller are the same application, don't filter
4009        if (isCallerSameApp(ps.name, callingUid)) {
4010            return false;
4011        }
4012        if (callerIsInstantApp) {
4013            // request for a specific component; if it hasn't been explicitly exposed, filter
4014            if (component != null) {
4015                return !isComponentVisibleToInstantApp(component, componentType);
4016            }
4017            // request for application; if no components have been explicitly exposed, filter
4018            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4019        }
4020        if (ps.getInstantApp(userId)) {
4021            // caller can see all components of all instant applications, don't filter
4022            if (canViewInstantApps(callingUid, userId)) {
4023                return false;
4024            }
4025            // request for a specific instant application component, filter
4026            if (component != null) {
4027                return true;
4028            }
4029            // request for an instant application; if the caller hasn't been granted access, filter
4030            return !mInstantAppRegistry.isInstantAccessGranted(
4031                    userId, UserHandle.getAppId(callingUid), ps.appId);
4032        }
4033        return false;
4034    }
4035
4036    /**
4037     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4038     */
4039    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4040        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4041    }
4042
4043    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4044            int flags) {
4045        // Callers can access only the libs they depend on, otherwise they need to explicitly
4046        // ask for the shared libraries given the caller is allowed to access all static libs.
4047        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4048            // System/shell/root get to see all static libs
4049            final int appId = UserHandle.getAppId(uid);
4050            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4051                    || appId == Process.ROOT_UID) {
4052                return false;
4053            }
4054        }
4055
4056        // No package means no static lib as it is always on internal storage
4057        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4058            return false;
4059        }
4060
4061        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4062                ps.pkg.staticSharedLibVersion);
4063        if (libEntry == null) {
4064            return false;
4065        }
4066
4067        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4068        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4069        if (uidPackageNames == null) {
4070            return true;
4071        }
4072
4073        for (String uidPackageName : uidPackageNames) {
4074            if (ps.name.equals(uidPackageName)) {
4075                return false;
4076            }
4077            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4078            if (uidPs != null) {
4079                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4080                        libEntry.info.getName());
4081                if (index < 0) {
4082                    continue;
4083                }
4084                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4085                    return false;
4086                }
4087            }
4088        }
4089        return true;
4090    }
4091
4092    @Override
4093    public String[] currentToCanonicalPackageNames(String[] names) {
4094        final int callingUid = Binder.getCallingUid();
4095        if (getInstantAppPackageName(callingUid) != null) {
4096            return names;
4097        }
4098        final String[] out = new String[names.length];
4099        // reader
4100        synchronized (mPackages) {
4101            final int callingUserId = UserHandle.getUserId(callingUid);
4102            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4103            for (int i=names.length-1; i>=0; i--) {
4104                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4105                boolean translateName = false;
4106                if (ps != null && ps.realName != null) {
4107                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4108                    translateName = !targetIsInstantApp
4109                            || canViewInstantApps
4110                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4111                                    UserHandle.getAppId(callingUid), ps.appId);
4112                }
4113                out[i] = translateName ? ps.realName : names[i];
4114            }
4115        }
4116        return out;
4117    }
4118
4119    @Override
4120    public String[] canonicalToCurrentPackageNames(String[] names) {
4121        final int callingUid = Binder.getCallingUid();
4122        if (getInstantAppPackageName(callingUid) != null) {
4123            return names;
4124        }
4125        final String[] out = new String[names.length];
4126        // reader
4127        synchronized (mPackages) {
4128            final int callingUserId = UserHandle.getUserId(callingUid);
4129            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4130            for (int i=names.length-1; i>=0; i--) {
4131                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4132                boolean translateName = false;
4133                if (cur != null) {
4134                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4135                    final boolean targetIsInstantApp =
4136                            ps != null && ps.getInstantApp(callingUserId);
4137                    translateName = !targetIsInstantApp
4138                            || canViewInstantApps
4139                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4140                                    UserHandle.getAppId(callingUid), ps.appId);
4141                }
4142                out[i] = translateName ? cur : names[i];
4143            }
4144        }
4145        return out;
4146    }
4147
4148    @Override
4149    public int getPackageUid(String packageName, int flags, int userId) {
4150        if (!sUserManager.exists(userId)) return -1;
4151        final int callingUid = Binder.getCallingUid();
4152        flags = updateFlagsForPackage(flags, userId, packageName);
4153        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4154                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4155
4156        // reader
4157        synchronized (mPackages) {
4158            final PackageParser.Package p = mPackages.get(packageName);
4159            if (p != null && p.isMatch(flags)) {
4160                PackageSetting ps = (PackageSetting) p.mExtras;
4161                if (filterAppAccessLPr(ps, callingUid, userId)) {
4162                    return -1;
4163                }
4164                return UserHandle.getUid(userId, p.applicationInfo.uid);
4165            }
4166            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4167                final PackageSetting ps = mSettings.mPackages.get(packageName);
4168                if (ps != null && ps.isMatch(flags)
4169                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4170                    return UserHandle.getUid(userId, ps.appId);
4171                }
4172            }
4173        }
4174
4175        return -1;
4176    }
4177
4178    @Override
4179    public int[] getPackageGids(String packageName, int flags, int userId) {
4180        if (!sUserManager.exists(userId)) return null;
4181        final int callingUid = Binder.getCallingUid();
4182        flags = updateFlagsForPackage(flags, userId, packageName);
4183        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4184                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4185
4186        // reader
4187        synchronized (mPackages) {
4188            final PackageParser.Package p = mPackages.get(packageName);
4189            if (p != null && p.isMatch(flags)) {
4190                PackageSetting ps = (PackageSetting) p.mExtras;
4191                if (filterAppAccessLPr(ps, callingUid, userId)) {
4192                    return null;
4193                }
4194                // TODO: Shouldn't this be checking for package installed state for userId and
4195                // return null?
4196                return ps.getPermissionsState().computeGids(userId);
4197            }
4198            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4199                final PackageSetting ps = mSettings.mPackages.get(packageName);
4200                if (ps != null && ps.isMatch(flags)
4201                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4202                    return ps.getPermissionsState().computeGids(userId);
4203                }
4204            }
4205        }
4206
4207        return null;
4208    }
4209
4210    @Override
4211    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4212        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4213    }
4214
4215    @Override
4216    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4217            int flags) {
4218        final List<PermissionInfo> permissionList =
4219                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4220        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4221    }
4222
4223    @Override
4224    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4225        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4226    }
4227
4228    @Override
4229    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4230        final List<PermissionGroupInfo> permissionList =
4231                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4232        return (permissionList == null)
4233                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4234    }
4235
4236    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4237            int filterCallingUid, int userId) {
4238        if (!sUserManager.exists(userId)) return null;
4239        PackageSetting ps = mSettings.mPackages.get(packageName);
4240        if (ps != null) {
4241            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4242                return null;
4243            }
4244            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4245                return null;
4246            }
4247            if (ps.pkg == null) {
4248                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4249                if (pInfo != null) {
4250                    return pInfo.applicationInfo;
4251                }
4252                return null;
4253            }
4254            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4255                    ps.readUserState(userId), userId);
4256            if (ai != null) {
4257                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4258            }
4259            return ai;
4260        }
4261        return null;
4262    }
4263
4264    @Override
4265    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4266        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4267    }
4268
4269    /**
4270     * Important: The provided filterCallingUid is used exclusively to filter out applications
4271     * that can be seen based on user state. It's typically the original caller uid prior
4272     * to clearing. Because it can only be provided by trusted code, it's value can be
4273     * trusted and will be used as-is; unlike userId which will be validated by this method.
4274     */
4275    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4276            int filterCallingUid, int userId) {
4277        if (!sUserManager.exists(userId)) return null;
4278        flags = updateFlagsForApplication(flags, userId, packageName);
4279        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4280                false /* requireFullPermission */, false /* checkShell */, "get application info");
4281
4282        // writer
4283        synchronized (mPackages) {
4284            // Normalize package name to handle renamed packages and static libs
4285            packageName = resolveInternalPackageNameLPr(packageName,
4286                    PackageManager.VERSION_CODE_HIGHEST);
4287
4288            PackageParser.Package p = mPackages.get(packageName);
4289            if (DEBUG_PACKAGE_INFO) Log.v(
4290                    TAG, "getApplicationInfo " + packageName
4291                    + ": " + p);
4292            if (p != null) {
4293                PackageSetting ps = mSettings.mPackages.get(packageName);
4294                if (ps == null) return null;
4295                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4296                    return null;
4297                }
4298                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4299                    return null;
4300                }
4301                // Note: isEnabledLP() does not apply here - always return info
4302                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4303                        p, flags, ps.readUserState(userId), userId);
4304                if (ai != null) {
4305                    ai.packageName = resolveExternalPackageNameLPr(p);
4306                }
4307                return ai;
4308            }
4309            if ("android".equals(packageName)||"system".equals(packageName)) {
4310                return mAndroidApplication;
4311            }
4312            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4313                // Already generates the external package name
4314                return generateApplicationInfoFromSettingsLPw(packageName,
4315                        flags, filterCallingUid, userId);
4316            }
4317        }
4318        return null;
4319    }
4320
4321    private String normalizePackageNameLPr(String packageName) {
4322        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4323        return normalizedPackageName != null ? normalizedPackageName : packageName;
4324    }
4325
4326    @Override
4327    public void deletePreloadsFileCache() {
4328        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4329            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4330        }
4331        File dir = Environment.getDataPreloadsFileCacheDirectory();
4332        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4333        FileUtils.deleteContents(dir);
4334    }
4335
4336    @Override
4337    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4338            final int storageFlags, final IPackageDataObserver observer) {
4339        mContext.enforceCallingOrSelfPermission(
4340                android.Manifest.permission.CLEAR_APP_CACHE, null);
4341        mHandler.post(() -> {
4342            boolean success = false;
4343            try {
4344                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4345                success = true;
4346            } catch (IOException e) {
4347                Slog.w(TAG, e);
4348            }
4349            if (observer != null) {
4350                try {
4351                    observer.onRemoveCompleted(null, success);
4352                } catch (RemoteException e) {
4353                    Slog.w(TAG, e);
4354                }
4355            }
4356        });
4357    }
4358
4359    @Override
4360    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4361            final int storageFlags, final IntentSender pi) {
4362        mContext.enforceCallingOrSelfPermission(
4363                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4364        mHandler.post(() -> {
4365            boolean success = false;
4366            try {
4367                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4368                success = true;
4369            } catch (IOException e) {
4370                Slog.w(TAG, e);
4371            }
4372            if (pi != null) {
4373                try {
4374                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4375                } catch (SendIntentException e) {
4376                    Slog.w(TAG, e);
4377                }
4378            }
4379        });
4380    }
4381
4382    /**
4383     * Blocking call to clear various types of cached data across the system
4384     * until the requested bytes are available.
4385     */
4386    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4387        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4388        final File file = storage.findPathForUuid(volumeUuid);
4389        if (file.getUsableSpace() >= bytes) return;
4390
4391        if (ENABLE_FREE_CACHE_V2) {
4392            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4393                    volumeUuid);
4394            final boolean aggressive = (storageFlags
4395                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4396            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4397
4398            // 1. Pre-flight to determine if we have any chance to succeed
4399            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4400            if (internalVolume && (aggressive || SystemProperties
4401                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4402                deletePreloadsFileCache();
4403                if (file.getUsableSpace() >= bytes) return;
4404            }
4405
4406            // 3. Consider parsed APK data (aggressive only)
4407            if (internalVolume && aggressive) {
4408                FileUtils.deleteContents(mCacheDir);
4409                if (file.getUsableSpace() >= bytes) return;
4410            }
4411
4412            // 4. Consider cached app data (above quotas)
4413            try {
4414                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4415                        Installer.FLAG_FREE_CACHE_V2);
4416            } catch (InstallerException ignored) {
4417            }
4418            if (file.getUsableSpace() >= bytes) return;
4419
4420            // 5. Consider shared libraries with refcount=0 and age>min cache period
4421            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4422                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4423                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4424                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4425                return;
4426            }
4427
4428            // 6. Consider dexopt output (aggressive only)
4429            // TODO: Implement
4430
4431            // 7. Consider installed instant apps unused longer than min cache period
4432            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4433                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4434                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4435                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4436                return;
4437            }
4438
4439            // 8. Consider cached app data (below quotas)
4440            try {
4441                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4442                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4443            } catch (InstallerException ignored) {
4444            }
4445            if (file.getUsableSpace() >= bytes) return;
4446
4447            // 9. Consider DropBox entries
4448            // TODO: Implement
4449
4450            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4451            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4452                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4453                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4454                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4455                return;
4456            }
4457        } else {
4458            try {
4459                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4460            } catch (InstallerException ignored) {
4461            }
4462            if (file.getUsableSpace() >= bytes) return;
4463        }
4464
4465        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4466    }
4467
4468    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4469            throws IOException {
4470        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4471        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4472
4473        List<VersionedPackage> packagesToDelete = null;
4474        final long now = System.currentTimeMillis();
4475
4476        synchronized (mPackages) {
4477            final int[] allUsers = sUserManager.getUserIds();
4478            final int libCount = mSharedLibraries.size();
4479            for (int i = 0; i < libCount; i++) {
4480                final LongSparseArray<SharedLibraryEntry> versionedLib
4481                        = mSharedLibraries.valueAt(i);
4482                if (versionedLib == null) {
4483                    continue;
4484                }
4485                final int versionCount = versionedLib.size();
4486                for (int j = 0; j < versionCount; j++) {
4487                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4488                    // Skip packages that are not static shared libs.
4489                    if (!libInfo.isStatic()) {
4490                        break;
4491                    }
4492                    // Important: We skip static shared libs used for some user since
4493                    // in such a case we need to keep the APK on the device. The check for
4494                    // a lib being used for any user is performed by the uninstall call.
4495                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4496                    // Resolve the package name - we use synthetic package names internally
4497                    final String internalPackageName = resolveInternalPackageNameLPr(
4498                            declaringPackage.getPackageName(),
4499                            declaringPackage.getLongVersionCode());
4500                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4501                    // Skip unused static shared libs cached less than the min period
4502                    // to prevent pruning a lib needed by a subsequently installed package.
4503                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4504                        continue;
4505                    }
4506                    if (packagesToDelete == null) {
4507                        packagesToDelete = new ArrayList<>();
4508                    }
4509                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4510                            declaringPackage.getLongVersionCode()));
4511                }
4512            }
4513        }
4514
4515        if (packagesToDelete != null) {
4516            final int packageCount = packagesToDelete.size();
4517            for (int i = 0; i < packageCount; i++) {
4518                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4519                // Delete the package synchronously (will fail of the lib used for any user).
4520                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4521                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4522                                == PackageManager.DELETE_SUCCEEDED) {
4523                    if (volume.getUsableSpace() >= neededSpace) {
4524                        return true;
4525                    }
4526                }
4527            }
4528        }
4529
4530        return false;
4531    }
4532
4533    /**
4534     * Update given flags based on encryption status of current user.
4535     */
4536    private int updateFlags(int flags, int userId) {
4537        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4538                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4539            // Caller expressed an explicit opinion about what encryption
4540            // aware/unaware components they want to see, so fall through and
4541            // give them what they want
4542        } else {
4543            // Caller expressed no opinion, so match based on user state
4544            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4545                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4546            } else {
4547                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4548            }
4549        }
4550        return flags;
4551    }
4552
4553    private UserManagerInternal getUserManagerInternal() {
4554        if (mUserManagerInternal == null) {
4555            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4556        }
4557        return mUserManagerInternal;
4558    }
4559
4560    private DeviceIdleController.LocalService getDeviceIdleController() {
4561        if (mDeviceIdleController == null) {
4562            mDeviceIdleController =
4563                    LocalServices.getService(DeviceIdleController.LocalService.class);
4564        }
4565        return mDeviceIdleController;
4566    }
4567
4568    /**
4569     * Update given flags when being used to request {@link PackageInfo}.
4570     */
4571    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4572        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4573        boolean triaged = true;
4574        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4575                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4576            // Caller is asking for component details, so they'd better be
4577            // asking for specific encryption matching behavior, or be triaged
4578            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4579                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4580                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4581                triaged = false;
4582            }
4583        }
4584        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4585                | PackageManager.MATCH_SYSTEM_ONLY
4586                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4587            triaged = false;
4588        }
4589        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4590            mPermissionManager.enforceCrossUserPermission(
4591                    Binder.getCallingUid(), userId, false, false,
4592                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4593                    + Debug.getCallers(5));
4594        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4595                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4596            // If the caller wants all packages and has a restricted profile associated with it,
4597            // then match all users. This is to make sure that launchers that need to access work
4598            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4599            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4600            flags |= PackageManager.MATCH_ANY_USER;
4601        }
4602        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4603            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4604                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4605        }
4606        return updateFlags(flags, userId);
4607    }
4608
4609    /**
4610     * Update given flags when being used to request {@link ApplicationInfo}.
4611     */
4612    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4613        return updateFlagsForPackage(flags, userId, cookie);
4614    }
4615
4616    /**
4617     * Update given flags when being used to request {@link ComponentInfo}.
4618     */
4619    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4620        if (cookie instanceof Intent) {
4621            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4622                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4623            }
4624        }
4625
4626        boolean triaged = true;
4627        // Caller is asking for component details, so they'd better be
4628        // asking for specific encryption matching behavior, or be triaged
4629        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4630                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4631                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4632            triaged = false;
4633        }
4634        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4635            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4636                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4637        }
4638
4639        return updateFlags(flags, userId);
4640    }
4641
4642    /**
4643     * Update given intent when being used to request {@link ResolveInfo}.
4644     */
4645    private Intent updateIntentForResolve(Intent intent) {
4646        if (intent.getSelector() != null) {
4647            intent = intent.getSelector();
4648        }
4649        if (DEBUG_PREFERRED) {
4650            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4651        }
4652        return intent;
4653    }
4654
4655    /**
4656     * Update given flags when being used to request {@link ResolveInfo}.
4657     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4658     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4659     * flag set. However, this flag is only honoured in three circumstances:
4660     * <ul>
4661     * <li>when called from a system process</li>
4662     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4663     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4664     * action and a {@code android.intent.category.BROWSABLE} category</li>
4665     * </ul>
4666     */
4667    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4668        return updateFlagsForResolve(flags, userId, intent, callingUid,
4669                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4670    }
4671    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4672            boolean wantInstantApps) {
4673        return updateFlagsForResolve(flags, userId, intent, callingUid,
4674                wantInstantApps, false /*onlyExposedExplicitly*/);
4675    }
4676    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4677            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4678        // Safe mode means we shouldn't match any third-party components
4679        if (mSafeMode) {
4680            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4681        }
4682        if (getInstantAppPackageName(callingUid) != null) {
4683            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4684            if (onlyExposedExplicitly) {
4685                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4686            }
4687            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4688            flags |= PackageManager.MATCH_INSTANT;
4689        } else {
4690            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4691            final boolean allowMatchInstant =
4692                    (wantInstantApps
4693                            && Intent.ACTION_VIEW.equals(intent.getAction())
4694                            && hasWebURI(intent))
4695                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4696            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4697                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4698            if (!allowMatchInstant) {
4699                flags &= ~PackageManager.MATCH_INSTANT;
4700            }
4701        }
4702        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4703    }
4704
4705    @Override
4706    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4707        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4708    }
4709
4710    /**
4711     * Important: The provided filterCallingUid is used exclusively to filter out activities
4712     * that can be seen based on user state. It's typically the original caller uid prior
4713     * to clearing. Because it can only be provided by trusted code, it's value can be
4714     * trusted and will be used as-is; unlike userId which will be validated by this method.
4715     */
4716    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4717            int filterCallingUid, int userId) {
4718        if (!sUserManager.exists(userId)) return null;
4719        flags = updateFlagsForComponent(flags, userId, component);
4720        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4721                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4722        synchronized (mPackages) {
4723            PackageParser.Activity a = mActivities.mActivities.get(component);
4724
4725            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4726            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4727                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4728                if (ps == null) return null;
4729                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4730                    return null;
4731                }
4732                return PackageParser.generateActivityInfo(
4733                        a, flags, ps.readUserState(userId), userId);
4734            }
4735            if (mResolveComponentName.equals(component)) {
4736                return PackageParser.generateActivityInfo(
4737                        mResolveActivity, flags, new PackageUserState(), userId);
4738            }
4739        }
4740        return null;
4741    }
4742
4743    @Override
4744    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4745            String resolvedType) {
4746        synchronized (mPackages) {
4747            if (component.equals(mResolveComponentName)) {
4748                // The resolver supports EVERYTHING!
4749                return true;
4750            }
4751            final int callingUid = Binder.getCallingUid();
4752            final int callingUserId = UserHandle.getUserId(callingUid);
4753            PackageParser.Activity a = mActivities.mActivities.get(component);
4754            if (a == null) {
4755                return false;
4756            }
4757            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4758            if (ps == null) {
4759                return false;
4760            }
4761            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4762                return false;
4763            }
4764            for (int i=0; i<a.intents.size(); i++) {
4765                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4766                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4767                    return true;
4768                }
4769            }
4770            return false;
4771        }
4772    }
4773
4774    @Override
4775    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4776        if (!sUserManager.exists(userId)) return null;
4777        final int callingUid = Binder.getCallingUid();
4778        flags = updateFlagsForComponent(flags, userId, component);
4779        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4780                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4781        synchronized (mPackages) {
4782            PackageParser.Activity a = mReceivers.mActivities.get(component);
4783            if (DEBUG_PACKAGE_INFO) Log.v(
4784                TAG, "getReceiverInfo " + component + ": " + a);
4785            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4786                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4787                if (ps == null) return null;
4788                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4789                    return null;
4790                }
4791                return PackageParser.generateActivityInfo(
4792                        a, flags, ps.readUserState(userId), userId);
4793            }
4794        }
4795        return null;
4796    }
4797
4798    @Override
4799    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4800            int flags, int userId) {
4801        if (!sUserManager.exists(userId)) return null;
4802        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4803        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4804            return null;
4805        }
4806
4807        flags = updateFlagsForPackage(flags, userId, null);
4808
4809        final boolean canSeeStaticLibraries =
4810                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4811                        == PERMISSION_GRANTED
4812                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4813                        == PERMISSION_GRANTED
4814                || canRequestPackageInstallsInternal(packageName,
4815                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4816                        false  /* throwIfPermNotDeclared*/)
4817                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4818                        == PERMISSION_GRANTED;
4819
4820        synchronized (mPackages) {
4821            List<SharedLibraryInfo> result = null;
4822
4823            final int libCount = mSharedLibraries.size();
4824            for (int i = 0; i < libCount; i++) {
4825                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4826                if (versionedLib == null) {
4827                    continue;
4828                }
4829
4830                final int versionCount = versionedLib.size();
4831                for (int j = 0; j < versionCount; j++) {
4832                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4833                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4834                        break;
4835                    }
4836                    final long identity = Binder.clearCallingIdentity();
4837                    try {
4838                        PackageInfo packageInfo = getPackageInfoVersioned(
4839                                libInfo.getDeclaringPackage(), flags
4840                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4841                        if (packageInfo == null) {
4842                            continue;
4843                        }
4844                    } finally {
4845                        Binder.restoreCallingIdentity(identity);
4846                    }
4847
4848                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4849                            libInfo.getLongVersion(), libInfo.getType(),
4850                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4851                            flags, userId));
4852
4853                    if (result == null) {
4854                        result = new ArrayList<>();
4855                    }
4856                    result.add(resLibInfo);
4857                }
4858            }
4859
4860            return result != null ? new ParceledListSlice<>(result) : null;
4861        }
4862    }
4863
4864    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4865            SharedLibraryInfo libInfo, int flags, int userId) {
4866        List<VersionedPackage> versionedPackages = null;
4867        final int packageCount = mSettings.mPackages.size();
4868        for (int i = 0; i < packageCount; i++) {
4869            PackageSetting ps = mSettings.mPackages.valueAt(i);
4870
4871            if (ps == null) {
4872                continue;
4873            }
4874
4875            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4876                continue;
4877            }
4878
4879            final String libName = libInfo.getName();
4880            if (libInfo.isStatic()) {
4881                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4882                if (libIdx < 0) {
4883                    continue;
4884                }
4885                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4886                    continue;
4887                }
4888                if (versionedPackages == null) {
4889                    versionedPackages = new ArrayList<>();
4890                }
4891                // If the dependent is a static shared lib, use the public package name
4892                String dependentPackageName = ps.name;
4893                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4894                    dependentPackageName = ps.pkg.manifestPackageName;
4895                }
4896                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4897            } else if (ps.pkg != null) {
4898                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4899                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4900                    if (versionedPackages == null) {
4901                        versionedPackages = new ArrayList<>();
4902                    }
4903                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4904                }
4905            }
4906        }
4907
4908        return versionedPackages;
4909    }
4910
4911    @Override
4912    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4913        if (!sUserManager.exists(userId)) return null;
4914        final int callingUid = Binder.getCallingUid();
4915        flags = updateFlagsForComponent(flags, userId, component);
4916        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4917                false /* requireFullPermission */, false /* checkShell */, "get service info");
4918        synchronized (mPackages) {
4919            PackageParser.Service s = mServices.mServices.get(component);
4920            if (DEBUG_PACKAGE_INFO) Log.v(
4921                TAG, "getServiceInfo " + component + ": " + s);
4922            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4923                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4924                if (ps == null) return null;
4925                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4926                    return null;
4927                }
4928                return PackageParser.generateServiceInfo(
4929                        s, flags, ps.readUserState(userId), userId);
4930            }
4931        }
4932        return null;
4933    }
4934
4935    @Override
4936    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4937        if (!sUserManager.exists(userId)) return null;
4938        final int callingUid = Binder.getCallingUid();
4939        flags = updateFlagsForComponent(flags, userId, component);
4940        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4941                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4942        synchronized (mPackages) {
4943            PackageParser.Provider p = mProviders.mProviders.get(component);
4944            if (DEBUG_PACKAGE_INFO) Log.v(
4945                TAG, "getProviderInfo " + component + ": " + p);
4946            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4947                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4948                if (ps == null) return null;
4949                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4950                    return null;
4951                }
4952                return PackageParser.generateProviderInfo(
4953                        p, flags, ps.readUserState(userId), userId);
4954            }
4955        }
4956        return null;
4957    }
4958
4959    @Override
4960    public String[] getSystemSharedLibraryNames() {
4961        // allow instant applications
4962        synchronized (mPackages) {
4963            Set<String> libs = null;
4964            final int libCount = mSharedLibraries.size();
4965            for (int i = 0; i < libCount; i++) {
4966                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4967                if (versionedLib == null) {
4968                    continue;
4969                }
4970                final int versionCount = versionedLib.size();
4971                for (int j = 0; j < versionCount; j++) {
4972                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4973                    if (!libEntry.info.isStatic()) {
4974                        if (libs == null) {
4975                            libs = new ArraySet<>();
4976                        }
4977                        libs.add(libEntry.info.getName());
4978                        break;
4979                    }
4980                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4981                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4982                            UserHandle.getUserId(Binder.getCallingUid()),
4983                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4984                        if (libs == null) {
4985                            libs = new ArraySet<>();
4986                        }
4987                        libs.add(libEntry.info.getName());
4988                        break;
4989                    }
4990                }
4991            }
4992
4993            if (libs != null) {
4994                String[] libsArray = new String[libs.size()];
4995                libs.toArray(libsArray);
4996                return libsArray;
4997            }
4998
4999            return null;
5000        }
5001    }
5002
5003    @Override
5004    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5005        // allow instant applications
5006        synchronized (mPackages) {
5007            return mServicesSystemSharedLibraryPackageName;
5008        }
5009    }
5010
5011    @Override
5012    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5013        // allow instant applications
5014        synchronized (mPackages) {
5015            return mSharedSystemSharedLibraryPackageName;
5016        }
5017    }
5018
5019    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5020        for (int i = userList.length - 1; i >= 0; --i) {
5021            final int userId = userList[i];
5022            // don't add instant app to the list of updates
5023            if (pkgSetting.getInstantApp(userId)) {
5024                continue;
5025            }
5026            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5027            if (changedPackages == null) {
5028                changedPackages = new SparseArray<>();
5029                mChangedPackages.put(userId, changedPackages);
5030            }
5031            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5032            if (sequenceNumbers == null) {
5033                sequenceNumbers = new HashMap<>();
5034                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5035            }
5036            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5037            if (sequenceNumber != null) {
5038                changedPackages.remove(sequenceNumber);
5039            }
5040            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5041            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5042        }
5043        mChangedPackagesSequenceNumber++;
5044    }
5045
5046    @Override
5047    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5048        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5049            return null;
5050        }
5051        synchronized (mPackages) {
5052            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5053                return null;
5054            }
5055            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5056            if (changedPackages == null) {
5057                return null;
5058            }
5059            final List<String> packageNames =
5060                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5061            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5062                final String packageName = changedPackages.get(i);
5063                if (packageName != null) {
5064                    packageNames.add(packageName);
5065                }
5066            }
5067            return packageNames.isEmpty()
5068                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5069        }
5070    }
5071
5072    @Override
5073    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5074        // allow instant applications
5075        ArrayList<FeatureInfo> res;
5076        synchronized (mAvailableFeatures) {
5077            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5078            res.addAll(mAvailableFeatures.values());
5079        }
5080        final FeatureInfo fi = new FeatureInfo();
5081        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5082                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5083        res.add(fi);
5084
5085        return new ParceledListSlice<>(res);
5086    }
5087
5088    @Override
5089    public boolean hasSystemFeature(String name, int version) {
5090        // allow instant applications
5091        synchronized (mAvailableFeatures) {
5092            final FeatureInfo feat = mAvailableFeatures.get(name);
5093            if (feat == null) {
5094                return false;
5095            } else {
5096                return feat.version >= version;
5097            }
5098        }
5099    }
5100
5101    @Override
5102    public int checkPermission(String permName, String pkgName, int userId) {
5103        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5104    }
5105
5106    @Override
5107    public int checkUidPermission(String permName, int uid) {
5108        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5109    }
5110
5111    @Override
5112    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5113        if (UserHandle.getCallingUserId() != userId) {
5114            mContext.enforceCallingPermission(
5115                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5116                    "isPermissionRevokedByPolicy for user " + userId);
5117        }
5118
5119        if (checkPermission(permission, packageName, userId)
5120                == PackageManager.PERMISSION_GRANTED) {
5121            return false;
5122        }
5123
5124        final int callingUid = Binder.getCallingUid();
5125        if (getInstantAppPackageName(callingUid) != null) {
5126            if (!isCallerSameApp(packageName, callingUid)) {
5127                return false;
5128            }
5129        } else {
5130            if (isInstantApp(packageName, userId)) {
5131                return false;
5132            }
5133        }
5134
5135        final long identity = Binder.clearCallingIdentity();
5136        try {
5137            final int flags = getPermissionFlags(permission, packageName, userId);
5138            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5139        } finally {
5140            Binder.restoreCallingIdentity(identity);
5141        }
5142    }
5143
5144    @Override
5145    public String getPermissionControllerPackageName() {
5146        synchronized (mPackages) {
5147            return mRequiredInstallerPackage;
5148        }
5149    }
5150
5151    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5152        return mPermissionManager.addDynamicPermission(
5153                info, async, getCallingUid(), new PermissionCallback() {
5154                    @Override
5155                    public void onPermissionChanged() {
5156                        if (!async) {
5157                            mSettings.writeLPr();
5158                        } else {
5159                            scheduleWriteSettingsLocked();
5160                        }
5161                    }
5162                });
5163    }
5164
5165    @Override
5166    public boolean addPermission(PermissionInfo info) {
5167        synchronized (mPackages) {
5168            return addDynamicPermission(info, false);
5169        }
5170    }
5171
5172    @Override
5173    public boolean addPermissionAsync(PermissionInfo info) {
5174        synchronized (mPackages) {
5175            return addDynamicPermission(info, true);
5176        }
5177    }
5178
5179    @Override
5180    public void removePermission(String permName) {
5181        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5182    }
5183
5184    @Override
5185    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5186        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5187                getCallingUid(), userId, mPermissionCallback);
5188    }
5189
5190    @Override
5191    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5192        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5193                getCallingUid(), userId, mPermissionCallback);
5194    }
5195
5196    @Override
5197    public void resetRuntimePermissions() {
5198        mContext.enforceCallingOrSelfPermission(
5199                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5200                "revokeRuntimePermission");
5201
5202        int callingUid = Binder.getCallingUid();
5203        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5204            mContext.enforceCallingOrSelfPermission(
5205                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5206                    "resetRuntimePermissions");
5207        }
5208
5209        synchronized (mPackages) {
5210            mPermissionManager.updateAllPermissions(
5211                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5212                    mPermissionCallback);
5213            for (int userId : UserManagerService.getInstance().getUserIds()) {
5214                final int packageCount = mPackages.size();
5215                for (int i = 0; i < packageCount; i++) {
5216                    PackageParser.Package pkg = mPackages.valueAt(i);
5217                    if (!(pkg.mExtras instanceof PackageSetting)) {
5218                        continue;
5219                    }
5220                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5221                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5222                }
5223            }
5224        }
5225    }
5226
5227    @Override
5228    public int getPermissionFlags(String permName, String packageName, int userId) {
5229        return mPermissionManager.getPermissionFlags(
5230                permName, packageName, getCallingUid(), userId);
5231    }
5232
5233    @Override
5234    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5235            int flagValues, int userId) {
5236        mPermissionManager.updatePermissionFlags(
5237                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5238                mPermissionCallback);
5239    }
5240
5241    /**
5242     * Update the permission flags for all packages and runtime permissions of a user in order
5243     * to allow device or profile owner to remove POLICY_FIXED.
5244     */
5245    @Override
5246    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5247        synchronized (mPackages) {
5248            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5249                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5250                    mPermissionCallback);
5251            if (changed) {
5252                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5253            }
5254        }
5255    }
5256
5257    @Override
5258    public boolean shouldShowRequestPermissionRationale(String permissionName,
5259            String packageName, int userId) {
5260        if (UserHandle.getCallingUserId() != userId) {
5261            mContext.enforceCallingPermission(
5262                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5263                    "canShowRequestPermissionRationale for user " + userId);
5264        }
5265
5266        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5267        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5268            return false;
5269        }
5270
5271        if (checkPermission(permissionName, packageName, userId)
5272                == PackageManager.PERMISSION_GRANTED) {
5273            return false;
5274        }
5275
5276        final int flags;
5277
5278        final long identity = Binder.clearCallingIdentity();
5279        try {
5280            flags = getPermissionFlags(permissionName,
5281                    packageName, userId);
5282        } finally {
5283            Binder.restoreCallingIdentity(identity);
5284        }
5285
5286        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5287                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5288                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5289
5290        if ((flags & fixedFlags) != 0) {
5291            return false;
5292        }
5293
5294        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5295    }
5296
5297    @Override
5298    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5299        mContext.enforceCallingOrSelfPermission(
5300                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5301                "addOnPermissionsChangeListener");
5302
5303        synchronized (mPackages) {
5304            mOnPermissionChangeListeners.addListenerLocked(listener);
5305        }
5306    }
5307
5308    @Override
5309    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5310        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5311            throw new SecurityException("Instant applications don't have access to this method");
5312        }
5313        synchronized (mPackages) {
5314            mOnPermissionChangeListeners.removeListenerLocked(listener);
5315        }
5316    }
5317
5318    @Override
5319    public boolean isProtectedBroadcast(String actionName) {
5320        // allow instant applications
5321        synchronized (mProtectedBroadcasts) {
5322            if (mProtectedBroadcasts.contains(actionName)) {
5323                return true;
5324            } else if (actionName != null) {
5325                // TODO: remove these terrible hacks
5326                if (actionName.startsWith("android.net.netmon.lingerExpired")
5327                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5328                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5329                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5330                    return true;
5331                }
5332            }
5333        }
5334        return false;
5335    }
5336
5337    @Override
5338    public int checkSignatures(String pkg1, String pkg2) {
5339        synchronized (mPackages) {
5340            final PackageParser.Package p1 = mPackages.get(pkg1);
5341            final PackageParser.Package p2 = mPackages.get(pkg2);
5342            if (p1 == null || p1.mExtras == null
5343                    || p2 == null || p2.mExtras == null) {
5344                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5345            }
5346            final int callingUid = Binder.getCallingUid();
5347            final int callingUserId = UserHandle.getUserId(callingUid);
5348            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5349            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5350            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5351                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5352                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5353            }
5354            return compareSignatures(p1.mSignatures, p2.mSignatures);
5355        }
5356    }
5357
5358    @Override
5359    public int checkUidSignatures(int uid1, int uid2) {
5360        final int callingUid = Binder.getCallingUid();
5361        final int callingUserId = UserHandle.getUserId(callingUid);
5362        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5363        // Map to base uids.
5364        uid1 = UserHandle.getAppId(uid1);
5365        uid2 = UserHandle.getAppId(uid2);
5366        // reader
5367        synchronized (mPackages) {
5368            Signature[] s1;
5369            Signature[] s2;
5370            Object obj = mSettings.getUserIdLPr(uid1);
5371            if (obj != null) {
5372                if (obj instanceof SharedUserSetting) {
5373                    if (isCallerInstantApp) {
5374                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5375                    }
5376                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5377                } else if (obj instanceof PackageSetting) {
5378                    final PackageSetting ps = (PackageSetting) obj;
5379                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5380                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5381                    }
5382                    s1 = ps.signatures.mSignatures;
5383                } else {
5384                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5385                }
5386            } else {
5387                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5388            }
5389            obj = mSettings.getUserIdLPr(uid2);
5390            if (obj != null) {
5391                if (obj instanceof SharedUserSetting) {
5392                    if (isCallerInstantApp) {
5393                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5394                    }
5395                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5396                } else if (obj instanceof PackageSetting) {
5397                    final PackageSetting ps = (PackageSetting) obj;
5398                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5399                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5400                    }
5401                    s2 = ps.signatures.mSignatures;
5402                } else {
5403                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5404                }
5405            } else {
5406                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5407            }
5408            return compareSignatures(s1, s2);
5409        }
5410    }
5411
5412    /**
5413     * This method should typically only be used when granting or revoking
5414     * permissions, since the app may immediately restart after this call.
5415     * <p>
5416     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5417     * guard your work against the app being relaunched.
5418     */
5419    private void killUid(int appId, int userId, String reason) {
5420        final long identity = Binder.clearCallingIdentity();
5421        try {
5422            IActivityManager am = ActivityManager.getService();
5423            if (am != null) {
5424                try {
5425                    am.killUid(appId, userId, reason);
5426                } catch (RemoteException e) {
5427                    /* ignore - same process */
5428                }
5429            }
5430        } finally {
5431            Binder.restoreCallingIdentity(identity);
5432        }
5433    }
5434
5435    /**
5436     * If the database version for this type of package (internal storage or
5437     * external storage) is less than the version where package signatures
5438     * were updated, return true.
5439     */
5440    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5441        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5442        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5443    }
5444
5445    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5446        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5447        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5448    }
5449
5450    @Override
5451    public List<String> getAllPackages() {
5452        final int callingUid = Binder.getCallingUid();
5453        final int callingUserId = UserHandle.getUserId(callingUid);
5454        synchronized (mPackages) {
5455            if (canViewInstantApps(callingUid, callingUserId)) {
5456                return new ArrayList<String>(mPackages.keySet());
5457            }
5458            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5459            final List<String> result = new ArrayList<>();
5460            if (instantAppPkgName != null) {
5461                // caller is an instant application; filter unexposed applications
5462                for (PackageParser.Package pkg : mPackages.values()) {
5463                    if (!pkg.visibleToInstantApps) {
5464                        continue;
5465                    }
5466                    result.add(pkg.packageName);
5467                }
5468            } else {
5469                // caller is a normal application; filter instant applications
5470                for (PackageParser.Package pkg : mPackages.values()) {
5471                    final PackageSetting ps =
5472                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5473                    if (ps != null
5474                            && ps.getInstantApp(callingUserId)
5475                            && !mInstantAppRegistry.isInstantAccessGranted(
5476                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5477                        continue;
5478                    }
5479                    result.add(pkg.packageName);
5480                }
5481            }
5482            return result;
5483        }
5484    }
5485
5486    @Override
5487    public String[] getPackagesForUid(int uid) {
5488        final int callingUid = Binder.getCallingUid();
5489        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5490        final int userId = UserHandle.getUserId(uid);
5491        uid = UserHandle.getAppId(uid);
5492        // reader
5493        synchronized (mPackages) {
5494            Object obj = mSettings.getUserIdLPr(uid);
5495            if (obj instanceof SharedUserSetting) {
5496                if (isCallerInstantApp) {
5497                    return null;
5498                }
5499                final SharedUserSetting sus = (SharedUserSetting) obj;
5500                final int N = sus.packages.size();
5501                String[] res = new String[N];
5502                final Iterator<PackageSetting> it = sus.packages.iterator();
5503                int i = 0;
5504                while (it.hasNext()) {
5505                    PackageSetting ps = it.next();
5506                    if (ps.getInstalled(userId)) {
5507                        res[i++] = ps.name;
5508                    } else {
5509                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5510                    }
5511                }
5512                return res;
5513            } else if (obj instanceof PackageSetting) {
5514                final PackageSetting ps = (PackageSetting) obj;
5515                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5516                    return new String[]{ps.name};
5517                }
5518            }
5519        }
5520        return null;
5521    }
5522
5523    @Override
5524    public String getNameForUid(int uid) {
5525        final int callingUid = Binder.getCallingUid();
5526        if (getInstantAppPackageName(callingUid) != null) {
5527            return null;
5528        }
5529        synchronized (mPackages) {
5530            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5531            if (obj instanceof SharedUserSetting) {
5532                final SharedUserSetting sus = (SharedUserSetting) obj;
5533                return sus.name + ":" + sus.userId;
5534            } else if (obj instanceof PackageSetting) {
5535                final PackageSetting ps = (PackageSetting) obj;
5536                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5537                    return null;
5538                }
5539                return ps.name;
5540            }
5541            return null;
5542        }
5543    }
5544
5545    @Override
5546    public String[] getNamesForUids(int[] uids) {
5547        if (uids == null || uids.length == 0) {
5548            return null;
5549        }
5550        final int callingUid = Binder.getCallingUid();
5551        if (getInstantAppPackageName(callingUid) != null) {
5552            return null;
5553        }
5554        final String[] names = new String[uids.length];
5555        synchronized (mPackages) {
5556            for (int i = uids.length - 1; i >= 0; i--) {
5557                final int uid = uids[i];
5558                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5559                if (obj instanceof SharedUserSetting) {
5560                    final SharedUserSetting sus = (SharedUserSetting) obj;
5561                    names[i] = "shared:" + sus.name;
5562                } else if (obj instanceof PackageSetting) {
5563                    final PackageSetting ps = (PackageSetting) obj;
5564                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5565                        names[i] = null;
5566                    } else {
5567                        names[i] = ps.name;
5568                    }
5569                } else {
5570                    names[i] = null;
5571                }
5572            }
5573        }
5574        return names;
5575    }
5576
5577    @Override
5578    public int getUidForSharedUser(String sharedUserName) {
5579        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5580            return -1;
5581        }
5582        if (sharedUserName == null) {
5583            return -1;
5584        }
5585        // reader
5586        synchronized (mPackages) {
5587            SharedUserSetting suid;
5588            try {
5589                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5590                if (suid != null) {
5591                    return suid.userId;
5592                }
5593            } catch (PackageManagerException ignore) {
5594                // can't happen, but, still need to catch it
5595            }
5596            return -1;
5597        }
5598    }
5599
5600    @Override
5601    public int getFlagsForUid(int uid) {
5602        final int callingUid = Binder.getCallingUid();
5603        if (getInstantAppPackageName(callingUid) != null) {
5604            return 0;
5605        }
5606        synchronized (mPackages) {
5607            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5608            if (obj instanceof SharedUserSetting) {
5609                final SharedUserSetting sus = (SharedUserSetting) obj;
5610                return sus.pkgFlags;
5611            } else if (obj instanceof PackageSetting) {
5612                final PackageSetting ps = (PackageSetting) obj;
5613                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5614                    return 0;
5615                }
5616                return ps.pkgFlags;
5617            }
5618        }
5619        return 0;
5620    }
5621
5622    @Override
5623    public int getPrivateFlagsForUid(int uid) {
5624        final int callingUid = Binder.getCallingUid();
5625        if (getInstantAppPackageName(callingUid) != null) {
5626            return 0;
5627        }
5628        synchronized (mPackages) {
5629            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5630            if (obj instanceof SharedUserSetting) {
5631                final SharedUserSetting sus = (SharedUserSetting) obj;
5632                return sus.pkgPrivateFlags;
5633            } else if (obj instanceof PackageSetting) {
5634                final PackageSetting ps = (PackageSetting) obj;
5635                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5636                    return 0;
5637                }
5638                return ps.pkgPrivateFlags;
5639            }
5640        }
5641        return 0;
5642    }
5643
5644    @Override
5645    public boolean isUidPrivileged(int uid) {
5646        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5647            return false;
5648        }
5649        uid = UserHandle.getAppId(uid);
5650        // reader
5651        synchronized (mPackages) {
5652            Object obj = mSettings.getUserIdLPr(uid);
5653            if (obj instanceof SharedUserSetting) {
5654                final SharedUserSetting sus = (SharedUserSetting) obj;
5655                final Iterator<PackageSetting> it = sus.packages.iterator();
5656                while (it.hasNext()) {
5657                    if (it.next().isPrivileged()) {
5658                        return true;
5659                    }
5660                }
5661            } else if (obj instanceof PackageSetting) {
5662                final PackageSetting ps = (PackageSetting) obj;
5663                return ps.isPrivileged();
5664            }
5665        }
5666        return false;
5667    }
5668
5669    @Override
5670    public String[] getAppOpPermissionPackages(String permName) {
5671        return mPermissionManager.getAppOpPermissionPackages(permName);
5672    }
5673
5674    @Override
5675    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5676            int flags, int userId) {
5677        return resolveIntentInternal(
5678                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5679    }
5680
5681    /**
5682     * Normally instant apps can only be resolved when they're visible to the caller.
5683     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5684     * since we need to allow the system to start any installed application.
5685     */
5686    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5687            int flags, int userId, boolean resolveForStart) {
5688        try {
5689            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5690
5691            if (!sUserManager.exists(userId)) return null;
5692            final int callingUid = Binder.getCallingUid();
5693            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5694            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5695                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5696
5697            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5698            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5699                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5700            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5701
5702            final ResolveInfo bestChoice =
5703                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5704            return bestChoice;
5705        } finally {
5706            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5707        }
5708    }
5709
5710    @Override
5711    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5712        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5713            throw new SecurityException(
5714                    "findPersistentPreferredActivity can only be run by the system");
5715        }
5716        if (!sUserManager.exists(userId)) {
5717            return null;
5718        }
5719        final int callingUid = Binder.getCallingUid();
5720        intent = updateIntentForResolve(intent);
5721        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5722        final int flags = updateFlagsForResolve(
5723                0, userId, intent, callingUid, false /*includeInstantApps*/);
5724        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5725                userId);
5726        synchronized (mPackages) {
5727            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5728                    userId);
5729        }
5730    }
5731
5732    @Override
5733    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5734            IntentFilter filter, int match, ComponentName activity) {
5735        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5736            return;
5737        }
5738        final int userId = UserHandle.getCallingUserId();
5739        if (DEBUG_PREFERRED) {
5740            Log.v(TAG, "setLastChosenActivity intent=" + intent
5741                + " resolvedType=" + resolvedType
5742                + " flags=" + flags
5743                + " filter=" + filter
5744                + " match=" + match
5745                + " activity=" + activity);
5746            filter.dump(new PrintStreamPrinter(System.out), "    ");
5747        }
5748        intent.setComponent(null);
5749        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5750                userId);
5751        // Find any earlier preferred or last chosen entries and nuke them
5752        findPreferredActivity(intent, resolvedType,
5753                flags, query, 0, false, true, false, userId);
5754        // Add the new activity as the last chosen for this filter
5755        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5756                "Setting last chosen");
5757    }
5758
5759    @Override
5760    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5761        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5762            return null;
5763        }
5764        final int userId = UserHandle.getCallingUserId();
5765        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5766        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5767                userId);
5768        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5769                false, false, false, userId);
5770    }
5771
5772    /**
5773     * Returns whether or not instant apps have been disabled remotely.
5774     */
5775    private boolean isEphemeralDisabled() {
5776        return mEphemeralAppsDisabled;
5777    }
5778
5779    private boolean isInstantAppAllowed(
5780            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5781            boolean skipPackageCheck) {
5782        if (mInstantAppResolverConnection == null) {
5783            return false;
5784        }
5785        if (mInstantAppInstallerActivity == null) {
5786            return false;
5787        }
5788        if (intent.getComponent() != null) {
5789            return false;
5790        }
5791        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5792            return false;
5793        }
5794        if (!skipPackageCheck && intent.getPackage() != null) {
5795            return false;
5796        }
5797        final boolean isWebUri = hasWebURI(intent);
5798        if (!isWebUri || intent.getData().getHost() == null) {
5799            return false;
5800        }
5801        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5802        // Or if there's already an ephemeral app installed that handles the action
5803        synchronized (mPackages) {
5804            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5805            for (int n = 0; n < count; n++) {
5806                final ResolveInfo info = resolvedActivities.get(n);
5807                final String packageName = info.activityInfo.packageName;
5808                final PackageSetting ps = mSettings.mPackages.get(packageName);
5809                if (ps != null) {
5810                    // only check domain verification status if the app is not a browser
5811                    if (!info.handleAllWebDataURI) {
5812                        // Try to get the status from User settings first
5813                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5814                        final int status = (int) (packedStatus >> 32);
5815                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5816                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5817                            if (DEBUG_EPHEMERAL) {
5818                                Slog.v(TAG, "DENY instant app;"
5819                                    + " pkg: " + packageName + ", status: " + status);
5820                            }
5821                            return false;
5822                        }
5823                    }
5824                    if (ps.getInstantApp(userId)) {
5825                        if (DEBUG_EPHEMERAL) {
5826                            Slog.v(TAG, "DENY instant app installed;"
5827                                    + " pkg: " + packageName);
5828                        }
5829                        return false;
5830                    }
5831                }
5832            }
5833        }
5834        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5835        return true;
5836    }
5837
5838    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5839            Intent origIntent, String resolvedType, String callingPackage,
5840            Bundle verificationBundle, int userId) {
5841        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5842                new InstantAppRequest(responseObj, origIntent, resolvedType,
5843                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5844        mHandler.sendMessage(msg);
5845    }
5846
5847    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5848            int flags, List<ResolveInfo> query, int userId) {
5849        if (query != null) {
5850            final int N = query.size();
5851            if (N == 1) {
5852                return query.get(0);
5853            } else if (N > 1) {
5854                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5855                // If there is more than one activity with the same priority,
5856                // then let the user decide between them.
5857                ResolveInfo r0 = query.get(0);
5858                ResolveInfo r1 = query.get(1);
5859                if (DEBUG_INTENT_MATCHING || debug) {
5860                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5861                            + r1.activityInfo.name + "=" + r1.priority);
5862                }
5863                // If the first activity has a higher priority, or a different
5864                // default, then it is always desirable to pick it.
5865                if (r0.priority != r1.priority
5866                        || r0.preferredOrder != r1.preferredOrder
5867                        || r0.isDefault != r1.isDefault) {
5868                    return query.get(0);
5869                }
5870                // If we have saved a preference for a preferred activity for
5871                // this Intent, use that.
5872                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5873                        flags, query, r0.priority, true, false, debug, userId);
5874                if (ri != null) {
5875                    return ri;
5876                }
5877                // If we have an ephemeral app, use it
5878                for (int i = 0; i < N; i++) {
5879                    ri = query.get(i);
5880                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5881                        final String packageName = ri.activityInfo.packageName;
5882                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5883                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5884                        final int status = (int)(packedStatus >> 32);
5885                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5886                            return ri;
5887                        }
5888                    }
5889                }
5890                ri = new ResolveInfo(mResolveInfo);
5891                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5892                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5893                // If all of the options come from the same package, show the application's
5894                // label and icon instead of the generic resolver's.
5895                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5896                // and then throw away the ResolveInfo itself, meaning that the caller loses
5897                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5898                // a fallback for this case; we only set the target package's resources on
5899                // the ResolveInfo, not the ActivityInfo.
5900                final String intentPackage = intent.getPackage();
5901                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5902                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5903                    ri.resolvePackageName = intentPackage;
5904                    if (userNeedsBadging(userId)) {
5905                        ri.noResourceId = true;
5906                    } else {
5907                        ri.icon = appi.icon;
5908                    }
5909                    ri.iconResourceId = appi.icon;
5910                    ri.labelRes = appi.labelRes;
5911                }
5912                ri.activityInfo.applicationInfo = new ApplicationInfo(
5913                        ri.activityInfo.applicationInfo);
5914                if (userId != 0) {
5915                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5916                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5917                }
5918                // Make sure that the resolver is displayable in car mode
5919                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5920                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5921                return ri;
5922            }
5923        }
5924        return null;
5925    }
5926
5927    /**
5928     * Return true if the given list is not empty and all of its contents have
5929     * an activityInfo with the given package name.
5930     */
5931    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5932        if (ArrayUtils.isEmpty(list)) {
5933            return false;
5934        }
5935        for (int i = 0, N = list.size(); i < N; i++) {
5936            final ResolveInfo ri = list.get(i);
5937            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5938            if (ai == null || !packageName.equals(ai.packageName)) {
5939                return false;
5940            }
5941        }
5942        return true;
5943    }
5944
5945    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5946            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5947        final int N = query.size();
5948        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5949                .get(userId);
5950        // Get the list of persistent preferred activities that handle the intent
5951        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5952        List<PersistentPreferredActivity> pprefs = ppir != null
5953                ? ppir.queryIntent(intent, resolvedType,
5954                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5955                        userId)
5956                : null;
5957        if (pprefs != null && pprefs.size() > 0) {
5958            final int M = pprefs.size();
5959            for (int i=0; i<M; i++) {
5960                final PersistentPreferredActivity ppa = pprefs.get(i);
5961                if (DEBUG_PREFERRED || debug) {
5962                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5963                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5964                            + "\n  component=" + ppa.mComponent);
5965                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5966                }
5967                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5968                        flags | MATCH_DISABLED_COMPONENTS, userId);
5969                if (DEBUG_PREFERRED || debug) {
5970                    Slog.v(TAG, "Found persistent preferred activity:");
5971                    if (ai != null) {
5972                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5973                    } else {
5974                        Slog.v(TAG, "  null");
5975                    }
5976                }
5977                if (ai == null) {
5978                    // This previously registered persistent preferred activity
5979                    // component is no longer known. Ignore it and do NOT remove it.
5980                    continue;
5981                }
5982                for (int j=0; j<N; j++) {
5983                    final ResolveInfo ri = query.get(j);
5984                    if (!ri.activityInfo.applicationInfo.packageName
5985                            .equals(ai.applicationInfo.packageName)) {
5986                        continue;
5987                    }
5988                    if (!ri.activityInfo.name.equals(ai.name)) {
5989                        continue;
5990                    }
5991                    //  Found a persistent preference that can handle the intent.
5992                    if (DEBUG_PREFERRED || debug) {
5993                        Slog.v(TAG, "Returning persistent preferred activity: " +
5994                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5995                    }
5996                    return ri;
5997                }
5998            }
5999        }
6000        return null;
6001    }
6002
6003    // TODO: handle preferred activities missing while user has amnesia
6004    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6005            List<ResolveInfo> query, int priority, boolean always,
6006            boolean removeMatches, boolean debug, int userId) {
6007        if (!sUserManager.exists(userId)) return null;
6008        final int callingUid = Binder.getCallingUid();
6009        flags = updateFlagsForResolve(
6010                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6011        intent = updateIntentForResolve(intent);
6012        // writer
6013        synchronized (mPackages) {
6014            // Try to find a matching persistent preferred activity.
6015            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6016                    debug, userId);
6017
6018            // If a persistent preferred activity matched, use it.
6019            if (pri != null) {
6020                return pri;
6021            }
6022
6023            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6024            // Get the list of preferred activities that handle the intent
6025            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6026            List<PreferredActivity> prefs = pir != null
6027                    ? pir.queryIntent(intent, resolvedType,
6028                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6029                            userId)
6030                    : null;
6031            if (prefs != null && prefs.size() > 0) {
6032                boolean changed = false;
6033                try {
6034                    // First figure out how good the original match set is.
6035                    // We will only allow preferred activities that came
6036                    // from the same match quality.
6037                    int match = 0;
6038
6039                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6040
6041                    final int N = query.size();
6042                    for (int j=0; j<N; j++) {
6043                        final ResolveInfo ri = query.get(j);
6044                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6045                                + ": 0x" + Integer.toHexString(match));
6046                        if (ri.match > match) {
6047                            match = ri.match;
6048                        }
6049                    }
6050
6051                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6052                            + Integer.toHexString(match));
6053
6054                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6055                    final int M = prefs.size();
6056                    for (int i=0; i<M; i++) {
6057                        final PreferredActivity pa = prefs.get(i);
6058                        if (DEBUG_PREFERRED || debug) {
6059                            Slog.v(TAG, "Checking PreferredActivity ds="
6060                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6061                                    + "\n  component=" + pa.mPref.mComponent);
6062                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6063                        }
6064                        if (pa.mPref.mMatch != match) {
6065                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6066                                    + Integer.toHexString(pa.mPref.mMatch));
6067                            continue;
6068                        }
6069                        // If it's not an "always" type preferred activity and that's what we're
6070                        // looking for, skip it.
6071                        if (always && !pa.mPref.mAlways) {
6072                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6073                            continue;
6074                        }
6075                        final ActivityInfo ai = getActivityInfo(
6076                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6077                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6078                                userId);
6079                        if (DEBUG_PREFERRED || debug) {
6080                            Slog.v(TAG, "Found preferred activity:");
6081                            if (ai != null) {
6082                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6083                            } else {
6084                                Slog.v(TAG, "  null");
6085                            }
6086                        }
6087                        if (ai == null) {
6088                            // This previously registered preferred activity
6089                            // component is no longer known.  Most likely an update
6090                            // to the app was installed and in the new version this
6091                            // component no longer exists.  Clean it up by removing
6092                            // it from the preferred activities list, and skip it.
6093                            Slog.w(TAG, "Removing dangling preferred activity: "
6094                                    + pa.mPref.mComponent);
6095                            pir.removeFilter(pa);
6096                            changed = true;
6097                            continue;
6098                        }
6099                        for (int j=0; j<N; j++) {
6100                            final ResolveInfo ri = query.get(j);
6101                            if (!ri.activityInfo.applicationInfo.packageName
6102                                    .equals(ai.applicationInfo.packageName)) {
6103                                continue;
6104                            }
6105                            if (!ri.activityInfo.name.equals(ai.name)) {
6106                                continue;
6107                            }
6108
6109                            if (removeMatches) {
6110                                pir.removeFilter(pa);
6111                                changed = true;
6112                                if (DEBUG_PREFERRED) {
6113                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6114                                }
6115                                break;
6116                            }
6117
6118                            // Okay we found a previously set preferred or last chosen app.
6119                            // If the result set is different from when this
6120                            // was created, and is not a subset of the preferred set, we need to
6121                            // clear it and re-ask the user their preference, if we're looking for
6122                            // an "always" type entry.
6123                            if (always && !pa.mPref.sameSet(query)) {
6124                                if (pa.mPref.isSuperset(query)) {
6125                                    // some components of the set are no longer present in
6126                                    // the query, but the preferred activity can still be reused
6127                                    if (DEBUG_PREFERRED) {
6128                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6129                                                + " still valid as only non-preferred components"
6130                                                + " were removed for " + intent + " type "
6131                                                + resolvedType);
6132                                    }
6133                                    // remove obsolete components and re-add the up-to-date filter
6134                                    PreferredActivity freshPa = new PreferredActivity(pa,
6135                                            pa.mPref.mMatch,
6136                                            pa.mPref.discardObsoleteComponents(query),
6137                                            pa.mPref.mComponent,
6138                                            pa.mPref.mAlways);
6139                                    pir.removeFilter(pa);
6140                                    pir.addFilter(freshPa);
6141                                    changed = true;
6142                                } else {
6143                                    Slog.i(TAG,
6144                                            "Result set changed, dropping preferred activity for "
6145                                                    + intent + " type " + resolvedType);
6146                                    if (DEBUG_PREFERRED) {
6147                                        Slog.v(TAG, "Removing preferred activity since set changed "
6148                                                + pa.mPref.mComponent);
6149                                    }
6150                                    pir.removeFilter(pa);
6151                                    // Re-add the filter as a "last chosen" entry (!always)
6152                                    PreferredActivity lastChosen = new PreferredActivity(
6153                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6154                                    pir.addFilter(lastChosen);
6155                                    changed = true;
6156                                    return null;
6157                                }
6158                            }
6159
6160                            // Yay! Either the set matched or we're looking for the last chosen
6161                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6162                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6163                            return ri;
6164                        }
6165                    }
6166                } finally {
6167                    if (changed) {
6168                        if (DEBUG_PREFERRED) {
6169                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6170                        }
6171                        scheduleWritePackageRestrictionsLocked(userId);
6172                    }
6173                }
6174            }
6175        }
6176        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6177        return null;
6178    }
6179
6180    /*
6181     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6182     */
6183    @Override
6184    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6185            int targetUserId) {
6186        mContext.enforceCallingOrSelfPermission(
6187                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6188        List<CrossProfileIntentFilter> matches =
6189                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6190        if (matches != null) {
6191            int size = matches.size();
6192            for (int i = 0; i < size; i++) {
6193                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6194            }
6195        }
6196        if (hasWebURI(intent)) {
6197            // cross-profile app linking works only towards the parent.
6198            final int callingUid = Binder.getCallingUid();
6199            final UserInfo parent = getProfileParent(sourceUserId);
6200            synchronized(mPackages) {
6201                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6202                        false /*includeInstantApps*/);
6203                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6204                        intent, resolvedType, flags, sourceUserId, parent.id);
6205                return xpDomainInfo != null;
6206            }
6207        }
6208        return false;
6209    }
6210
6211    private UserInfo getProfileParent(int userId) {
6212        final long identity = Binder.clearCallingIdentity();
6213        try {
6214            return sUserManager.getProfileParent(userId);
6215        } finally {
6216            Binder.restoreCallingIdentity(identity);
6217        }
6218    }
6219
6220    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6221            String resolvedType, int userId) {
6222        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6223        if (resolver != null) {
6224            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6225        }
6226        return null;
6227    }
6228
6229    @Override
6230    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6231            String resolvedType, int flags, int userId) {
6232        try {
6233            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6234
6235            return new ParceledListSlice<>(
6236                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6237        } finally {
6238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6239        }
6240    }
6241
6242    /**
6243     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6244     * instant, returns {@code null}.
6245     */
6246    private String getInstantAppPackageName(int callingUid) {
6247        synchronized (mPackages) {
6248            // If the caller is an isolated app use the owner's uid for the lookup.
6249            if (Process.isIsolated(callingUid)) {
6250                callingUid = mIsolatedOwners.get(callingUid);
6251            }
6252            final int appId = UserHandle.getAppId(callingUid);
6253            final Object obj = mSettings.getUserIdLPr(appId);
6254            if (obj instanceof PackageSetting) {
6255                final PackageSetting ps = (PackageSetting) obj;
6256                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6257                return isInstantApp ? ps.pkg.packageName : null;
6258            }
6259        }
6260        return null;
6261    }
6262
6263    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6264            String resolvedType, int flags, int userId) {
6265        return queryIntentActivitiesInternal(
6266                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6267                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6268    }
6269
6270    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6271            String resolvedType, int flags, int filterCallingUid, int userId,
6272            boolean resolveForStart, boolean allowDynamicSplits) {
6273        if (!sUserManager.exists(userId)) return Collections.emptyList();
6274        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6275        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6276                false /* requireFullPermission */, false /* checkShell */,
6277                "query intent activities");
6278        final String pkgName = intent.getPackage();
6279        ComponentName comp = intent.getComponent();
6280        if (comp == null) {
6281            if (intent.getSelector() != null) {
6282                intent = intent.getSelector();
6283                comp = intent.getComponent();
6284            }
6285        }
6286
6287        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6288                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6289        if (comp != null) {
6290            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6291            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6292            if (ai != null) {
6293                // When specifying an explicit component, we prevent the activity from being
6294                // used when either 1) the calling package is normal and the activity is within
6295                // an ephemeral application or 2) the calling package is ephemeral and the
6296                // activity is not visible to ephemeral applications.
6297                final boolean matchInstantApp =
6298                        (flags & PackageManager.MATCH_INSTANT) != 0;
6299                final boolean matchVisibleToInstantAppOnly =
6300                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6301                final boolean matchExplicitlyVisibleOnly =
6302                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6303                final boolean isCallerInstantApp =
6304                        instantAppPkgName != null;
6305                final boolean isTargetSameInstantApp =
6306                        comp.getPackageName().equals(instantAppPkgName);
6307                final boolean isTargetInstantApp =
6308                        (ai.applicationInfo.privateFlags
6309                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6310                final boolean isTargetVisibleToInstantApp =
6311                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6312                final boolean isTargetExplicitlyVisibleToInstantApp =
6313                        isTargetVisibleToInstantApp
6314                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6315                final boolean isTargetHiddenFromInstantApp =
6316                        !isTargetVisibleToInstantApp
6317                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6318                final boolean blockResolution =
6319                        !isTargetSameInstantApp
6320                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6321                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6322                                        && isTargetHiddenFromInstantApp));
6323                if (!blockResolution) {
6324                    final ResolveInfo ri = new ResolveInfo();
6325                    ri.activityInfo = ai;
6326                    list.add(ri);
6327                }
6328            }
6329            return applyPostResolutionFilter(
6330                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6331        }
6332
6333        // reader
6334        boolean sortResult = false;
6335        boolean addEphemeral = false;
6336        List<ResolveInfo> result;
6337        final boolean ephemeralDisabled = isEphemeralDisabled();
6338        synchronized (mPackages) {
6339            if (pkgName == null) {
6340                List<CrossProfileIntentFilter> matchingFilters =
6341                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6342                // Check for results that need to skip the current profile.
6343                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6344                        resolvedType, flags, userId);
6345                if (xpResolveInfo != null) {
6346                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6347                    xpResult.add(xpResolveInfo);
6348                    return applyPostResolutionFilter(
6349                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6350                            allowDynamicSplits, filterCallingUid, userId);
6351                }
6352
6353                // Check for results in the current profile.
6354                result = filterIfNotSystemUser(mActivities.queryIntent(
6355                        intent, resolvedType, flags, userId), userId);
6356                addEphemeral = !ephemeralDisabled
6357                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6358                // Check for cross profile results.
6359                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6360                xpResolveInfo = queryCrossProfileIntents(
6361                        matchingFilters, intent, resolvedType, flags, userId,
6362                        hasNonNegativePriorityResult);
6363                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6364                    boolean isVisibleToUser = filterIfNotSystemUser(
6365                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6366                    if (isVisibleToUser) {
6367                        result.add(xpResolveInfo);
6368                        sortResult = true;
6369                    }
6370                }
6371                if (hasWebURI(intent)) {
6372                    CrossProfileDomainInfo xpDomainInfo = null;
6373                    final UserInfo parent = getProfileParent(userId);
6374                    if (parent != null) {
6375                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6376                                flags, userId, parent.id);
6377                    }
6378                    if (xpDomainInfo != null) {
6379                        if (xpResolveInfo != null) {
6380                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6381                            // in the result.
6382                            result.remove(xpResolveInfo);
6383                        }
6384                        if (result.size() == 0 && !addEphemeral) {
6385                            // No result in current profile, but found candidate in parent user.
6386                            // And we are not going to add emphemeral app, so we can return the
6387                            // result straight away.
6388                            result.add(xpDomainInfo.resolveInfo);
6389                            return applyPostResolutionFilter(result, instantAppPkgName,
6390                                    allowDynamicSplits, filterCallingUid, userId);
6391                        }
6392                    } else if (result.size() <= 1 && !addEphemeral) {
6393                        // No result in parent user and <= 1 result in current profile, and we
6394                        // are not going to add emphemeral app, so we can return the result without
6395                        // further processing.
6396                        return applyPostResolutionFilter(result, instantAppPkgName,
6397                                allowDynamicSplits, filterCallingUid, userId);
6398                    }
6399                    // We have more than one candidate (combining results from current and parent
6400                    // profile), so we need filtering and sorting.
6401                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6402                            intent, flags, result, xpDomainInfo, userId);
6403                    sortResult = true;
6404                }
6405            } else {
6406                final PackageParser.Package pkg = mPackages.get(pkgName);
6407                result = null;
6408                if (pkg != null) {
6409                    result = filterIfNotSystemUser(
6410                            mActivities.queryIntentForPackage(
6411                                    intent, resolvedType, flags, pkg.activities, userId),
6412                            userId);
6413                }
6414                if (result == null || result.size() == 0) {
6415                    // the caller wants to resolve for a particular package; however, there
6416                    // were no installed results, so, try to find an ephemeral result
6417                    addEphemeral = !ephemeralDisabled
6418                            && isInstantAppAllowed(
6419                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6420                    if (result == null) {
6421                        result = new ArrayList<>();
6422                    }
6423                }
6424            }
6425        }
6426        if (addEphemeral) {
6427            result = maybeAddInstantAppInstaller(
6428                    result, intent, resolvedType, flags, userId, resolveForStart);
6429        }
6430        if (sortResult) {
6431            Collections.sort(result, mResolvePrioritySorter);
6432        }
6433        return applyPostResolutionFilter(
6434                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6435    }
6436
6437    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6438            String resolvedType, int flags, int userId, boolean resolveForStart) {
6439        // first, check to see if we've got an instant app already installed
6440        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6441        ResolveInfo localInstantApp = null;
6442        boolean blockResolution = false;
6443        if (!alreadyResolvedLocally) {
6444            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6445                    flags
6446                        | PackageManager.GET_RESOLVED_FILTER
6447                        | PackageManager.MATCH_INSTANT
6448                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6449                    userId);
6450            for (int i = instantApps.size() - 1; i >= 0; --i) {
6451                final ResolveInfo info = instantApps.get(i);
6452                final String packageName = info.activityInfo.packageName;
6453                final PackageSetting ps = mSettings.mPackages.get(packageName);
6454                if (ps.getInstantApp(userId)) {
6455                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6456                    final int status = (int)(packedStatus >> 32);
6457                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6458                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6459                        // there's a local instant application installed, but, the user has
6460                        // chosen to never use it; skip resolution and don't acknowledge
6461                        // an instant application is even available
6462                        if (DEBUG_EPHEMERAL) {
6463                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6464                        }
6465                        blockResolution = true;
6466                        break;
6467                    } else {
6468                        // we have a locally installed instant application; skip resolution
6469                        // but acknowledge there's an instant application available
6470                        if (DEBUG_EPHEMERAL) {
6471                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6472                        }
6473                        localInstantApp = info;
6474                        break;
6475                    }
6476                }
6477            }
6478        }
6479        // no app installed, let's see if one's available
6480        AuxiliaryResolveInfo auxiliaryResponse = null;
6481        if (!blockResolution) {
6482            if (localInstantApp == null) {
6483                // we don't have an instant app locally, resolve externally
6484                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6485                final InstantAppRequest requestObject = new InstantAppRequest(
6486                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6487                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6488                        resolveForStart);
6489                auxiliaryResponse =
6490                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6491                                mContext, mInstantAppResolverConnection, requestObject);
6492                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6493            } else {
6494                // we have an instant application locally, but, we can't admit that since
6495                // callers shouldn't be able to determine prior browsing. create a dummy
6496                // auxiliary response so the downstream code behaves as if there's an
6497                // instant application available externally. when it comes time to start
6498                // the instant application, we'll do the right thing.
6499                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6500                auxiliaryResponse = new AuxiliaryResolveInfo(
6501                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6502                        ai.versionCode, null /*failureIntent*/);
6503            }
6504        }
6505        if (auxiliaryResponse != null) {
6506            if (DEBUG_EPHEMERAL) {
6507                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6508            }
6509            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6510            final PackageSetting ps =
6511                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6512            if (ps != null) {
6513                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6514                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6515                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6516                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6517                // make sure this resolver is the default
6518                ephemeralInstaller.isDefault = true;
6519                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6520                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6521                // add a non-generic filter
6522                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6523                ephemeralInstaller.filter.addDataPath(
6524                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6525                ephemeralInstaller.isInstantAppAvailable = true;
6526                result.add(ephemeralInstaller);
6527            }
6528        }
6529        return result;
6530    }
6531
6532    private static class CrossProfileDomainInfo {
6533        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6534        ResolveInfo resolveInfo;
6535        /* Best domain verification status of the activities found in the other profile */
6536        int bestDomainVerificationStatus;
6537    }
6538
6539    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6540            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6541        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6542                sourceUserId)) {
6543            return null;
6544        }
6545        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6546                resolvedType, flags, parentUserId);
6547
6548        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6549            return null;
6550        }
6551        CrossProfileDomainInfo result = null;
6552        int size = resultTargetUser.size();
6553        for (int i = 0; i < size; i++) {
6554            ResolveInfo riTargetUser = resultTargetUser.get(i);
6555            // Intent filter verification is only for filters that specify a host. So don't return
6556            // those that handle all web uris.
6557            if (riTargetUser.handleAllWebDataURI) {
6558                continue;
6559            }
6560            String packageName = riTargetUser.activityInfo.packageName;
6561            PackageSetting ps = mSettings.mPackages.get(packageName);
6562            if (ps == null) {
6563                continue;
6564            }
6565            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6566            int status = (int)(verificationState >> 32);
6567            if (result == null) {
6568                result = new CrossProfileDomainInfo();
6569                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6570                        sourceUserId, parentUserId);
6571                result.bestDomainVerificationStatus = status;
6572            } else {
6573                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6574                        result.bestDomainVerificationStatus);
6575            }
6576        }
6577        // Don't consider matches with status NEVER across profiles.
6578        if (result != null && result.bestDomainVerificationStatus
6579                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6580            return null;
6581        }
6582        return result;
6583    }
6584
6585    /**
6586     * Verification statuses are ordered from the worse to the best, except for
6587     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6588     */
6589    private int bestDomainVerificationStatus(int status1, int status2) {
6590        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6591            return status2;
6592        }
6593        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6594            return status1;
6595        }
6596        return (int) MathUtils.max(status1, status2);
6597    }
6598
6599    private boolean isUserEnabled(int userId) {
6600        long callingId = Binder.clearCallingIdentity();
6601        try {
6602            UserInfo userInfo = sUserManager.getUserInfo(userId);
6603            return userInfo != null && userInfo.isEnabled();
6604        } finally {
6605            Binder.restoreCallingIdentity(callingId);
6606        }
6607    }
6608
6609    /**
6610     * Filter out activities with systemUserOnly flag set, when current user is not System.
6611     *
6612     * @return filtered list
6613     */
6614    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6615        if (userId == UserHandle.USER_SYSTEM) {
6616            return resolveInfos;
6617        }
6618        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6619            ResolveInfo info = resolveInfos.get(i);
6620            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6621                resolveInfos.remove(i);
6622            }
6623        }
6624        return resolveInfos;
6625    }
6626
6627    /**
6628     * Filters out ephemeral activities.
6629     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6630     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6631     *
6632     * @param resolveInfos The pre-filtered list of resolved activities
6633     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6634     *          is performed.
6635     * @return A filtered list of resolved activities.
6636     */
6637    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6638            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6639        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6640            final ResolveInfo info = resolveInfos.get(i);
6641            // allow activities that are defined in the provided package
6642            if (allowDynamicSplits
6643                    && info.activityInfo.splitName != null
6644                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6645                            info.activityInfo.splitName)) {
6646                if (mInstantAppInstallerInfo == null) {
6647                    if (DEBUG_INSTALL) {
6648                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6649                    }
6650                    resolveInfos.remove(i);
6651                    continue;
6652                }
6653                // requested activity is defined in a split that hasn't been installed yet.
6654                // add the installer to the resolve list
6655                if (DEBUG_INSTALL) {
6656                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6657                }
6658                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6659                final ComponentName installFailureActivity = findInstallFailureActivity(
6660                        info.activityInfo.packageName,  filterCallingUid, userId);
6661                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6662                        info.activityInfo.packageName, info.activityInfo.splitName,
6663                        installFailureActivity,
6664                        info.activityInfo.applicationInfo.versionCode,
6665                        null /*failureIntent*/);
6666                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6667                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6668                // add a non-generic filter
6669                installerInfo.filter = new IntentFilter();
6670
6671                // This resolve info may appear in the chooser UI, so let us make it
6672                // look as the one it replaces as far as the user is concerned which
6673                // requires loading the correct label and icon for the resolve info.
6674                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6675                installerInfo.labelRes = info.resolveLabelResId();
6676                installerInfo.icon = info.resolveIconResId();
6677
6678                // propagate priority/preferred order/default
6679                installerInfo.priority = info.priority;
6680                installerInfo.preferredOrder = info.preferredOrder;
6681                installerInfo.isDefault = info.isDefault;
6682                resolveInfos.set(i, installerInfo);
6683                continue;
6684            }
6685            // caller is a full app, don't need to apply any other filtering
6686            if (ephemeralPkgName == null) {
6687                continue;
6688            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6689                // caller is same app; don't need to apply any other filtering
6690                continue;
6691            }
6692            // allow activities that have been explicitly exposed to ephemeral apps
6693            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6694            if (!isEphemeralApp
6695                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6696                continue;
6697            }
6698            resolveInfos.remove(i);
6699        }
6700        return resolveInfos;
6701    }
6702
6703    /**
6704     * Returns the activity component that can handle install failures.
6705     * <p>By default, the instant application installer handles failures. However, an
6706     * application may want to handle failures on its own. Applications do this by
6707     * creating an activity with an intent filter that handles the action
6708     * {@link Intent#ACTION_INSTALL_FAILURE}.
6709     */
6710    private @Nullable ComponentName findInstallFailureActivity(
6711            String packageName, int filterCallingUid, int userId) {
6712        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6713        failureActivityIntent.setPackage(packageName);
6714        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6715        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6716                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6717                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6718        final int NR = result.size();
6719        if (NR > 0) {
6720            for (int i = 0; i < NR; i++) {
6721                final ResolveInfo info = result.get(i);
6722                if (info.activityInfo.splitName != null) {
6723                    continue;
6724                }
6725                return new ComponentName(packageName, info.activityInfo.name);
6726            }
6727        }
6728        return null;
6729    }
6730
6731    /**
6732     * @param resolveInfos list of resolve infos in descending priority order
6733     * @return if the list contains a resolve info with non-negative priority
6734     */
6735    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6736        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6737    }
6738
6739    private static boolean hasWebURI(Intent intent) {
6740        if (intent.getData() == null) {
6741            return false;
6742        }
6743        final String scheme = intent.getScheme();
6744        if (TextUtils.isEmpty(scheme)) {
6745            return false;
6746        }
6747        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6748    }
6749
6750    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6751            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6752            int userId) {
6753        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6754
6755        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6756            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6757                    candidates.size());
6758        }
6759
6760        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6761        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6762        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6763        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6764        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6765        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6766
6767        synchronized (mPackages) {
6768            final int count = candidates.size();
6769            // First, try to use linked apps. Partition the candidates into four lists:
6770            // one for the final results, one for the "do not use ever", one for "undefined status"
6771            // and finally one for "browser app type".
6772            for (int n=0; n<count; n++) {
6773                ResolveInfo info = candidates.get(n);
6774                String packageName = info.activityInfo.packageName;
6775                PackageSetting ps = mSettings.mPackages.get(packageName);
6776                if (ps != null) {
6777                    // Add to the special match all list (Browser use case)
6778                    if (info.handleAllWebDataURI) {
6779                        matchAllList.add(info);
6780                        continue;
6781                    }
6782                    // Try to get the status from User settings first
6783                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6784                    int status = (int)(packedStatus >> 32);
6785                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6786                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6787                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6788                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6789                                    + " : linkgen=" + linkGeneration);
6790                        }
6791                        // Use link-enabled generation as preferredOrder, i.e.
6792                        // prefer newly-enabled over earlier-enabled.
6793                        info.preferredOrder = linkGeneration;
6794                        alwaysList.add(info);
6795                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6796                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6797                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6798                        }
6799                        neverList.add(info);
6800                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6801                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6802                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6803                        }
6804                        alwaysAskList.add(info);
6805                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6806                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6807                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6808                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6809                        }
6810                        undefinedList.add(info);
6811                    }
6812                }
6813            }
6814
6815            // We'll want to include browser possibilities in a few cases
6816            boolean includeBrowser = false;
6817
6818            // First try to add the "always" resolution(s) for the current user, if any
6819            if (alwaysList.size() > 0) {
6820                result.addAll(alwaysList);
6821            } else {
6822                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6823                result.addAll(undefinedList);
6824                // Maybe add one for the other profile.
6825                if (xpDomainInfo != null && (
6826                        xpDomainInfo.bestDomainVerificationStatus
6827                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6828                    result.add(xpDomainInfo.resolveInfo);
6829                }
6830                includeBrowser = true;
6831            }
6832
6833            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6834            // If there were 'always' entries their preferred order has been set, so we also
6835            // back that off to make the alternatives equivalent
6836            if (alwaysAskList.size() > 0) {
6837                for (ResolveInfo i : result) {
6838                    i.preferredOrder = 0;
6839                }
6840                result.addAll(alwaysAskList);
6841                includeBrowser = true;
6842            }
6843
6844            if (includeBrowser) {
6845                // Also add browsers (all of them or only the default one)
6846                if (DEBUG_DOMAIN_VERIFICATION) {
6847                    Slog.v(TAG, "   ...including browsers in candidate set");
6848                }
6849                if ((matchFlags & MATCH_ALL) != 0) {
6850                    result.addAll(matchAllList);
6851                } else {
6852                    // Browser/generic handling case.  If there's a default browser, go straight
6853                    // to that (but only if there is no other higher-priority match).
6854                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6855                    int maxMatchPrio = 0;
6856                    ResolveInfo defaultBrowserMatch = null;
6857                    final int numCandidates = matchAllList.size();
6858                    for (int n = 0; n < numCandidates; n++) {
6859                        ResolveInfo info = matchAllList.get(n);
6860                        // track the highest overall match priority...
6861                        if (info.priority > maxMatchPrio) {
6862                            maxMatchPrio = info.priority;
6863                        }
6864                        // ...and the highest-priority default browser match
6865                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6866                            if (defaultBrowserMatch == null
6867                                    || (defaultBrowserMatch.priority < info.priority)) {
6868                                if (debug) {
6869                                    Slog.v(TAG, "Considering default browser match " + info);
6870                                }
6871                                defaultBrowserMatch = info;
6872                            }
6873                        }
6874                    }
6875                    if (defaultBrowserMatch != null
6876                            && defaultBrowserMatch.priority >= maxMatchPrio
6877                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6878                    {
6879                        if (debug) {
6880                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6881                        }
6882                        result.add(defaultBrowserMatch);
6883                    } else {
6884                        result.addAll(matchAllList);
6885                    }
6886                }
6887
6888                // If there is nothing selected, add all candidates and remove the ones that the user
6889                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6890                if (result.size() == 0) {
6891                    result.addAll(candidates);
6892                    result.removeAll(neverList);
6893                }
6894            }
6895        }
6896        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6897            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6898                    result.size());
6899            for (ResolveInfo info : result) {
6900                Slog.v(TAG, "  + " + info.activityInfo);
6901            }
6902        }
6903        return result;
6904    }
6905
6906    // Returns a packed value as a long:
6907    //
6908    // high 'int'-sized word: link status: undefined/ask/never/always.
6909    // low 'int'-sized word: relative priority among 'always' results.
6910    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6911        long result = ps.getDomainVerificationStatusForUser(userId);
6912        // if none available, get the master status
6913        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6914            if (ps.getIntentFilterVerificationInfo() != null) {
6915                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6916            }
6917        }
6918        return result;
6919    }
6920
6921    private ResolveInfo querySkipCurrentProfileIntents(
6922            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6923            int flags, int sourceUserId) {
6924        if (matchingFilters != null) {
6925            int size = matchingFilters.size();
6926            for (int i = 0; i < size; i ++) {
6927                CrossProfileIntentFilter filter = matchingFilters.get(i);
6928                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6929                    // Checking if there are activities in the target user that can handle the
6930                    // intent.
6931                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6932                            resolvedType, flags, sourceUserId);
6933                    if (resolveInfo != null) {
6934                        return resolveInfo;
6935                    }
6936                }
6937            }
6938        }
6939        return null;
6940    }
6941
6942    // Return matching ResolveInfo in target user if any.
6943    private ResolveInfo queryCrossProfileIntents(
6944            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6945            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6946        if (matchingFilters != null) {
6947            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6948            // match the same intent. For performance reasons, it is better not to
6949            // run queryIntent twice for the same userId
6950            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6951            int size = matchingFilters.size();
6952            for (int i = 0; i < size; i++) {
6953                CrossProfileIntentFilter filter = matchingFilters.get(i);
6954                int targetUserId = filter.getTargetUserId();
6955                boolean skipCurrentProfile =
6956                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6957                boolean skipCurrentProfileIfNoMatchFound =
6958                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6959                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6960                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6961                    // Checking if there are activities in the target user that can handle the
6962                    // intent.
6963                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6964                            resolvedType, flags, sourceUserId);
6965                    if (resolveInfo != null) return resolveInfo;
6966                    alreadyTriedUserIds.put(targetUserId, true);
6967                }
6968            }
6969        }
6970        return null;
6971    }
6972
6973    /**
6974     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6975     * will forward the intent to the filter's target user.
6976     * Otherwise, returns null.
6977     */
6978    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6979            String resolvedType, int flags, int sourceUserId) {
6980        int targetUserId = filter.getTargetUserId();
6981        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6982                resolvedType, flags, targetUserId);
6983        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6984            // If all the matches in the target profile are suspended, return null.
6985            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6986                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6987                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6988                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6989                            targetUserId);
6990                }
6991            }
6992        }
6993        return null;
6994    }
6995
6996    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6997            int sourceUserId, int targetUserId) {
6998        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6999        long ident = Binder.clearCallingIdentity();
7000        boolean targetIsProfile;
7001        try {
7002            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7003        } finally {
7004            Binder.restoreCallingIdentity(ident);
7005        }
7006        String className;
7007        if (targetIsProfile) {
7008            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7009        } else {
7010            className = FORWARD_INTENT_TO_PARENT;
7011        }
7012        ComponentName forwardingActivityComponentName = new ComponentName(
7013                mAndroidApplication.packageName, className);
7014        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7015                sourceUserId);
7016        if (!targetIsProfile) {
7017            forwardingActivityInfo.showUserIcon = targetUserId;
7018            forwardingResolveInfo.noResourceId = true;
7019        }
7020        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7021        forwardingResolveInfo.priority = 0;
7022        forwardingResolveInfo.preferredOrder = 0;
7023        forwardingResolveInfo.match = 0;
7024        forwardingResolveInfo.isDefault = true;
7025        forwardingResolveInfo.filter = filter;
7026        forwardingResolveInfo.targetUserId = targetUserId;
7027        return forwardingResolveInfo;
7028    }
7029
7030    @Override
7031    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7032            Intent[] specifics, String[] specificTypes, Intent intent,
7033            String resolvedType, int flags, int userId) {
7034        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7035                specificTypes, intent, resolvedType, flags, userId));
7036    }
7037
7038    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7039            Intent[] specifics, String[] specificTypes, Intent intent,
7040            String resolvedType, int flags, int userId) {
7041        if (!sUserManager.exists(userId)) return Collections.emptyList();
7042        final int callingUid = Binder.getCallingUid();
7043        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7044                false /*includeInstantApps*/);
7045        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7046                false /*requireFullPermission*/, false /*checkShell*/,
7047                "query intent activity options");
7048        final String resultsAction = intent.getAction();
7049
7050        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7051                | PackageManager.GET_RESOLVED_FILTER, userId);
7052
7053        if (DEBUG_INTENT_MATCHING) {
7054            Log.v(TAG, "Query " + intent + ": " + results);
7055        }
7056
7057        int specificsPos = 0;
7058        int N;
7059
7060        // todo: note that the algorithm used here is O(N^2).  This
7061        // isn't a problem in our current environment, but if we start running
7062        // into situations where we have more than 5 or 10 matches then this
7063        // should probably be changed to something smarter...
7064
7065        // First we go through and resolve each of the specific items
7066        // that were supplied, taking care of removing any corresponding
7067        // duplicate items in the generic resolve list.
7068        if (specifics != null) {
7069            for (int i=0; i<specifics.length; i++) {
7070                final Intent sintent = specifics[i];
7071                if (sintent == null) {
7072                    continue;
7073                }
7074
7075                if (DEBUG_INTENT_MATCHING) {
7076                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7077                }
7078
7079                String action = sintent.getAction();
7080                if (resultsAction != null && resultsAction.equals(action)) {
7081                    // If this action was explicitly requested, then don't
7082                    // remove things that have it.
7083                    action = null;
7084                }
7085
7086                ResolveInfo ri = null;
7087                ActivityInfo ai = null;
7088
7089                ComponentName comp = sintent.getComponent();
7090                if (comp == null) {
7091                    ri = resolveIntent(
7092                        sintent,
7093                        specificTypes != null ? specificTypes[i] : null,
7094                            flags, userId);
7095                    if (ri == null) {
7096                        continue;
7097                    }
7098                    if (ri == mResolveInfo) {
7099                        // ACK!  Must do something better with this.
7100                    }
7101                    ai = ri.activityInfo;
7102                    comp = new ComponentName(ai.applicationInfo.packageName,
7103                            ai.name);
7104                } else {
7105                    ai = getActivityInfo(comp, flags, userId);
7106                    if (ai == null) {
7107                        continue;
7108                    }
7109                }
7110
7111                // Look for any generic query activities that are duplicates
7112                // of this specific one, and remove them from the results.
7113                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7114                N = results.size();
7115                int j;
7116                for (j=specificsPos; j<N; j++) {
7117                    ResolveInfo sri = results.get(j);
7118                    if ((sri.activityInfo.name.equals(comp.getClassName())
7119                            && sri.activityInfo.applicationInfo.packageName.equals(
7120                                    comp.getPackageName()))
7121                        || (action != null && sri.filter.matchAction(action))) {
7122                        results.remove(j);
7123                        if (DEBUG_INTENT_MATCHING) Log.v(
7124                            TAG, "Removing duplicate item from " + j
7125                            + " due to specific " + specificsPos);
7126                        if (ri == null) {
7127                            ri = sri;
7128                        }
7129                        j--;
7130                        N--;
7131                    }
7132                }
7133
7134                // Add this specific item to its proper place.
7135                if (ri == null) {
7136                    ri = new ResolveInfo();
7137                    ri.activityInfo = ai;
7138                }
7139                results.add(specificsPos, ri);
7140                ri.specificIndex = i;
7141                specificsPos++;
7142            }
7143        }
7144
7145        // Now we go through the remaining generic results and remove any
7146        // duplicate actions that are found here.
7147        N = results.size();
7148        for (int i=specificsPos; i<N-1; i++) {
7149            final ResolveInfo rii = results.get(i);
7150            if (rii.filter == null) {
7151                continue;
7152            }
7153
7154            // Iterate over all of the actions of this result's intent
7155            // filter...  typically this should be just one.
7156            final Iterator<String> it = rii.filter.actionsIterator();
7157            if (it == null) {
7158                continue;
7159            }
7160            while (it.hasNext()) {
7161                final String action = it.next();
7162                if (resultsAction != null && resultsAction.equals(action)) {
7163                    // If this action was explicitly requested, then don't
7164                    // remove things that have it.
7165                    continue;
7166                }
7167                for (int j=i+1; j<N; j++) {
7168                    final ResolveInfo rij = results.get(j);
7169                    if (rij.filter != null && rij.filter.hasAction(action)) {
7170                        results.remove(j);
7171                        if (DEBUG_INTENT_MATCHING) Log.v(
7172                            TAG, "Removing duplicate item from " + j
7173                            + " due to action " + action + " at " + i);
7174                        j--;
7175                        N--;
7176                    }
7177                }
7178            }
7179
7180            // If the caller didn't request filter information, drop it now
7181            // so we don't have to marshall/unmarshall it.
7182            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7183                rii.filter = null;
7184            }
7185        }
7186
7187        // Filter out the caller activity if so requested.
7188        if (caller != null) {
7189            N = results.size();
7190            for (int i=0; i<N; i++) {
7191                ActivityInfo ainfo = results.get(i).activityInfo;
7192                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7193                        && caller.getClassName().equals(ainfo.name)) {
7194                    results.remove(i);
7195                    break;
7196                }
7197            }
7198        }
7199
7200        // If the caller didn't request filter information,
7201        // drop them now so we don't have to
7202        // marshall/unmarshall it.
7203        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7204            N = results.size();
7205            for (int i=0; i<N; i++) {
7206                results.get(i).filter = null;
7207            }
7208        }
7209
7210        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7211        return results;
7212    }
7213
7214    @Override
7215    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7216            String resolvedType, int flags, int userId) {
7217        return new ParceledListSlice<>(
7218                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7219                        false /*allowDynamicSplits*/));
7220    }
7221
7222    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7223            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7224        if (!sUserManager.exists(userId)) return Collections.emptyList();
7225        final int callingUid = Binder.getCallingUid();
7226        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7227                false /*requireFullPermission*/, false /*checkShell*/,
7228                "query intent receivers");
7229        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7230        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7231                false /*includeInstantApps*/);
7232        ComponentName comp = intent.getComponent();
7233        if (comp == null) {
7234            if (intent.getSelector() != null) {
7235                intent = intent.getSelector();
7236                comp = intent.getComponent();
7237            }
7238        }
7239        if (comp != null) {
7240            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7241            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7242            if (ai != null) {
7243                // When specifying an explicit component, we prevent the activity from being
7244                // used when either 1) the calling package is normal and the activity is within
7245                // an instant application or 2) the calling package is ephemeral and the
7246                // activity is not visible to instant applications.
7247                final boolean matchInstantApp =
7248                        (flags & PackageManager.MATCH_INSTANT) != 0;
7249                final boolean matchVisibleToInstantAppOnly =
7250                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7251                final boolean matchExplicitlyVisibleOnly =
7252                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7253                final boolean isCallerInstantApp =
7254                        instantAppPkgName != null;
7255                final boolean isTargetSameInstantApp =
7256                        comp.getPackageName().equals(instantAppPkgName);
7257                final boolean isTargetInstantApp =
7258                        (ai.applicationInfo.privateFlags
7259                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7260                final boolean isTargetVisibleToInstantApp =
7261                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7262                final boolean isTargetExplicitlyVisibleToInstantApp =
7263                        isTargetVisibleToInstantApp
7264                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7265                final boolean isTargetHiddenFromInstantApp =
7266                        !isTargetVisibleToInstantApp
7267                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7268                final boolean blockResolution =
7269                        !isTargetSameInstantApp
7270                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7271                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7272                                        && isTargetHiddenFromInstantApp));
7273                if (!blockResolution) {
7274                    ResolveInfo ri = new ResolveInfo();
7275                    ri.activityInfo = ai;
7276                    list.add(ri);
7277                }
7278            }
7279            return applyPostResolutionFilter(
7280                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7281        }
7282
7283        // reader
7284        synchronized (mPackages) {
7285            String pkgName = intent.getPackage();
7286            if (pkgName == null) {
7287                final List<ResolveInfo> result =
7288                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7289                return applyPostResolutionFilter(
7290                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7291            }
7292            final PackageParser.Package pkg = mPackages.get(pkgName);
7293            if (pkg != null) {
7294                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7295                        intent, resolvedType, flags, pkg.receivers, userId);
7296                return applyPostResolutionFilter(
7297                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7298            }
7299            return Collections.emptyList();
7300        }
7301    }
7302
7303    @Override
7304    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7305        final int callingUid = Binder.getCallingUid();
7306        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7307    }
7308
7309    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7310            int userId, int callingUid) {
7311        if (!sUserManager.exists(userId)) return null;
7312        flags = updateFlagsForResolve(
7313                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7314        List<ResolveInfo> query = queryIntentServicesInternal(
7315                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7316        if (query != null) {
7317            if (query.size() >= 1) {
7318                // If there is more than one service with the same priority,
7319                // just arbitrarily pick the first one.
7320                return query.get(0);
7321            }
7322        }
7323        return null;
7324    }
7325
7326    @Override
7327    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7328            String resolvedType, int flags, int userId) {
7329        final int callingUid = Binder.getCallingUid();
7330        return new ParceledListSlice<>(queryIntentServicesInternal(
7331                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7332    }
7333
7334    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7335            String resolvedType, int flags, int userId, int callingUid,
7336            boolean includeInstantApps) {
7337        if (!sUserManager.exists(userId)) return Collections.emptyList();
7338        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7339                false /*requireFullPermission*/, false /*checkShell*/,
7340                "query intent receivers");
7341        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7342        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7343        ComponentName comp = intent.getComponent();
7344        if (comp == null) {
7345            if (intent.getSelector() != null) {
7346                intent = intent.getSelector();
7347                comp = intent.getComponent();
7348            }
7349        }
7350        if (comp != null) {
7351            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7352            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7353            if (si != null) {
7354                // When specifying an explicit component, we prevent the service from being
7355                // used when either 1) the service is in an instant application and the
7356                // caller is not the same instant application or 2) the calling package is
7357                // ephemeral and the activity is not visible to ephemeral applications.
7358                final boolean matchInstantApp =
7359                        (flags & PackageManager.MATCH_INSTANT) != 0;
7360                final boolean matchVisibleToInstantAppOnly =
7361                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7362                final boolean isCallerInstantApp =
7363                        instantAppPkgName != null;
7364                final boolean isTargetSameInstantApp =
7365                        comp.getPackageName().equals(instantAppPkgName);
7366                final boolean isTargetInstantApp =
7367                        (si.applicationInfo.privateFlags
7368                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7369                final boolean isTargetHiddenFromInstantApp =
7370                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7371                final boolean blockResolution =
7372                        !isTargetSameInstantApp
7373                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7374                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7375                                        && isTargetHiddenFromInstantApp));
7376                if (!blockResolution) {
7377                    final ResolveInfo ri = new ResolveInfo();
7378                    ri.serviceInfo = si;
7379                    list.add(ri);
7380                }
7381            }
7382            return list;
7383        }
7384
7385        // reader
7386        synchronized (mPackages) {
7387            String pkgName = intent.getPackage();
7388            if (pkgName == null) {
7389                return applyPostServiceResolutionFilter(
7390                        mServices.queryIntent(intent, resolvedType, flags, userId),
7391                        instantAppPkgName);
7392            }
7393            final PackageParser.Package pkg = mPackages.get(pkgName);
7394            if (pkg != null) {
7395                return applyPostServiceResolutionFilter(
7396                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7397                                userId),
7398                        instantAppPkgName);
7399            }
7400            return Collections.emptyList();
7401        }
7402    }
7403
7404    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7405            String instantAppPkgName) {
7406        if (instantAppPkgName == null) {
7407            return resolveInfos;
7408        }
7409        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7410            final ResolveInfo info = resolveInfos.get(i);
7411            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7412            // allow services that are defined in the provided package
7413            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7414                if (info.serviceInfo.splitName != null
7415                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7416                                info.serviceInfo.splitName)) {
7417                    // requested service is defined in a split that hasn't been installed yet.
7418                    // add the installer to the resolve list
7419                    if (DEBUG_EPHEMERAL) {
7420                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7421                    }
7422                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7423                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7424                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7425                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7426                            null /*failureIntent*/);
7427                    // make sure this resolver is the default
7428                    installerInfo.isDefault = true;
7429                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7430                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7431                    // add a non-generic filter
7432                    installerInfo.filter = new IntentFilter();
7433                    // load resources from the correct package
7434                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7435                    resolveInfos.set(i, installerInfo);
7436                }
7437                continue;
7438            }
7439            // allow services that have been explicitly exposed to ephemeral apps
7440            if (!isEphemeralApp
7441                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7442                continue;
7443            }
7444            resolveInfos.remove(i);
7445        }
7446        return resolveInfos;
7447    }
7448
7449    @Override
7450    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7451            String resolvedType, int flags, int userId) {
7452        return new ParceledListSlice<>(
7453                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7454    }
7455
7456    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7457            Intent intent, String resolvedType, int flags, int userId) {
7458        if (!sUserManager.exists(userId)) return Collections.emptyList();
7459        final int callingUid = Binder.getCallingUid();
7460        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7461        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7462                false /*includeInstantApps*/);
7463        ComponentName comp = intent.getComponent();
7464        if (comp == null) {
7465            if (intent.getSelector() != null) {
7466                intent = intent.getSelector();
7467                comp = intent.getComponent();
7468            }
7469        }
7470        if (comp != null) {
7471            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7472            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7473            if (pi != null) {
7474                // When specifying an explicit component, we prevent the provider from being
7475                // used when either 1) the provider is in an instant application and the
7476                // caller is not the same instant application or 2) the calling package is an
7477                // instant application and the provider is not visible to instant applications.
7478                final boolean matchInstantApp =
7479                        (flags & PackageManager.MATCH_INSTANT) != 0;
7480                final boolean matchVisibleToInstantAppOnly =
7481                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7482                final boolean isCallerInstantApp =
7483                        instantAppPkgName != null;
7484                final boolean isTargetSameInstantApp =
7485                        comp.getPackageName().equals(instantAppPkgName);
7486                final boolean isTargetInstantApp =
7487                        (pi.applicationInfo.privateFlags
7488                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7489                final boolean isTargetHiddenFromInstantApp =
7490                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7491                final boolean blockResolution =
7492                        !isTargetSameInstantApp
7493                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7494                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7495                                        && isTargetHiddenFromInstantApp));
7496                if (!blockResolution) {
7497                    final ResolveInfo ri = new ResolveInfo();
7498                    ri.providerInfo = pi;
7499                    list.add(ri);
7500                }
7501            }
7502            return list;
7503        }
7504
7505        // reader
7506        synchronized (mPackages) {
7507            String pkgName = intent.getPackage();
7508            if (pkgName == null) {
7509                return applyPostContentProviderResolutionFilter(
7510                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7511                        instantAppPkgName);
7512            }
7513            final PackageParser.Package pkg = mPackages.get(pkgName);
7514            if (pkg != null) {
7515                return applyPostContentProviderResolutionFilter(
7516                        mProviders.queryIntentForPackage(
7517                        intent, resolvedType, flags, pkg.providers, userId),
7518                        instantAppPkgName);
7519            }
7520            return Collections.emptyList();
7521        }
7522    }
7523
7524    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7525            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7526        if (instantAppPkgName == null) {
7527            return resolveInfos;
7528        }
7529        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7530            final ResolveInfo info = resolveInfos.get(i);
7531            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7532            // allow providers that are defined in the provided package
7533            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7534                if (info.providerInfo.splitName != null
7535                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7536                                info.providerInfo.splitName)) {
7537                    // requested provider is defined in a split that hasn't been installed yet.
7538                    // add the installer to the resolve list
7539                    if (DEBUG_EPHEMERAL) {
7540                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7541                    }
7542                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7543                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7544                            info.providerInfo.packageName, info.providerInfo.splitName,
7545                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7546                            null /*failureIntent*/);
7547                    // make sure this resolver is the default
7548                    installerInfo.isDefault = true;
7549                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7550                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7551                    // add a non-generic filter
7552                    installerInfo.filter = new IntentFilter();
7553                    // load resources from the correct package
7554                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7555                    resolveInfos.set(i, installerInfo);
7556                }
7557                continue;
7558            }
7559            // allow providers that have been explicitly exposed to instant applications
7560            if (!isEphemeralApp
7561                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7562                continue;
7563            }
7564            resolveInfos.remove(i);
7565        }
7566        return resolveInfos;
7567    }
7568
7569    @Override
7570    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7571        final int callingUid = Binder.getCallingUid();
7572        if (getInstantAppPackageName(callingUid) != null) {
7573            return ParceledListSlice.emptyList();
7574        }
7575        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7576        flags = updateFlagsForPackage(flags, userId, null);
7577        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7578        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7579                true /* requireFullPermission */, false /* checkShell */,
7580                "get installed packages");
7581
7582        // writer
7583        synchronized (mPackages) {
7584            ArrayList<PackageInfo> list;
7585            if (listUninstalled) {
7586                list = new ArrayList<>(mSettings.mPackages.size());
7587                for (PackageSetting ps : mSettings.mPackages.values()) {
7588                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7589                        continue;
7590                    }
7591                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7592                        continue;
7593                    }
7594                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7595                    if (pi != null) {
7596                        list.add(pi);
7597                    }
7598                }
7599            } else {
7600                list = new ArrayList<>(mPackages.size());
7601                for (PackageParser.Package p : mPackages.values()) {
7602                    final PackageSetting ps = (PackageSetting) p.mExtras;
7603                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7604                        continue;
7605                    }
7606                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7607                        continue;
7608                    }
7609                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7610                            p.mExtras, flags, userId);
7611                    if (pi != null) {
7612                        list.add(pi);
7613                    }
7614                }
7615            }
7616
7617            return new ParceledListSlice<>(list);
7618        }
7619    }
7620
7621    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7622            String[] permissions, boolean[] tmp, int flags, int userId) {
7623        int numMatch = 0;
7624        final PermissionsState permissionsState = ps.getPermissionsState();
7625        for (int i=0; i<permissions.length; i++) {
7626            final String permission = permissions[i];
7627            if (permissionsState.hasPermission(permission, userId)) {
7628                tmp[i] = true;
7629                numMatch++;
7630            } else {
7631                tmp[i] = false;
7632            }
7633        }
7634        if (numMatch == 0) {
7635            return;
7636        }
7637        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7638
7639        // The above might return null in cases of uninstalled apps or install-state
7640        // skew across users/profiles.
7641        if (pi != null) {
7642            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7643                if (numMatch == permissions.length) {
7644                    pi.requestedPermissions = permissions;
7645                } else {
7646                    pi.requestedPermissions = new String[numMatch];
7647                    numMatch = 0;
7648                    for (int i=0; i<permissions.length; i++) {
7649                        if (tmp[i]) {
7650                            pi.requestedPermissions[numMatch] = permissions[i];
7651                            numMatch++;
7652                        }
7653                    }
7654                }
7655            }
7656            list.add(pi);
7657        }
7658    }
7659
7660    @Override
7661    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7662            String[] permissions, int flags, int userId) {
7663        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7664        flags = updateFlagsForPackage(flags, userId, permissions);
7665        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7666                true /* requireFullPermission */, false /* checkShell */,
7667                "get packages holding permissions");
7668        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7669
7670        // writer
7671        synchronized (mPackages) {
7672            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7673            boolean[] tmpBools = new boolean[permissions.length];
7674            if (listUninstalled) {
7675                for (PackageSetting ps : mSettings.mPackages.values()) {
7676                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7677                            userId);
7678                }
7679            } else {
7680                for (PackageParser.Package pkg : mPackages.values()) {
7681                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7682                    if (ps != null) {
7683                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7684                                userId);
7685                    }
7686                }
7687            }
7688
7689            return new ParceledListSlice<PackageInfo>(list);
7690        }
7691    }
7692
7693    @Override
7694    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7695        final int callingUid = Binder.getCallingUid();
7696        if (getInstantAppPackageName(callingUid) != null) {
7697            return ParceledListSlice.emptyList();
7698        }
7699        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7700        flags = updateFlagsForApplication(flags, userId, null);
7701        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7702
7703        // writer
7704        synchronized (mPackages) {
7705            ArrayList<ApplicationInfo> list;
7706            if (listUninstalled) {
7707                list = new ArrayList<>(mSettings.mPackages.size());
7708                for (PackageSetting ps : mSettings.mPackages.values()) {
7709                    ApplicationInfo ai;
7710                    int effectiveFlags = flags;
7711                    if (ps.isSystem()) {
7712                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7713                    }
7714                    if (ps.pkg != null) {
7715                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7716                            continue;
7717                        }
7718                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7719                            continue;
7720                        }
7721                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7722                                ps.readUserState(userId), userId);
7723                        if (ai != null) {
7724                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7725                        }
7726                    } else {
7727                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7728                        // and already converts to externally visible package name
7729                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7730                                callingUid, effectiveFlags, userId);
7731                    }
7732                    if (ai != null) {
7733                        list.add(ai);
7734                    }
7735                }
7736            } else {
7737                list = new ArrayList<>(mPackages.size());
7738                for (PackageParser.Package p : mPackages.values()) {
7739                    if (p.mExtras != null) {
7740                        PackageSetting ps = (PackageSetting) p.mExtras;
7741                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7742                            continue;
7743                        }
7744                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7745                            continue;
7746                        }
7747                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7748                                ps.readUserState(userId), userId);
7749                        if (ai != null) {
7750                            ai.packageName = resolveExternalPackageNameLPr(p);
7751                            list.add(ai);
7752                        }
7753                    }
7754                }
7755            }
7756
7757            return new ParceledListSlice<>(list);
7758        }
7759    }
7760
7761    @Override
7762    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7763        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7764            return null;
7765        }
7766        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7767            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7768                    "getEphemeralApplications");
7769        }
7770        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7771                true /* requireFullPermission */, false /* checkShell */,
7772                "getEphemeralApplications");
7773        synchronized (mPackages) {
7774            List<InstantAppInfo> instantApps = mInstantAppRegistry
7775                    .getInstantAppsLPr(userId);
7776            if (instantApps != null) {
7777                return new ParceledListSlice<>(instantApps);
7778            }
7779        }
7780        return null;
7781    }
7782
7783    @Override
7784    public boolean isInstantApp(String packageName, int userId) {
7785        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7786                true /* requireFullPermission */, false /* checkShell */,
7787                "isInstantApp");
7788        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7789            return false;
7790        }
7791
7792        synchronized (mPackages) {
7793            int callingUid = Binder.getCallingUid();
7794            if (Process.isIsolated(callingUid)) {
7795                callingUid = mIsolatedOwners.get(callingUid);
7796            }
7797            final PackageSetting ps = mSettings.mPackages.get(packageName);
7798            PackageParser.Package pkg = mPackages.get(packageName);
7799            final boolean returnAllowed =
7800                    ps != null
7801                    && (isCallerSameApp(packageName, callingUid)
7802                            || canViewInstantApps(callingUid, userId)
7803                            || mInstantAppRegistry.isInstantAccessGranted(
7804                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7805            if (returnAllowed) {
7806                return ps.getInstantApp(userId);
7807            }
7808        }
7809        return false;
7810    }
7811
7812    @Override
7813    public byte[] getInstantAppCookie(String packageName, int userId) {
7814        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7815            return null;
7816        }
7817
7818        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7819                true /* requireFullPermission */, false /* checkShell */,
7820                "getInstantAppCookie");
7821        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7822            return null;
7823        }
7824        synchronized (mPackages) {
7825            return mInstantAppRegistry.getInstantAppCookieLPw(
7826                    packageName, userId);
7827        }
7828    }
7829
7830    @Override
7831    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7832        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7833            return true;
7834        }
7835
7836        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7837                true /* requireFullPermission */, true /* checkShell */,
7838                "setInstantAppCookie");
7839        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7840            return false;
7841        }
7842        synchronized (mPackages) {
7843            return mInstantAppRegistry.setInstantAppCookieLPw(
7844                    packageName, cookie, userId);
7845        }
7846    }
7847
7848    @Override
7849    public Bitmap getInstantAppIcon(String packageName, int userId) {
7850        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7851            return null;
7852        }
7853
7854        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7855            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7856                    "getInstantAppIcon");
7857        }
7858        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7859                true /* requireFullPermission */, false /* checkShell */,
7860                "getInstantAppIcon");
7861
7862        synchronized (mPackages) {
7863            return mInstantAppRegistry.getInstantAppIconLPw(
7864                    packageName, userId);
7865        }
7866    }
7867
7868    private boolean isCallerSameApp(String packageName, int uid) {
7869        PackageParser.Package pkg = mPackages.get(packageName);
7870        return pkg != null
7871                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7872    }
7873
7874    @Override
7875    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7877            return ParceledListSlice.emptyList();
7878        }
7879        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7880    }
7881
7882    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7883        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7884
7885        // reader
7886        synchronized (mPackages) {
7887            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7888            final int userId = UserHandle.getCallingUserId();
7889            while (i.hasNext()) {
7890                final PackageParser.Package p = i.next();
7891                if (p.applicationInfo == null) continue;
7892
7893                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7894                        && !p.applicationInfo.isDirectBootAware();
7895                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7896                        && p.applicationInfo.isDirectBootAware();
7897
7898                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7899                        && (!mSafeMode || isSystemApp(p))
7900                        && (matchesUnaware || matchesAware)) {
7901                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7902                    if (ps != null) {
7903                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7904                                ps.readUserState(userId), userId);
7905                        if (ai != null) {
7906                            finalList.add(ai);
7907                        }
7908                    }
7909                }
7910            }
7911        }
7912
7913        return finalList;
7914    }
7915
7916    @Override
7917    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7918        return resolveContentProviderInternal(name, flags, userId);
7919    }
7920
7921    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7922        if (!sUserManager.exists(userId)) return null;
7923        flags = updateFlagsForComponent(flags, userId, name);
7924        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7925        // reader
7926        synchronized (mPackages) {
7927            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7928            PackageSetting ps = provider != null
7929                    ? mSettings.mPackages.get(provider.owner.packageName)
7930                    : null;
7931            if (ps != null) {
7932                final boolean isInstantApp = ps.getInstantApp(userId);
7933                // normal application; filter out instant application provider
7934                if (instantAppPkgName == null && isInstantApp) {
7935                    return null;
7936                }
7937                // instant application; filter out other instant applications
7938                if (instantAppPkgName != null
7939                        && isInstantApp
7940                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7941                    return null;
7942                }
7943                // instant application; filter out non-exposed provider
7944                if (instantAppPkgName != null
7945                        && !isInstantApp
7946                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7947                    return null;
7948                }
7949                // provider not enabled
7950                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7951                    return null;
7952                }
7953                return PackageParser.generateProviderInfo(
7954                        provider, flags, ps.readUserState(userId), userId);
7955            }
7956            return null;
7957        }
7958    }
7959
7960    /**
7961     * @deprecated
7962     */
7963    @Deprecated
7964    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7965        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7966            return;
7967        }
7968        // reader
7969        synchronized (mPackages) {
7970            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7971                    .entrySet().iterator();
7972            final int userId = UserHandle.getCallingUserId();
7973            while (i.hasNext()) {
7974                Map.Entry<String, PackageParser.Provider> entry = i.next();
7975                PackageParser.Provider p = entry.getValue();
7976                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7977
7978                if (ps != null && p.syncable
7979                        && (!mSafeMode || (p.info.applicationInfo.flags
7980                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7981                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7982                            ps.readUserState(userId), userId);
7983                    if (info != null) {
7984                        outNames.add(entry.getKey());
7985                        outInfo.add(info);
7986                    }
7987                }
7988            }
7989        }
7990    }
7991
7992    @Override
7993    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7994            int uid, int flags, String metaDataKey) {
7995        final int callingUid = Binder.getCallingUid();
7996        final int userId = processName != null ? UserHandle.getUserId(uid)
7997                : UserHandle.getCallingUserId();
7998        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7999        flags = updateFlagsForComponent(flags, userId, processName);
8000        ArrayList<ProviderInfo> finalList = null;
8001        // reader
8002        synchronized (mPackages) {
8003            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8004            while (i.hasNext()) {
8005                final PackageParser.Provider p = i.next();
8006                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8007                if (ps != null && p.info.authority != null
8008                        && (processName == null
8009                                || (p.info.processName.equals(processName)
8010                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8011                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8012
8013                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8014                    // parameter.
8015                    if (metaDataKey != null
8016                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8017                        continue;
8018                    }
8019                    final ComponentName component =
8020                            new ComponentName(p.info.packageName, p.info.name);
8021                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8022                        continue;
8023                    }
8024                    if (finalList == null) {
8025                        finalList = new ArrayList<ProviderInfo>(3);
8026                    }
8027                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8028                            ps.readUserState(userId), userId);
8029                    if (info != null) {
8030                        finalList.add(info);
8031                    }
8032                }
8033            }
8034        }
8035
8036        if (finalList != null) {
8037            Collections.sort(finalList, mProviderInitOrderSorter);
8038            return new ParceledListSlice<ProviderInfo>(finalList);
8039        }
8040
8041        return ParceledListSlice.emptyList();
8042    }
8043
8044    @Override
8045    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8046        // reader
8047        synchronized (mPackages) {
8048            final int callingUid = Binder.getCallingUid();
8049            final int callingUserId = UserHandle.getUserId(callingUid);
8050            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8051            if (ps == null) return null;
8052            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8053                return null;
8054            }
8055            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8056            return PackageParser.generateInstrumentationInfo(i, flags);
8057        }
8058    }
8059
8060    @Override
8061    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8062            String targetPackage, int flags) {
8063        final int callingUid = Binder.getCallingUid();
8064        final int callingUserId = UserHandle.getUserId(callingUid);
8065        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8066        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8067            return ParceledListSlice.emptyList();
8068        }
8069        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8070    }
8071
8072    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8073            int flags) {
8074        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8075
8076        // reader
8077        synchronized (mPackages) {
8078            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8079            while (i.hasNext()) {
8080                final PackageParser.Instrumentation p = i.next();
8081                if (targetPackage == null
8082                        || targetPackage.equals(p.info.targetPackage)) {
8083                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8084                            flags);
8085                    if (ii != null) {
8086                        finalList.add(ii);
8087                    }
8088                }
8089            }
8090        }
8091
8092        return finalList;
8093    }
8094
8095    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8096        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8097        try {
8098            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8099        } finally {
8100            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8101        }
8102    }
8103
8104    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8105        final File[] files = scanDir.listFiles();
8106        if (ArrayUtils.isEmpty(files)) {
8107            Log.d(TAG, "No files in app dir " + scanDir);
8108            return;
8109        }
8110
8111        if (DEBUG_PACKAGE_SCANNING) {
8112            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8113                    + " flags=0x" + Integer.toHexString(parseFlags));
8114        }
8115        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8116                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8117                mParallelPackageParserCallback)) {
8118            // Submit files for parsing in parallel
8119            int fileCount = 0;
8120            for (File file : files) {
8121                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8122                        && !PackageInstallerService.isStageName(file.getName());
8123                if (!isPackage) {
8124                    // Ignore entries which are not packages
8125                    continue;
8126                }
8127                parallelPackageParser.submit(file, parseFlags);
8128                fileCount++;
8129            }
8130
8131            // Process results one by one
8132            for (; fileCount > 0; fileCount--) {
8133                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8134                Throwable throwable = parseResult.throwable;
8135                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8136
8137                if (throwable == null) {
8138                    // TODO(toddke): move lower in the scan chain
8139                    // Static shared libraries have synthetic package names
8140                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8141                        renameStaticSharedLibraryPackage(parseResult.pkg);
8142                    }
8143                    try {
8144                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8145                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8146                                    currentTime, null);
8147                        }
8148                    } catch (PackageManagerException e) {
8149                        errorCode = e.error;
8150                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8151                    }
8152                } else if (throwable instanceof PackageParser.PackageParserException) {
8153                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8154                            throwable;
8155                    errorCode = e.error;
8156                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8157                } else {
8158                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8159                            + parseResult.scanFile, throwable);
8160                }
8161
8162                // Delete invalid userdata apps
8163                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8164                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8165                    logCriticalInfo(Log.WARN,
8166                            "Deleting invalid package at " + parseResult.scanFile);
8167                    removeCodePathLI(parseResult.scanFile);
8168                }
8169            }
8170        }
8171    }
8172
8173    public static void reportSettingsProblem(int priority, String msg) {
8174        logCriticalInfo(priority, msg);
8175    }
8176
8177    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8178            final @ParseFlags int parseFlags) throws PackageManagerException {
8179        // When upgrading from pre-N MR1, verify the package time stamp using the package
8180        // directory and not the APK file.
8181        final long lastModifiedTime = mIsPreNMR1Upgrade
8182                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8183        if (ps != null
8184                && ps.codePathString.equals(pkg.codePath)
8185                && ps.timeStamp == lastModifiedTime
8186                && !isCompatSignatureUpdateNeeded(pkg)
8187                && !isRecoverSignatureUpdateNeeded(pkg)) {
8188            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8189            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8190            ArraySet<PublicKey> signingKs;
8191            synchronized (mPackages) {
8192                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8193            }
8194            if (ps.signatures.mSignatures != null
8195                    && ps.signatures.mSignatures.length != 0
8196                    && signingKs != null) {
8197                // Optimization: reuse the existing cached certificates
8198                // if the package appears to be unchanged.
8199                pkg.mSignatures = ps.signatures.mSignatures;
8200                pkg.mSigningKeys = signingKs;
8201                return;
8202            }
8203
8204            Slog.w(TAG, "PackageSetting for " + ps.name
8205                    + " is missing signatures.  Collecting certs again to recover them.");
8206        } else {
8207            Slog.i(TAG, toString() + " changed; collecting certs");
8208        }
8209
8210        try {
8211            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8212            PackageParser.collectCertificates(pkg, parseFlags);
8213        } catch (PackageParserException e) {
8214            throw PackageManagerException.from(e);
8215        } finally {
8216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8217        }
8218    }
8219
8220    /**
8221     *  Traces a package scan.
8222     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8223     */
8224    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8225            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8226        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8227        try {
8228            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8229        } finally {
8230            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8231        }
8232    }
8233
8234    /**
8235     *  Scans a package and returns the newly parsed package.
8236     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8237     */
8238    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8239            long currentTime, UserHandle user) throws PackageManagerException {
8240        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8241        PackageParser pp = new PackageParser();
8242        pp.setSeparateProcesses(mSeparateProcesses);
8243        pp.setOnlyCoreApps(mOnlyCore);
8244        pp.setDisplayMetrics(mMetrics);
8245        pp.setCallback(mPackageParserCallback);
8246
8247        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8248        final PackageParser.Package pkg;
8249        try {
8250            pkg = pp.parsePackage(scanFile, parseFlags);
8251        } catch (PackageParserException e) {
8252            throw PackageManagerException.from(e);
8253        } finally {
8254            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8255        }
8256
8257        // Static shared libraries have synthetic package names
8258        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8259            renameStaticSharedLibraryPackage(pkg);
8260        }
8261
8262        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8263    }
8264
8265    /**
8266     *  Scans a package and returns the newly parsed package.
8267     *  @throws PackageManagerException on a parse error.
8268     */
8269    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8270            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8271            @Nullable UserHandle user)
8272                    throws PackageManagerException {
8273        // If the package has children and this is the first dive in the function
8274        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8275        // packages (parent and children) would be successfully scanned before the
8276        // actual scan since scanning mutates internal state and we want to atomically
8277        // install the package and its children.
8278        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8279            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8280                scanFlags |= SCAN_CHECK_ONLY;
8281            }
8282        } else {
8283            scanFlags &= ~SCAN_CHECK_ONLY;
8284        }
8285
8286        // Scan the parent
8287        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags,
8288                scanFlags, currentTime, user);
8289
8290        // Scan the children
8291        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8292        for (int i = 0; i < childCount; i++) {
8293            PackageParser.Package childPackage = pkg.childPackages.get(i);
8294            scanPackageInternalLI(childPackage, parseFlags, scanFlags,
8295                    currentTime, user);
8296        }
8297
8298
8299        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8300            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8301        }
8302
8303        return scannedPkg;
8304    }
8305
8306    /**
8307     *  Scans a package and returns the newly parsed package.
8308     *  @throws PackageManagerException on a parse error.
8309     */
8310    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg,
8311            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8312            @Nullable UserHandle user)
8313                    throws PackageManagerException {
8314        PackageSetting ps = null;
8315        PackageSetting updatedPs;
8316        // reader
8317        synchronized (mPackages) {
8318            // Look to see if we already know about this package.
8319            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8320            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8321                // This package has been renamed to its original name.  Let's
8322                // use that.
8323                ps = mSettings.getPackageLPr(oldName);
8324            }
8325            // If there was no original package, see one for the real package name.
8326            if (ps == null) {
8327                ps = mSettings.getPackageLPr(pkg.packageName);
8328            }
8329            // Check to see if this package could be hiding/updating a system
8330            // package.  Must look for it either under the original or real
8331            // package name depending on our state.
8332            updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8333            if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs);
8334
8335            // If this is a package we don't know about on the system partition, we
8336            // may need to remove disabled child packages on the system partition
8337            // or may need to not add child packages if the parent apk is updated
8338            // on the data partition and no longer defines this child package.
8339            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8340                // If this is a parent package for an updated system app and this system
8341                // app got an OTA update which no longer defines some of the child packages
8342                // we have to prune them from the disabled system packages.
8343                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8344                if (disabledPs != null) {
8345                    final int scannedChildCount = (pkg.childPackages != null)
8346                            ? pkg.childPackages.size() : 0;
8347                    final int disabledChildCount = disabledPs.childPackageNames != null
8348                            ? disabledPs.childPackageNames.size() : 0;
8349                    for (int i = 0; i < disabledChildCount; i++) {
8350                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8351                        boolean disabledPackageAvailable = false;
8352                        for (int j = 0; j < scannedChildCount; j++) {
8353                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8354                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8355                                disabledPackageAvailable = true;
8356                                break;
8357                            }
8358                         }
8359                         if (!disabledPackageAvailable) {
8360                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8361                         }
8362                    }
8363                }
8364            }
8365        }
8366
8367        final boolean isUpdatedPkg = updatedPs != null;
8368        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8369        boolean isUpdatedPkgBetter = false;
8370        // First check if this is a system package that may involve an update
8371        if (isUpdatedSystemPkg) {
8372            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8373            // it needs to drop FLAG_PRIVILEGED.
8374            if (locationIsPrivileged(pkg.codePath)) {
8375                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8376            } else {
8377                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8378            }
8379            // If new package is not located in "/oem" (e.g. due to an OTA),
8380            // it needs to drop FLAG_OEM.
8381            if (locationIsOem(pkg.codePath)) {
8382                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8383            } else {
8384                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8385            }
8386            // If new package is not located in "/vendor" (e.g. due to an OTA),
8387            // it needs to drop FLAG_VENDOR.
8388            if (locationIsVendor(pkg.codePath)) {
8389                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
8390            } else {
8391                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_VENDOR;
8392            }
8393
8394            if (ps != null && !ps.codePathString.equals(pkg.codePath)) {
8395                // The path has changed from what was last scanned...  check the
8396                // version of the new path against what we have stored to determine
8397                // what to do.
8398                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8399                if (pkg.getLongVersionCode() <= ps.versionCode) {
8400                    // The system package has been updated and the code path does not match
8401                    // Ignore entry. Skip it.
8402                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath
8403                            + " ignored: updated version " + ps.versionCode
8404                            + " better than this " + pkg.getLongVersionCode());
8405                    if (!updatedPs.codePathString.equals(pkg.codePath)) {
8406                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8407                                + ps.name + " changing from " + updatedPs.codePathString
8408                                + " to " + pkg.codePath);
8409                        final File codePath = new File(pkg.codePath);
8410                        updatedPs.codePath = codePath;
8411                        updatedPs.codePathString = pkg.codePath;
8412                        updatedPs.resourcePath = codePath;
8413                        updatedPs.resourcePathString = pkg.codePath;
8414                    }
8415                    updatedPs.pkg = pkg;
8416                    updatedPs.versionCode = pkg.getLongVersionCode();
8417
8418                    // Update the disabled system child packages to point to the package too.
8419                    final int childCount = updatedPs.childPackageNames != null
8420                            ? updatedPs.childPackageNames.size() : 0;
8421                    for (int i = 0; i < childCount; i++) {
8422                        String childPackageName = updatedPs.childPackageNames.get(i);
8423                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8424                                childPackageName);
8425                        if (updatedChildPkg != null) {
8426                            updatedChildPkg.pkg = pkg;
8427                            updatedChildPkg.versionCode = pkg.getLongVersionCode();
8428                        }
8429                    }
8430                } else {
8431                    // The current app on the system partition is better than
8432                    // what we have updated to on the data partition; switch
8433                    // back to the system partition version.
8434                    // At this point, its safely assumed that package installation for
8435                    // apps in system partition will go through. If not there won't be a working
8436                    // version of the app
8437                    // writer
8438                    synchronized (mPackages) {
8439                        // Just remove the loaded entries from package lists.
8440                        mPackages.remove(ps.name);
8441                    }
8442
8443                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8444                            + " reverting from " + ps.codePathString
8445                            + ": new version " + pkg.getLongVersionCode()
8446                            + " better than installed " + ps.versionCode);
8447
8448                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8449                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8450                    synchronized (mInstallLock) {
8451                        args.cleanUpResourcesLI();
8452                    }
8453                    synchronized (mPackages) {
8454                        mSettings.enableSystemPackageLPw(ps.name);
8455                    }
8456                    isUpdatedPkgBetter = true;
8457                }
8458            }
8459        }
8460
8461        String resourcePath = null;
8462        String baseResourcePath = null;
8463        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8464            if (ps != null && ps.resourcePathString != null) {
8465                resourcePath = ps.resourcePathString;
8466                baseResourcePath = ps.resourcePathString;
8467            } else {
8468                // Should not happen at all. Just log an error.
8469                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8470            }
8471        } else {
8472            resourcePath = pkg.codePath;
8473            baseResourcePath = pkg.baseCodePath;
8474        }
8475
8476        // Set application objects path explicitly.
8477        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8478        pkg.setApplicationInfoCodePath(pkg.codePath);
8479        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8480        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8481        pkg.setApplicationInfoResourcePath(resourcePath);
8482        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8483        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8484
8485        // throw an exception if we have an update to a system application, but, it's not more
8486        // recent than the package we've already scanned
8487        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8488            // Set CPU Abis to application info.
8489            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8490                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs);
8491                derivePackageAbi(pkg, cpuAbiOverride, false);
8492            } else {
8493                pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString;
8494                pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString;
8495            }
8496            pkg.mExtras = updatedPs;
8497
8498            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8499                    + pkg.codePath + " ignored: updated version " + updatedPs.versionCode
8500                    + " better than this " + pkg.getLongVersionCode());
8501        }
8502
8503        if (isUpdatedPkg) {
8504            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8505            scanFlags |= SCAN_AS_SYSTEM;
8506
8507            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8508            // flag set initially
8509            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8510                scanFlags |= SCAN_AS_PRIVILEGED;
8511            }
8512
8513            // An updated OEM app will not have the SCAN_AS_OEM
8514            // flag set initially
8515            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8516                scanFlags |= SCAN_AS_OEM;
8517            }
8518
8519            // An updated vendor app will not have the SCAN_AS_VENDOR
8520            // flag set initially
8521            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
8522                scanFlags |= SCAN_AS_VENDOR;
8523            }
8524        }
8525
8526        // Verify certificates against what was last scanned
8527        collectCertificatesLI(ps, pkg, parseFlags);
8528
8529        /*
8530         * A new system app appeared, but we already had a non-system one of the
8531         * same name installed earlier.
8532         */
8533        boolean shouldHideSystemApp = false;
8534        if (!isUpdatedPkg && ps != null
8535                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8536            /*
8537             * Check to make sure the signatures match first. If they don't,
8538             * wipe the installed application and its data.
8539             */
8540            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8541                    != PackageManager.SIGNATURE_MATCH) {
8542                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8543                        + " signatures don't match existing userdata copy; removing");
8544                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8545                        "scanPackageInternalLI")) {
8546                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8547                }
8548                ps = null;
8549            } else {
8550                /*
8551                 * If the newly-added system app is an older version than the
8552                 * already installed version, hide it. It will be scanned later
8553                 * and re-added like an update.
8554                 */
8555                if (pkg.getLongVersionCode() <= ps.versionCode) {
8556                    shouldHideSystemApp = true;
8557                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + pkg.codePath
8558                            + " but new version " + pkg.getLongVersionCode()
8559                            + " better than installed " + ps.versionCode + "; hiding system");
8560                } else {
8561                    /*
8562                     * The newly found system app is a newer version that the
8563                     * one previously installed. Simply remove the
8564                     * already-installed application and replace it with our own
8565                     * while keeping the application data.
8566                     */
8567                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8568                            + " reverting from " + ps.codePathString + ": new version "
8569                            + pkg.getLongVersionCode() + " better than installed "
8570                            + ps.versionCode);
8571                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8572                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8573                    synchronized (mInstallLock) {
8574                        args.cleanUpResourcesLI();
8575                    }
8576                }
8577            }
8578        }
8579
8580        // The apk is forward locked (not public) if its code and resources
8581        // are kept in different files. (except for app in either system or
8582        // vendor path).
8583        // TODO grab this value from PackageSettings
8584        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8585            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8586                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
8587            }
8588        }
8589
8590        final int userId = ((user == null) ? 0 : user.getIdentifier());
8591        if (ps != null && ps.getInstantApp(userId)) {
8592            scanFlags |= SCAN_AS_INSTANT_APP;
8593        }
8594        if (ps != null && ps.getVirtulalPreload(userId)) {
8595            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8596        }
8597
8598        // Note that we invoke the following method only if we are about to unpack an application
8599        PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8600                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8601
8602        /*
8603         * If the system app should be overridden by a previously installed
8604         * data, hide the system app now and let the /data/app scan pick it up
8605         * again.
8606         */
8607        if (shouldHideSystemApp) {
8608            synchronized (mPackages) {
8609                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8610            }
8611        }
8612
8613        return scannedPkg;
8614    }
8615
8616    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8617        // Derive the new package synthetic package name
8618        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8619                + pkg.staticSharedLibVersion);
8620    }
8621
8622    private static String fixProcessName(String defProcessName,
8623            String processName) {
8624        if (processName == null) {
8625            return defProcessName;
8626        }
8627        return processName;
8628    }
8629
8630    /**
8631     * Enforces that only the system UID or root's UID can call a method exposed
8632     * via Binder.
8633     *
8634     * @param message used as message if SecurityException is thrown
8635     * @throws SecurityException if the caller is not system or root
8636     */
8637    private static final void enforceSystemOrRoot(String message) {
8638        final int uid = Binder.getCallingUid();
8639        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8640            throw new SecurityException(message);
8641        }
8642    }
8643
8644    @Override
8645    public void performFstrimIfNeeded() {
8646        enforceSystemOrRoot("Only the system can request fstrim");
8647
8648        // Before everything else, see whether we need to fstrim.
8649        try {
8650            IStorageManager sm = PackageHelper.getStorageManager();
8651            if (sm != null) {
8652                boolean doTrim = false;
8653                final long interval = android.provider.Settings.Global.getLong(
8654                        mContext.getContentResolver(),
8655                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8656                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8657                if (interval > 0) {
8658                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8659                    if (timeSinceLast > interval) {
8660                        doTrim = true;
8661                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8662                                + "; running immediately");
8663                    }
8664                }
8665                if (doTrim) {
8666                    final boolean dexOptDialogShown;
8667                    synchronized (mPackages) {
8668                        dexOptDialogShown = mDexOptDialogShown;
8669                    }
8670                    if (!isFirstBoot() && dexOptDialogShown) {
8671                        try {
8672                            ActivityManager.getService().showBootMessage(
8673                                    mContext.getResources().getString(
8674                                            R.string.android_upgrading_fstrim), true);
8675                        } catch (RemoteException e) {
8676                        }
8677                    }
8678                    sm.runMaintenance();
8679                }
8680            } else {
8681                Slog.e(TAG, "storageManager service unavailable!");
8682            }
8683        } catch (RemoteException e) {
8684            // Can't happen; StorageManagerService is local
8685        }
8686    }
8687
8688    @Override
8689    public void updatePackagesIfNeeded() {
8690        enforceSystemOrRoot("Only the system can request package update");
8691
8692        // We need to re-extract after an OTA.
8693        boolean causeUpgrade = isUpgrade();
8694
8695        // First boot or factory reset.
8696        // Note: we also handle devices that are upgrading to N right now as if it is their
8697        //       first boot, as they do not have profile data.
8698        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8699
8700        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8701        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8702
8703        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8704            return;
8705        }
8706
8707        List<PackageParser.Package> pkgs;
8708        synchronized (mPackages) {
8709            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8710        }
8711
8712        final long startTime = System.nanoTime();
8713        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8714                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8715                    false /* bootComplete */);
8716
8717        final int elapsedTimeSeconds =
8718                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8719
8720        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8721        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8722        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8723        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8724        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8725    }
8726
8727    /*
8728     * Return the prebuilt profile path given a package base code path.
8729     */
8730    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8731        return pkg.baseCodePath + ".prof";
8732    }
8733
8734    /**
8735     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8736     * containing statistics about the invocation. The array consists of three elements,
8737     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8738     * and {@code numberOfPackagesFailed}.
8739     */
8740    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8741            final String compilerFilter, boolean bootComplete) {
8742
8743        int numberOfPackagesVisited = 0;
8744        int numberOfPackagesOptimized = 0;
8745        int numberOfPackagesSkipped = 0;
8746        int numberOfPackagesFailed = 0;
8747        final int numberOfPackagesToDexopt = pkgs.size();
8748
8749        for (PackageParser.Package pkg : pkgs) {
8750            numberOfPackagesVisited++;
8751
8752            boolean useProfileForDexopt = false;
8753
8754            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8755                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8756                // that are already compiled.
8757                File profileFile = new File(getPrebuildProfilePath(pkg));
8758                // Copy profile if it exists.
8759                if (profileFile.exists()) {
8760                    try {
8761                        // We could also do this lazily before calling dexopt in
8762                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8763                        // is that we don't have a good way to say "do this only once".
8764                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8765                                pkg.applicationInfo.uid, pkg.packageName)) {
8766                            Log.e(TAG, "Installer failed to copy system profile!");
8767                        } else {
8768                            // Disabled as this causes speed-profile compilation during first boot
8769                            // even if things are already compiled.
8770                            // useProfileForDexopt = true;
8771                        }
8772                    } catch (Exception e) {
8773                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8774                                e);
8775                    }
8776                } else {
8777                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8778                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8779                    // minimize the number off apps being speed-profile compiled during first boot.
8780                    // The other paths will not change the filter.
8781                    if (disabledPs != null && disabledPs.pkg.isStub) {
8782                        // The package is the stub one, remove the stub suffix to get the normal
8783                        // package and APK names.
8784                        String systemProfilePath =
8785                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8786                        profileFile = new File(systemProfilePath);
8787                        // If we have a profile for a compressed APK, copy it to the reference
8788                        // location.
8789                        // Note that copying the profile here will cause it to override the
8790                        // reference profile every OTA even though the existing reference profile
8791                        // may have more data. We can't copy during decompression since the
8792                        // directories are not set up at that point.
8793                        if (profileFile.exists()) {
8794                            try {
8795                                // We could also do this lazily before calling dexopt in
8796                                // PackageDexOptimizer to prevent this happening on first boot. The
8797                                // issue is that we don't have a good way to say "do this only
8798                                // once".
8799                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8800                                        pkg.applicationInfo.uid, pkg.packageName)) {
8801                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8802                                } else {
8803                                    useProfileForDexopt = true;
8804                                }
8805                            } catch (Exception e) {
8806                                Log.e(TAG, "Failed to copy profile " +
8807                                        profileFile.getAbsolutePath() + " ", e);
8808                            }
8809                        }
8810                    }
8811                }
8812            }
8813
8814            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8815                if (DEBUG_DEXOPT) {
8816                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8817                }
8818                numberOfPackagesSkipped++;
8819                continue;
8820            }
8821
8822            if (DEBUG_DEXOPT) {
8823                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8824                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8825            }
8826
8827            if (showDialog) {
8828                try {
8829                    ActivityManager.getService().showBootMessage(
8830                            mContext.getResources().getString(R.string.android_upgrading_apk,
8831                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8832                } catch (RemoteException e) {
8833                }
8834                synchronized (mPackages) {
8835                    mDexOptDialogShown = true;
8836                }
8837            }
8838
8839            String pkgCompilerFilter = compilerFilter;
8840            if (useProfileForDexopt) {
8841                // Use background dexopt mode to try and use the profile. Note that this does not
8842                // guarantee usage of the profile.
8843                pkgCompilerFilter =
8844                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8845                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8846            }
8847
8848            // checkProfiles is false to avoid merging profiles during boot which
8849            // might interfere with background compilation (b/28612421).
8850            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8851            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8852            // trade-off worth doing to save boot time work.
8853            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8854            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8855                    pkg.packageName,
8856                    pkgCompilerFilter,
8857                    dexoptFlags));
8858
8859            switch (primaryDexOptStaus) {
8860                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8861                    numberOfPackagesOptimized++;
8862                    break;
8863                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8864                    numberOfPackagesSkipped++;
8865                    break;
8866                case PackageDexOptimizer.DEX_OPT_FAILED:
8867                    numberOfPackagesFailed++;
8868                    break;
8869                default:
8870                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8871                    break;
8872            }
8873        }
8874
8875        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8876                numberOfPackagesFailed };
8877    }
8878
8879    @Override
8880    public void notifyPackageUse(String packageName, int reason) {
8881        synchronized (mPackages) {
8882            final int callingUid = Binder.getCallingUid();
8883            final int callingUserId = UserHandle.getUserId(callingUid);
8884            if (getInstantAppPackageName(callingUid) != null) {
8885                if (!isCallerSameApp(packageName, callingUid)) {
8886                    return;
8887                }
8888            } else {
8889                if (isInstantApp(packageName, callingUserId)) {
8890                    return;
8891                }
8892            }
8893            notifyPackageUseLocked(packageName, reason);
8894        }
8895    }
8896
8897    private void notifyPackageUseLocked(String packageName, int reason) {
8898        final PackageParser.Package p = mPackages.get(packageName);
8899        if (p == null) {
8900            return;
8901        }
8902        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8903    }
8904
8905    @Override
8906    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8907            List<String> classPaths, String loaderIsa) {
8908        int userId = UserHandle.getCallingUserId();
8909        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8910        if (ai == null) {
8911            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8912                + loadingPackageName + ", user=" + userId);
8913            return;
8914        }
8915        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8916    }
8917
8918    @Override
8919    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8920            IDexModuleRegisterCallback callback) {
8921        int userId = UserHandle.getCallingUserId();
8922        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8923        DexManager.RegisterDexModuleResult result;
8924        if (ai == null) {
8925            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8926                     " calling user. package=" + packageName + ", user=" + userId);
8927            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8928        } else {
8929            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8930        }
8931
8932        if (callback != null) {
8933            mHandler.post(() -> {
8934                try {
8935                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8936                } catch (RemoteException e) {
8937                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8938                }
8939            });
8940        }
8941    }
8942
8943    /**
8944     * Ask the package manager to perform a dex-opt with the given compiler filter.
8945     *
8946     * Note: exposed only for the shell command to allow moving packages explicitly to a
8947     *       definite state.
8948     */
8949    @Override
8950    public boolean performDexOptMode(String packageName,
8951            boolean checkProfiles, String targetCompilerFilter, boolean force,
8952            boolean bootComplete, String splitName) {
8953        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8954                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8955                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8956        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8957                splitName, flags));
8958    }
8959
8960    /**
8961     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8962     * secondary dex files belonging to the given package.
8963     *
8964     * Note: exposed only for the shell command to allow moving packages explicitly to a
8965     *       definite state.
8966     */
8967    @Override
8968    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8969            boolean force) {
8970        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8971                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8972                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8973                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8974        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8975    }
8976
8977    /*package*/ boolean performDexOpt(DexoptOptions options) {
8978        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8979            return false;
8980        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8981            return false;
8982        }
8983
8984        if (options.isDexoptOnlySecondaryDex()) {
8985            return mDexManager.dexoptSecondaryDex(options);
8986        } else {
8987            int dexoptStatus = performDexOptWithStatus(options);
8988            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8989        }
8990    }
8991
8992    /**
8993     * Perform dexopt on the given package and return one of following result:
8994     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8995     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8996     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8997     */
8998    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8999        return performDexOptTraced(options);
9000    }
9001
9002    private int performDexOptTraced(DexoptOptions options) {
9003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9004        try {
9005            return performDexOptInternal(options);
9006        } finally {
9007            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9008        }
9009    }
9010
9011    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9012    // if the package can now be considered up to date for the given filter.
9013    private int performDexOptInternal(DexoptOptions options) {
9014        PackageParser.Package p;
9015        synchronized (mPackages) {
9016            p = mPackages.get(options.getPackageName());
9017            if (p == null) {
9018                // Package could not be found. Report failure.
9019                return PackageDexOptimizer.DEX_OPT_FAILED;
9020            }
9021            mPackageUsage.maybeWriteAsync(mPackages);
9022            mCompilerStats.maybeWriteAsync();
9023        }
9024        long callingId = Binder.clearCallingIdentity();
9025        try {
9026            synchronized (mInstallLock) {
9027                return performDexOptInternalWithDependenciesLI(p, options);
9028            }
9029        } finally {
9030            Binder.restoreCallingIdentity(callingId);
9031        }
9032    }
9033
9034    public ArraySet<String> getOptimizablePackages() {
9035        ArraySet<String> pkgs = new ArraySet<String>();
9036        synchronized (mPackages) {
9037            for (PackageParser.Package p : mPackages.values()) {
9038                if (PackageDexOptimizer.canOptimizePackage(p)) {
9039                    pkgs.add(p.packageName);
9040                }
9041            }
9042        }
9043        return pkgs;
9044    }
9045
9046    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9047            DexoptOptions options) {
9048        // Select the dex optimizer based on the force parameter.
9049        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9050        //       allocate an object here.
9051        PackageDexOptimizer pdo = options.isForce()
9052                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9053                : mPackageDexOptimizer;
9054
9055        // Dexopt all dependencies first. Note: we ignore the return value and march on
9056        // on errors.
9057        // Note that we are going to call performDexOpt on those libraries as many times as
9058        // they are referenced in packages. When we do a batch of performDexOpt (for example
9059        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9060        // and the first package that uses the library will dexopt it. The
9061        // others will see that the compiled code for the library is up to date.
9062        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9063        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9064        if (!deps.isEmpty()) {
9065            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9066                    options.getCompilerFilter(), options.getSplitName(),
9067                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9068            for (PackageParser.Package depPackage : deps) {
9069                // TODO: Analyze and investigate if we (should) profile libraries.
9070                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9071                        getOrCreateCompilerPackageStats(depPackage),
9072                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9073            }
9074        }
9075        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9076                getOrCreateCompilerPackageStats(p),
9077                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9078    }
9079
9080    /**
9081     * Reconcile the information we have about the secondary dex files belonging to
9082     * {@code packagName} and the actual dex files. For all dex files that were
9083     * deleted, update the internal records and delete the generated oat files.
9084     */
9085    @Override
9086    public void reconcileSecondaryDexFiles(String packageName) {
9087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9088            return;
9089        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9090            return;
9091        }
9092        mDexManager.reconcileSecondaryDexFiles(packageName);
9093    }
9094
9095    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9096    // a reference there.
9097    /*package*/ DexManager getDexManager() {
9098        return mDexManager;
9099    }
9100
9101    /**
9102     * Execute the background dexopt job immediately.
9103     */
9104    @Override
9105    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9106        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9107            return false;
9108        }
9109        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9110    }
9111
9112    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9113        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9114                || p.usesStaticLibraries != null) {
9115            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9116            Set<String> collectedNames = new HashSet<>();
9117            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9118
9119            retValue.remove(p);
9120
9121            return retValue;
9122        } else {
9123            return Collections.emptyList();
9124        }
9125    }
9126
9127    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9128            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9129        if (!collectedNames.contains(p.packageName)) {
9130            collectedNames.add(p.packageName);
9131            collected.add(p);
9132
9133            if (p.usesLibraries != null) {
9134                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9135                        null, collected, collectedNames);
9136            }
9137            if (p.usesOptionalLibraries != null) {
9138                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9139                        null, collected, collectedNames);
9140            }
9141            if (p.usesStaticLibraries != null) {
9142                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9143                        p.usesStaticLibrariesVersions, collected, collectedNames);
9144            }
9145        }
9146    }
9147
9148    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9149            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9150        final int libNameCount = libs.size();
9151        for (int i = 0; i < libNameCount; i++) {
9152            String libName = libs.get(i);
9153            long version = (versions != null && versions.length == libNameCount)
9154                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9155            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9156            if (libPkg != null) {
9157                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9158            }
9159        }
9160    }
9161
9162    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9163        synchronized (mPackages) {
9164            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9165            if (libEntry != null) {
9166                return mPackages.get(libEntry.apk);
9167            }
9168            return null;
9169        }
9170    }
9171
9172    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9173        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9174        if (versionedLib == null) {
9175            return null;
9176        }
9177        return versionedLib.get(version);
9178    }
9179
9180    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9181        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9182                pkg.staticSharedLibName);
9183        if (versionedLib == null) {
9184            return null;
9185        }
9186        long previousLibVersion = -1;
9187        final int versionCount = versionedLib.size();
9188        for (int i = 0; i < versionCount; i++) {
9189            final long libVersion = versionedLib.keyAt(i);
9190            if (libVersion < pkg.staticSharedLibVersion) {
9191                previousLibVersion = Math.max(previousLibVersion, libVersion);
9192            }
9193        }
9194        if (previousLibVersion >= 0) {
9195            return versionedLib.get(previousLibVersion);
9196        }
9197        return null;
9198    }
9199
9200    public void shutdown() {
9201        mPackageUsage.writeNow(mPackages);
9202        mCompilerStats.writeNow();
9203        mDexManager.writePackageDexUsageNow();
9204    }
9205
9206    @Override
9207    public void dumpProfiles(String packageName) {
9208        PackageParser.Package pkg;
9209        synchronized (mPackages) {
9210            pkg = mPackages.get(packageName);
9211            if (pkg == null) {
9212                throw new IllegalArgumentException("Unknown package: " + packageName);
9213            }
9214        }
9215        /* Only the shell, root, or the app user should be able to dump profiles. */
9216        int callingUid = Binder.getCallingUid();
9217        if (callingUid != Process.SHELL_UID &&
9218            callingUid != Process.ROOT_UID &&
9219            callingUid != pkg.applicationInfo.uid) {
9220            throw new SecurityException("dumpProfiles");
9221        }
9222
9223        synchronized (mInstallLock) {
9224            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9225            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9226            try {
9227                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9228                String codePaths = TextUtils.join(";", allCodePaths);
9229                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9230            } catch (InstallerException e) {
9231                Slog.w(TAG, "Failed to dump profiles", e);
9232            }
9233            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9234        }
9235    }
9236
9237    @Override
9238    public void forceDexOpt(String packageName) {
9239        enforceSystemOrRoot("forceDexOpt");
9240
9241        PackageParser.Package pkg;
9242        synchronized (mPackages) {
9243            pkg = mPackages.get(packageName);
9244            if (pkg == null) {
9245                throw new IllegalArgumentException("Unknown package: " + packageName);
9246            }
9247        }
9248
9249        synchronized (mInstallLock) {
9250            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9251
9252            // Whoever is calling forceDexOpt wants a compiled package.
9253            // Don't use profiles since that may cause compilation to be skipped.
9254            final int res = performDexOptInternalWithDependenciesLI(
9255                    pkg,
9256                    new DexoptOptions(packageName,
9257                            getDefaultCompilerFilter(),
9258                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9259
9260            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9261            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9262                throw new IllegalStateException("Failed to dexopt: " + res);
9263            }
9264        }
9265    }
9266
9267    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9268        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9269            Slog.w(TAG, "Unable to update from " + oldPkg.name
9270                    + " to " + newPkg.packageName
9271                    + ": old package not in system partition");
9272            return false;
9273        } else if (mPackages.get(oldPkg.name) != null) {
9274            Slog.w(TAG, "Unable to update from " + oldPkg.name
9275                    + " to " + newPkg.packageName
9276                    + ": old package still exists");
9277            return false;
9278        }
9279        return true;
9280    }
9281
9282    void removeCodePathLI(File codePath) {
9283        if (codePath.isDirectory()) {
9284            try {
9285                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9286            } catch (InstallerException e) {
9287                Slog.w(TAG, "Failed to remove code path", e);
9288            }
9289        } else {
9290            codePath.delete();
9291        }
9292    }
9293
9294    private int[] resolveUserIds(int userId) {
9295        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9296    }
9297
9298    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9299        if (pkg == null) {
9300            Slog.wtf(TAG, "Package was null!", new Throwable());
9301            return;
9302        }
9303        clearAppDataLeafLIF(pkg, userId, flags);
9304        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9305        for (int i = 0; i < childCount; i++) {
9306            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9307        }
9308    }
9309
9310    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9311        final PackageSetting ps;
9312        synchronized (mPackages) {
9313            ps = mSettings.mPackages.get(pkg.packageName);
9314        }
9315        for (int realUserId : resolveUserIds(userId)) {
9316            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9317            try {
9318                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9319                        ceDataInode);
9320            } catch (InstallerException e) {
9321                Slog.w(TAG, String.valueOf(e));
9322            }
9323        }
9324    }
9325
9326    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9327        if (pkg == null) {
9328            Slog.wtf(TAG, "Package was null!", new Throwable());
9329            return;
9330        }
9331        destroyAppDataLeafLIF(pkg, userId, flags);
9332        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9333        for (int i = 0; i < childCount; i++) {
9334            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9335        }
9336    }
9337
9338    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9339        final PackageSetting ps;
9340        synchronized (mPackages) {
9341            ps = mSettings.mPackages.get(pkg.packageName);
9342        }
9343        for (int realUserId : resolveUserIds(userId)) {
9344            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9345            try {
9346                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9347                        ceDataInode);
9348            } catch (InstallerException e) {
9349                Slog.w(TAG, String.valueOf(e));
9350            }
9351            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9352        }
9353    }
9354
9355    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9356        if (pkg == null) {
9357            Slog.wtf(TAG, "Package was null!", new Throwable());
9358            return;
9359        }
9360        destroyAppProfilesLeafLIF(pkg);
9361        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9362        for (int i = 0; i < childCount; i++) {
9363            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9364        }
9365    }
9366
9367    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9368        try {
9369            mInstaller.destroyAppProfiles(pkg.packageName);
9370        } catch (InstallerException e) {
9371            Slog.w(TAG, String.valueOf(e));
9372        }
9373    }
9374
9375    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9376        if (pkg == null) {
9377            Slog.wtf(TAG, "Package was null!", new Throwable());
9378            return;
9379        }
9380        clearAppProfilesLeafLIF(pkg);
9381        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9382        for (int i = 0; i < childCount; i++) {
9383            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9384        }
9385    }
9386
9387    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9388        try {
9389            mInstaller.clearAppProfiles(pkg.packageName);
9390        } catch (InstallerException e) {
9391            Slog.w(TAG, String.valueOf(e));
9392        }
9393    }
9394
9395    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9396            long lastUpdateTime) {
9397        // Set parent install/update time
9398        PackageSetting ps = (PackageSetting) pkg.mExtras;
9399        if (ps != null) {
9400            ps.firstInstallTime = firstInstallTime;
9401            ps.lastUpdateTime = lastUpdateTime;
9402        }
9403        // Set children install/update time
9404        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9405        for (int i = 0; i < childCount; i++) {
9406            PackageParser.Package childPkg = pkg.childPackages.get(i);
9407            ps = (PackageSetting) childPkg.mExtras;
9408            if (ps != null) {
9409                ps.firstInstallTime = firstInstallTime;
9410                ps.lastUpdateTime = lastUpdateTime;
9411            }
9412        }
9413    }
9414
9415    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9416            SharedLibraryEntry file,
9417            PackageParser.Package changingLib) {
9418        if (file.path != null) {
9419            usesLibraryFiles.add(file.path);
9420            return;
9421        }
9422        PackageParser.Package p = mPackages.get(file.apk);
9423        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9424            // If we are doing this while in the middle of updating a library apk,
9425            // then we need to make sure to use that new apk for determining the
9426            // dependencies here.  (We haven't yet finished committing the new apk
9427            // to the package manager state.)
9428            if (p == null || p.packageName.equals(changingLib.packageName)) {
9429                p = changingLib;
9430            }
9431        }
9432        if (p != null) {
9433            usesLibraryFiles.addAll(p.getAllCodePaths());
9434            if (p.usesLibraryFiles != null) {
9435                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9436            }
9437        }
9438    }
9439
9440    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9441            PackageParser.Package changingLib) throws PackageManagerException {
9442        if (pkg == null) {
9443            return;
9444        }
9445        // The collection used here must maintain the order of addition (so
9446        // that libraries are searched in the correct order) and must have no
9447        // duplicates.
9448        Set<String> usesLibraryFiles = null;
9449        if (pkg.usesLibraries != null) {
9450            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9451                    null, null, pkg.packageName, changingLib, true,
9452                    pkg.applicationInfo.targetSdkVersion, null);
9453        }
9454        if (pkg.usesStaticLibraries != null) {
9455            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9456                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9457                    pkg.packageName, changingLib, true,
9458                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9459        }
9460        if (pkg.usesOptionalLibraries != null) {
9461            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9462                    null, null, pkg.packageName, changingLib, false,
9463                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9464        }
9465        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9466            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9467        } else {
9468            pkg.usesLibraryFiles = null;
9469        }
9470    }
9471
9472    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9473            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9474            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9475            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9476            throws PackageManagerException {
9477        final int libCount = requestedLibraries.size();
9478        for (int i = 0; i < libCount; i++) {
9479            final String libName = requestedLibraries.get(i);
9480            final long libVersion = requiredVersions != null ? requiredVersions[i]
9481                    : SharedLibraryInfo.VERSION_UNDEFINED;
9482            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9483            if (libEntry == null) {
9484                if (required) {
9485                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9486                            "Package " + packageName + " requires unavailable shared library "
9487                                    + libName + "; failing!");
9488                } else if (DEBUG_SHARED_LIBRARIES) {
9489                    Slog.i(TAG, "Package " + packageName
9490                            + " desires unavailable shared library "
9491                            + libName + "; ignoring!");
9492                }
9493            } else {
9494                if (requiredVersions != null && requiredCertDigests != null) {
9495                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9496                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9497                            "Package " + packageName + " requires unavailable static shared"
9498                                    + " library " + libName + " version "
9499                                    + libEntry.info.getLongVersion() + "; failing!");
9500                    }
9501
9502                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9503                    if (libPkg == null) {
9504                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9505                                "Package " + packageName + " requires unavailable static shared"
9506                                        + " library; failing!");
9507                    }
9508
9509                    final String[] expectedCertDigests = requiredCertDigests[i];
9510                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9511                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9512                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9513                            : PackageUtils.computeSignaturesSha256Digests(
9514                                    new Signature[]{libPkg.mSignatures[0]});
9515
9516                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9517                    // target O we don't parse the "additional-certificate" tags similarly
9518                    // how we only consider all certs only for apps targeting O (see above).
9519                    // Therefore, the size check is safe to make.
9520                    if (expectedCertDigests.length != libCertDigests.length) {
9521                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9522                                "Package " + packageName + " requires differently signed" +
9523                                        " static shared library; failing!");
9524                    }
9525
9526                    // Use a predictable order as signature order may vary
9527                    Arrays.sort(libCertDigests);
9528                    Arrays.sort(expectedCertDigests);
9529
9530                    final int certCount = libCertDigests.length;
9531                    for (int j = 0; j < certCount; j++) {
9532                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9533                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9534                                    "Package " + packageName + " requires differently signed" +
9535                                            " static shared library; failing!");
9536                        }
9537                    }
9538                }
9539
9540                if (outUsedLibraries == null) {
9541                    // Use LinkedHashSet to preserve the order of files added to
9542                    // usesLibraryFiles while eliminating duplicates.
9543                    outUsedLibraries = new LinkedHashSet<>();
9544                }
9545                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9546            }
9547        }
9548        return outUsedLibraries;
9549    }
9550
9551    private static boolean hasString(List<String> list, List<String> which) {
9552        if (list == null) {
9553            return false;
9554        }
9555        for (int i=list.size()-1; i>=0; i--) {
9556            for (int j=which.size()-1; j>=0; j--) {
9557                if (which.get(j).equals(list.get(i))) {
9558                    return true;
9559                }
9560            }
9561        }
9562        return false;
9563    }
9564
9565    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9566            PackageParser.Package changingPkg) {
9567        ArrayList<PackageParser.Package> res = null;
9568        for (PackageParser.Package pkg : mPackages.values()) {
9569            if (changingPkg != null
9570                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9571                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9572                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9573                            changingPkg.staticSharedLibName)) {
9574                return null;
9575            }
9576            if (res == null) {
9577                res = new ArrayList<>();
9578            }
9579            res.add(pkg);
9580            try {
9581                updateSharedLibrariesLPr(pkg, changingPkg);
9582            } catch (PackageManagerException e) {
9583                // If a system app update or an app and a required lib missing we
9584                // delete the package and for updated system apps keep the data as
9585                // it is better for the user to reinstall than to be in an limbo
9586                // state. Also libs disappearing under an app should never happen
9587                // - just in case.
9588                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9589                    final int flags = pkg.isUpdatedSystemApp()
9590                            ? PackageManager.DELETE_KEEP_DATA : 0;
9591                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9592                            flags , null, true, null);
9593                }
9594                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9595            }
9596        }
9597        return res;
9598    }
9599
9600    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9601            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9602            @Nullable UserHandle user) throws PackageManagerException {
9603        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9604        // If the package has children and this is the first dive in the function
9605        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9606        // whether all packages (parent and children) would be successfully scanned
9607        // before the actual scan since scanning mutates internal state and we want
9608        // to atomically install the package and its children.
9609        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9610            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9611                scanFlags |= SCAN_CHECK_ONLY;
9612            }
9613        } else {
9614            scanFlags &= ~SCAN_CHECK_ONLY;
9615        }
9616
9617        final PackageParser.Package scannedPkg;
9618        try {
9619            // Scan the parent
9620            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9621            // Scan the children
9622            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9623            for (int i = 0; i < childCount; i++) {
9624                PackageParser.Package childPkg = pkg.childPackages.get(i);
9625                scanPackageNewLI(childPkg, parseFlags,
9626                        scanFlags, currentTime, user);
9627            }
9628        } finally {
9629            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9630        }
9631
9632        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9633            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9634        }
9635
9636        return scannedPkg;
9637    }
9638
9639    /** The result of a package scan. */
9640    private static class ScanResult {
9641        /** Whether or not the package scan was successful */
9642        public final boolean success;
9643        /**
9644         * The final package settings. This may be the same object passed in
9645         * the {@link ScanRequest}, but, with modified values.
9646         */
9647        @Nullable public final PackageSetting pkgSetting;
9648        /** ABI code paths that have changed in the package scan */
9649        @Nullable public final List<String> changedAbiCodePath;
9650        public ScanResult(
9651                boolean success,
9652                @Nullable PackageSetting pkgSetting,
9653                @Nullable List<String> changedAbiCodePath) {
9654            this.success = success;
9655            this.pkgSetting = pkgSetting;
9656            this.changedAbiCodePath = changedAbiCodePath;
9657        }
9658    }
9659
9660    /** A package to be scanned */
9661    private static class ScanRequest {
9662        /** The parsed package */
9663        @NonNull public final PackageParser.Package pkg;
9664        /** Shared user settings, if the package has a shared user */
9665        @Nullable public final SharedUserSetting sharedUserSetting;
9666        /**
9667         * Package settings of the currently installed version.
9668         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9669         * during scan.
9670         */
9671        @Nullable public final PackageSetting pkgSetting;
9672        /** A copy of the settings for the currently installed version */
9673        @Nullable public final PackageSetting oldPkgSetting;
9674        /** Package settings for the disabled version on the /system partition */
9675        @Nullable public final PackageSetting disabledPkgSetting;
9676        /** Package settings for the installed version under its original package name */
9677        @Nullable public final PackageSetting originalPkgSetting;
9678        /** The real package name of a renamed application */
9679        @Nullable public final String realPkgName;
9680        public final @ParseFlags int parseFlags;
9681        public final @ScanFlags int scanFlags;
9682        /** The user for which the package is being scanned */
9683        @Nullable public final UserHandle user;
9684        /** Whether or not the platform package is being scanned */
9685        public final boolean isPlatformPackage;
9686        public ScanRequest(
9687                @NonNull PackageParser.Package pkg,
9688                @Nullable SharedUserSetting sharedUserSetting,
9689                @Nullable PackageSetting pkgSetting,
9690                @Nullable PackageSetting disabledPkgSetting,
9691                @Nullable PackageSetting originalPkgSetting,
9692                @Nullable String realPkgName,
9693                @ParseFlags int parseFlags,
9694                @ScanFlags int scanFlags,
9695                boolean isPlatformPackage,
9696                @Nullable UserHandle user) {
9697            this.pkg = pkg;
9698            this.pkgSetting = pkgSetting;
9699            this.sharedUserSetting = sharedUserSetting;
9700            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9701            this.disabledPkgSetting = disabledPkgSetting;
9702            this.originalPkgSetting = originalPkgSetting;
9703            this.realPkgName = realPkgName;
9704            this.parseFlags = parseFlags;
9705            this.scanFlags = scanFlags;
9706            this.isPlatformPackage = isPlatformPackage;
9707            this.user = user;
9708        }
9709    }
9710
9711    @GuardedBy("mInstallLock")
9712    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9713            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9714            @Nullable UserHandle user) throws PackageManagerException {
9715
9716        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9717        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9718        if (realPkgName != null) {
9719            ensurePackageRenamed(pkg, renamedPkgName);
9720        }
9721        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9722        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9723        final PackageSetting disabledPkgSetting =
9724                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9725
9726        if (mTransferedPackages.contains(pkg.packageName)) {
9727            Slog.w(TAG, "Package " + pkg.packageName
9728                    + " was transferred to another, but its .apk remains");
9729        }
9730
9731        synchronized (mPackages) {
9732            applyPolicy(pkg, parseFlags, scanFlags);
9733            assertPackageIsValid(pkg, parseFlags, scanFlags);
9734
9735            SharedUserSetting sharedUserSetting = null;
9736            if (pkg.mSharedUserId != null) {
9737                // SIDE EFFECTS; may potentially allocate a new shared user
9738                sharedUserSetting = mSettings.getSharedUserLPw(
9739                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9740                if (DEBUG_PACKAGE_SCANNING) {
9741                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9742                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9743                                + " (uid=" + sharedUserSetting.userId + "):"
9744                                + " packages=" + sharedUserSetting.packages);
9745                }
9746            }
9747
9748            boolean scanSucceeded = false;
9749            try {
9750                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9751                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9752                        (pkg == mPlatformPackage), user);
9753                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9754                if (result.success) {
9755                    commitScanResultsLocked(request, result);
9756                }
9757                scanSucceeded = true;
9758            } finally {
9759                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9760                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9761                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9762                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9763                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9764                  }
9765            }
9766        }
9767        return pkg;
9768    }
9769
9770    /**
9771     * Commits the package scan and modifies system state.
9772     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9773     * of committing the package, leaving the system in an inconsistent state.
9774     * This needs to be fixed so, once we get to this point, no errors are
9775     * possible and the system is not left in an inconsistent state.
9776     */
9777    @GuardedBy("mPackages")
9778    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9779            throws PackageManagerException {
9780        final PackageParser.Package pkg = request.pkg;
9781        final @ParseFlags int parseFlags = request.parseFlags;
9782        final @ScanFlags int scanFlags = request.scanFlags;
9783        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9784        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9785        final UserHandle user = request.user;
9786        final String realPkgName = request.realPkgName;
9787        final PackageSetting pkgSetting = result.pkgSetting;
9788        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9789        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9790
9791        if (newPkgSettingCreated) {
9792            if (originalPkgSetting != null) {
9793                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9794            }
9795            // THROWS: when we can't allocate a user id. add call to check if there's
9796            // enough space to ensure we won't throw; otherwise, don't modify state
9797            mSettings.addUserToSettingLPw(pkgSetting);
9798
9799            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
9800                mTransferedPackages.add(originalPkgSetting.name);
9801            }
9802        }
9803        // TODO(toddke): Consider a method specifically for modifying the Package object
9804        // post scan; or, moving this stuff out of the Package object since it has nothing
9805        // to do with the package on disk.
9806        // We need to have this here because addUserToSettingLPw() is sometimes responsible
9807        // for creating the application ID. If we did this earlier, we would be saving the
9808        // correct ID.
9809        pkg.applicationInfo.uid = pkgSetting.appId;
9810
9811        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9812
9813        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
9814            mTransferedPackages.add(pkg.packageName);
9815        }
9816
9817        // THROWS: when requested libraries that can't be found. it only changes
9818        // the state of the passed in pkg object, so, move to the top of the method
9819        // and allow it to abort
9820        if ((scanFlags & SCAN_BOOTING) == 0
9821                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9822            // Check all shared libraries and map to their actual file path.
9823            // We only do this here for apps not on a system dir, because those
9824            // are the only ones that can fail an install due to this.  We
9825            // will take care of the system apps by updating all of their
9826            // library paths after the scan is done. Also during the initial
9827            // scan don't update any libs as we do this wholesale after all
9828            // apps are scanned to avoid dependency based scanning.
9829            updateSharedLibrariesLPr(pkg, null);
9830        }
9831
9832        // All versions of a static shared library are referenced with the same
9833        // package name. Internally, we use a synthetic package name to allow
9834        // multiple versions of the same shared library to be installed. So,
9835        // we need to generate the synthetic package name of the latest shared
9836        // library in order to compare signatures.
9837        PackageSetting signatureCheckPs = pkgSetting;
9838        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9839            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9840            if (libraryEntry != null) {
9841                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9842            }
9843        }
9844
9845        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9846        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9847            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9848                // We just determined the app is signed correctly, so bring
9849                // over the latest parsed certs.
9850                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9851            } else {
9852                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9853                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9854                            "Package " + pkg.packageName + " upgrade keys do not match the "
9855                                    + "previously installed version");
9856                } else {
9857                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9858                    String msg = "System package " + pkg.packageName
9859                            + " signature changed; retaining data.";
9860                    reportSettingsProblem(Log.WARN, msg);
9861                }
9862            }
9863        } else {
9864            try {
9865                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9866                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9867                final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9868                        compareCompat, compareRecover);
9869                // The new KeySets will be re-added later in the scanning process.
9870                if (compatMatch) {
9871                    synchronized (mPackages) {
9872                        ksms.removeAppKeySetDataLPw(pkg.packageName);
9873                    }
9874                }
9875                // We just determined the app is signed correctly, so bring
9876                // over the latest parsed certs.
9877                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9878            } catch (PackageManagerException e) {
9879                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9880                    throw e;
9881                }
9882                // The signature has changed, but this package is in the system
9883                // image...  let's recover!
9884                pkgSetting.signatures.mSignatures = pkg.mSignatures;
9885                // However...  if this package is part of a shared user, but it
9886                // doesn't match the signature of the shared user, let's fail.
9887                // What this means is that you can't change the signatures
9888                // associated with an overall shared user, which doesn't seem all
9889                // that unreasonable.
9890                if (signatureCheckPs.sharedUser != null) {
9891                    if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9892                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9893                        throw new PackageManagerException(
9894                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9895                                "Signature mismatch for shared user: "
9896                                        + pkgSetting.sharedUser);
9897                    }
9898                }
9899                // File a report about this.
9900                String msg = "System package " + pkg.packageName
9901                        + " signature changed; retaining data.";
9902                reportSettingsProblem(Log.WARN, msg);
9903            }
9904        }
9905
9906        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9907            // This package wants to adopt ownership of permissions from
9908            // another package.
9909            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9910                final String origName = pkg.mAdoptPermissions.get(i);
9911                final PackageSetting orig = mSettings.getPackageLPr(origName);
9912                if (orig != null) {
9913                    if (verifyPackageUpdateLPr(orig, pkg)) {
9914                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
9915                                + pkg.packageName);
9916                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9917                    }
9918                }
9919            }
9920        }
9921
9922        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
9923            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
9924                final String codePathString = changedAbiCodePath.get(i);
9925                try {
9926                    mInstaller.rmdex(codePathString,
9927                            getDexCodeInstructionSet(getPreferredInstructionSet()));
9928                } catch (InstallerException ignored) {
9929                }
9930            }
9931        }
9932
9933        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9934            if (oldPkgSetting != null) {
9935                synchronized (mPackages) {
9936                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
9937                }
9938            }
9939        } else {
9940            final int userId = user == null ? 0 : user.getIdentifier();
9941            // Modify state for the given package setting
9942            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9943                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9944            if (pkgSetting.getInstantApp(userId)) {
9945                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9946            }
9947        }
9948    }
9949
9950    /**
9951     * Returns the "real" name of the package.
9952     * <p>This may differ from the package's actual name if the application has already
9953     * been installed under one of this package's original names.
9954     */
9955    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
9956            @Nullable String renamedPkgName) {
9957        if (pkg.mOriginalPackages == null || !pkg.mOriginalPackages.contains(renamedPkgName)) {
9958            return null;
9959        }
9960        return pkg.mRealPackage;
9961    }
9962
9963    /**
9964     * Returns the original package setting.
9965     * <p>A package can migrate its name during an update. In this scenario, a package
9966     * designates a set of names that it considers as one of its original names.
9967     * <p>An original package must be signed identically and it must have the same
9968     * shared user [if any].
9969     */
9970    @GuardedBy("mPackages")
9971    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
9972            @Nullable String renamedPkgName) {
9973        if (pkg.mOriginalPackages == null || pkg.mOriginalPackages.contains(renamedPkgName)) {
9974            return null;
9975        }
9976        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
9977            final PackageSetting originalPs =
9978                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
9979            if (originalPs != null) {
9980                // the package is already installed under its original name...
9981                // but, should we use it?
9982                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
9983                    // the new package is incompatible with the original
9984                    continue;
9985                } else if (originalPs.sharedUser != null) {
9986                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
9987                        // the shared user id is incompatible with the original
9988                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
9989                                + " to " + pkg.packageName + ": old uid "
9990                                + originalPs.sharedUser.name
9991                                + " differs from " + pkg.mSharedUserId);
9992                        continue;
9993                    }
9994                    // TODO: Add case when shared user id is added [b/28144775]
9995                } else {
9996                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9997                            + pkg.packageName + " to old name " + originalPs.name);
9998                }
9999                return originalPs;
10000            }
10001        }
10002        return null;
10003    }
10004
10005    /**
10006     * Renames the package if it was installed under a different name.
10007     * <p>When we've already installed the package under an original name, update
10008     * the new package so we can continue to have the old name.
10009     */
10010    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10011            @NonNull String renamedPackageName) {
10012        if (pkg.mOriginalPackages == null
10013                || !pkg.mOriginalPackages.contains(renamedPackageName)
10014                || pkg.packageName.equals(renamedPackageName)) {
10015            return;
10016        }
10017        pkg.setPackageName(renamedPackageName);
10018    }
10019
10020    /**
10021     * Just scans the package without any side effects.
10022     * <p>Not entirely true at the moment. There is still one side effect -- this
10023     * method potentially modifies a live {@link PackageSetting} object representing
10024     * the package being scanned. This will be resolved in the future.
10025     *
10026     * @param request Information about the package to be scanned
10027     * @param isUnderFactoryTest Whether or not the device is under factory test
10028     * @param currentTime The current time, in millis
10029     * @return The results of the scan
10030     */
10031    @GuardedBy("mInstallLock")
10032    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10033            boolean isUnderFactoryTest, long currentTime)
10034                    throws PackageManagerException {
10035        final PackageParser.Package pkg = request.pkg;
10036        PackageSetting pkgSetting = request.pkgSetting;
10037        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10038        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10039        final @ParseFlags int parseFlags = request.parseFlags;
10040        final @ScanFlags int scanFlags = request.scanFlags;
10041        final String realPkgName = request.realPkgName;
10042        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10043        final UserHandle user = request.user;
10044        final boolean isPlatformPackage = request.isPlatformPackage;
10045
10046        List<String> changedAbiCodePath = null;
10047
10048        if (DEBUG_PACKAGE_SCANNING) {
10049            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10050                Log.d(TAG, "Scanning package " + pkg.packageName);
10051        }
10052
10053        if (Build.IS_DEBUGGABLE &&
10054                pkg.isPrivileged() &&
10055                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10056            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10057        }
10058
10059        // Initialize package source and resource directories
10060        final File scanFile = new File(pkg.codePath);
10061        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10062        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10063
10064        // We keep references to the derived CPU Abis from settings in oder to reuse
10065        // them in the case where we're not upgrading or booting for the first time.
10066        String primaryCpuAbiFromSettings = null;
10067        String secondaryCpuAbiFromSettings = null;
10068        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10069
10070        if (!needToDeriveAbi) {
10071            if (pkgSetting != null) {
10072                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10073                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10074            } else {
10075                // Re-scanning a system package after uninstalling updates; need to derive ABI
10076                needToDeriveAbi = true;
10077            }
10078        }
10079
10080        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10081            PackageManagerService.reportSettingsProblem(Log.WARN,
10082                    "Package " + pkg.packageName + " shared user changed from "
10083                            + (pkgSetting.sharedUser != null
10084                            ? pkgSetting.sharedUser.name : "<nothing>")
10085                            + " to "
10086                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10087                            + "; replacing with new");
10088            pkgSetting = null;
10089        }
10090
10091        String[] usesStaticLibraries = null;
10092        if (pkg.usesStaticLibraries != null) {
10093            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10094            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10095        }
10096
10097        final boolean createNewPackage = (pkgSetting == null);
10098        if (createNewPackage) {
10099            final String parentPackageName = (pkg.parentPackage != null)
10100                    ? pkg.parentPackage.packageName : null;
10101            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10102            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10103            // REMOVE SharedUserSetting from method; update in a separate call
10104            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10105                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10106                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10107                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10108                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10109                    user, true /*allowInstall*/, instantApp, virtualPreload,
10110                    parentPackageName, pkg.getChildPackageNames(),
10111                    UserManagerService.getInstance(), usesStaticLibraries,
10112                    pkg.usesStaticLibrariesVersions);
10113        } else {
10114            // REMOVE SharedUserSetting from method; update in a separate call.
10115            //
10116            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10117            // secondaryCpuAbi are not known at this point so we always update them
10118            // to null here, only to reset them at a later point.
10119            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10120                    destCodeFile, pkg.applicationInfo.nativeLibraryDir,
10121                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10122                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10123                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10124                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10125        }
10126        if (createNewPackage && originalPkgSetting != null) {
10127            // If we are first transitioning from an original package,
10128            // fix up the new package's name now.  We need to do this after
10129            // looking up the package under its new name, so getPackageLP
10130            // can take care of fiddling things correctly.
10131            pkg.setPackageName(originalPkgSetting.name);
10132
10133            // File a report about this.
10134            String msg = "New package " + pkgSetting.realName
10135                    + " renamed to replace old package " + pkgSetting.name;
10136            reportSettingsProblem(Log.WARN, msg);
10137        }
10138
10139        if (disabledPkgSetting != null) {
10140            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10141        }
10142
10143        SELinuxMMAC.assignSeInfoValue(pkg);
10144
10145        pkg.mExtras = pkgSetting;
10146        pkg.applicationInfo.processName = fixProcessName(
10147                pkg.applicationInfo.packageName,
10148                pkg.applicationInfo.processName);
10149
10150        if (!isPlatformPackage) {
10151            // Get all of our default paths setup
10152            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10153        }
10154
10155        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10156
10157        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10158            if (needToDeriveAbi) {
10159                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10160                final boolean extractNativeLibs = !pkg.isLibrary();
10161                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10162                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10163
10164                // Some system apps still use directory structure for native libraries
10165                // in which case we might end up not detecting abi solely based on apk
10166                // structure. Try to detect abi based on directory structure.
10167                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10168                        pkg.applicationInfo.primaryCpuAbi == null) {
10169                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10170                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10171                }
10172            } else {
10173                // This is not a first boot or an upgrade, don't bother deriving the
10174                // ABI during the scan. Instead, trust the value that was stored in the
10175                // package setting.
10176                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10177                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10178
10179                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10180
10181                if (DEBUG_ABI_SELECTION) {
10182                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10183                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10184                            pkg.applicationInfo.secondaryCpuAbi);
10185                }
10186            }
10187        } else {
10188            if ((scanFlags & SCAN_MOVE) != 0) {
10189                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10190                // but we already have this packages package info in the PackageSetting. We just
10191                // use that and derive the native library path based on the new codepath.
10192                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10193                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10194            }
10195
10196            // Set native library paths again. For moves, the path will be updated based on the
10197            // ABIs we've determined above. For non-moves, the path will be updated based on the
10198            // ABIs we determined during compilation, but the path will depend on the final
10199            // package path (after the rename away from the stage path).
10200            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10201        }
10202
10203        // This is a special case for the "system" package, where the ABI is
10204        // dictated by the zygote configuration (and init.rc). We should keep track
10205        // of this ABI so that we can deal with "normal" applications that run under
10206        // the same UID correctly.
10207        if (isPlatformPackage) {
10208            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10209                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10210        }
10211
10212        // If there's a mismatch between the abi-override in the package setting
10213        // and the abiOverride specified for the install. Warn about this because we
10214        // would've already compiled the app without taking the package setting into
10215        // account.
10216        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10217            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10218                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10219                        " for package " + pkg.packageName);
10220            }
10221        }
10222
10223        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10224        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10225        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10226
10227        // Copy the derived override back to the parsed package, so that we can
10228        // update the package settings accordingly.
10229        pkg.cpuAbiOverride = cpuAbiOverride;
10230
10231        if (DEBUG_ABI_SELECTION) {
10232            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10233                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10234                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10235        }
10236
10237        // Push the derived path down into PackageSettings so we know what to
10238        // clean up at uninstall time.
10239        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10240
10241        if (DEBUG_ABI_SELECTION) {
10242            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10243                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10244                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10245        }
10246
10247        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10248            // We don't do this here during boot because we can do it all
10249            // at once after scanning all existing packages.
10250            //
10251            // We also do this *before* we perform dexopt on this package, so that
10252            // we can avoid redundant dexopts, and also to make sure we've got the
10253            // code and package path correct.
10254            changedAbiCodePath =
10255                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10256        }
10257
10258        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10259                android.Manifest.permission.FACTORY_TEST)) {
10260            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10261        }
10262
10263        if (isSystemApp(pkg)) {
10264            pkgSetting.isOrphaned = true;
10265        }
10266
10267        // Take care of first install / last update times.
10268        final long scanFileTime = getLastModifiedTime(pkg);
10269        if (currentTime != 0) {
10270            if (pkgSetting.firstInstallTime == 0) {
10271                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10272            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10273                pkgSetting.lastUpdateTime = currentTime;
10274            }
10275        } else if (pkgSetting.firstInstallTime == 0) {
10276            // We need *something*.  Take time time stamp of the file.
10277            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10278        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10279            if (scanFileTime != pkgSetting.timeStamp) {
10280                // A package on the system image has changed; consider this
10281                // to be an update.
10282                pkgSetting.lastUpdateTime = scanFileTime;
10283            }
10284        }
10285        pkgSetting.setTimeStamp(scanFileTime);
10286
10287        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10288    }
10289
10290    /**
10291     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10292     */
10293    private static boolean apkHasCode(String fileName) {
10294        StrictJarFile jarFile = null;
10295        try {
10296            jarFile = new StrictJarFile(fileName,
10297                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10298            return jarFile.findEntry("classes.dex") != null;
10299        } catch (IOException ignore) {
10300        } finally {
10301            try {
10302                if (jarFile != null) {
10303                    jarFile.close();
10304                }
10305            } catch (IOException ignore) {}
10306        }
10307        return false;
10308    }
10309
10310    /**
10311     * Enforces code policy for the package. This ensures that if an APK has
10312     * declared hasCode="true" in its manifest that the APK actually contains
10313     * code.
10314     *
10315     * @throws PackageManagerException If bytecode could not be found when it should exist
10316     */
10317    private static void assertCodePolicy(PackageParser.Package pkg)
10318            throws PackageManagerException {
10319        final boolean shouldHaveCode =
10320                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10321        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10322            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10323                    "Package " + pkg.baseCodePath + " code is missing");
10324        }
10325
10326        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10327            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10328                final boolean splitShouldHaveCode =
10329                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10330                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10331                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10332                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10333                }
10334            }
10335        }
10336    }
10337
10338    /**
10339     * Applies policy to the parsed package based upon the given policy flags.
10340     * Ensures the package is in a good state.
10341     * <p>
10342     * Implementation detail: This method must NOT have any side effect. It would
10343     * ideally be static, but, it requires locks to read system state.
10344     */
10345    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10346            final @ScanFlags int scanFlags) {
10347        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10348            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10349            if (pkg.applicationInfo.isDirectBootAware()) {
10350                // we're direct boot aware; set for all components
10351                for (PackageParser.Service s : pkg.services) {
10352                    s.info.encryptionAware = s.info.directBootAware = true;
10353                }
10354                for (PackageParser.Provider p : pkg.providers) {
10355                    p.info.encryptionAware = p.info.directBootAware = true;
10356                }
10357                for (PackageParser.Activity a : pkg.activities) {
10358                    a.info.encryptionAware = a.info.directBootAware = true;
10359                }
10360                for (PackageParser.Activity r : pkg.receivers) {
10361                    r.info.encryptionAware = r.info.directBootAware = true;
10362                }
10363            }
10364            if (compressedFileExists(pkg.codePath)) {
10365                pkg.isStub = true;
10366            }
10367        } else {
10368            // non system apps can't be flagged as core
10369            pkg.coreApp = false;
10370            // clear flags not applicable to regular apps
10371            pkg.applicationInfo.flags &=
10372                    ~ApplicationInfo.FLAG_PERSISTENT;
10373            pkg.applicationInfo.privateFlags &=
10374                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10375            pkg.applicationInfo.privateFlags &=
10376                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10377            // clear protected broadcasts
10378            pkg.protectedBroadcasts = null;
10379            // cap permission priorities
10380            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10381                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10382                    pkg.permissionGroups.get(i).info.priority = 0;
10383                }
10384            }
10385        }
10386        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10387            // ignore export request for single user receivers
10388            if (pkg.receivers != null) {
10389                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10390                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10391                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10392                        receiver.info.exported = false;
10393                    }
10394                }
10395            }
10396            // ignore export request for single user services
10397            if (pkg.services != null) {
10398                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10399                    final PackageParser.Service service = pkg.services.get(i);
10400                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10401                        service.info.exported = false;
10402                    }
10403                }
10404            }
10405            // ignore export request for single user providers
10406            if (pkg.providers != null) {
10407                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10408                    final PackageParser.Provider provider = pkg.providers.get(i);
10409                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10410                        provider.info.exported = false;
10411                    }
10412                }
10413            }
10414        }
10415        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10416
10417        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10418            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10419        }
10420
10421        if ((scanFlags & SCAN_AS_OEM) != 0) {
10422            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10423        }
10424
10425        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10426            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10427        }
10428
10429        if (!isSystemApp(pkg)) {
10430            // Only system apps can use these features.
10431            pkg.mOriginalPackages = null;
10432            pkg.mRealPackage = null;
10433            pkg.mAdoptPermissions = null;
10434        }
10435    }
10436
10437    /**
10438     * Asserts the parsed package is valid according to the given policy. If the
10439     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10440     * <p>
10441     * Implementation detail: This method must NOT have any side effects. It would
10442     * ideally be static, but, it requires locks to read system state.
10443     *
10444     * @throws PackageManagerException If the package fails any of the validation checks
10445     */
10446    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10447            final @ScanFlags int scanFlags)
10448                    throws PackageManagerException {
10449        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10450            assertCodePolicy(pkg);
10451        }
10452
10453        if (pkg.applicationInfo.getCodePath() == null ||
10454                pkg.applicationInfo.getResourcePath() == null) {
10455            // Bail out. The resource and code paths haven't been set.
10456            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10457                    "Code and resource paths haven't been set correctly");
10458        }
10459
10460        // Make sure we're not adding any bogus keyset info
10461        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10462        ksms.assertScannedPackageValid(pkg);
10463
10464        synchronized (mPackages) {
10465            // The special "android" package can only be defined once
10466            if (pkg.packageName.equals("android")) {
10467                if (mAndroidApplication != null) {
10468                    Slog.w(TAG, "*************************************************");
10469                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10470                    Slog.w(TAG, " codePath=" + pkg.codePath);
10471                    Slog.w(TAG, "*************************************************");
10472                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10473                            "Core android package being redefined.  Skipping.");
10474                }
10475            }
10476
10477            // A package name must be unique; don't allow duplicates
10478            if (mPackages.containsKey(pkg.packageName)) {
10479                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10480                        "Application package " + pkg.packageName
10481                        + " already installed.  Skipping duplicate.");
10482            }
10483
10484            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10485                // Static libs have a synthetic package name containing the version
10486                // but we still want the base name to be unique.
10487                if (mPackages.containsKey(pkg.manifestPackageName)) {
10488                    throw new PackageManagerException(
10489                            "Duplicate static shared lib provider package");
10490                }
10491
10492                // Static shared libraries should have at least O target SDK
10493                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10494                    throw new PackageManagerException(
10495                            "Packages declaring static-shared libs must target O SDK or higher");
10496                }
10497
10498                // Package declaring static a shared lib cannot be instant apps
10499                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10500                    throw new PackageManagerException(
10501                            "Packages declaring static-shared libs cannot be instant apps");
10502                }
10503
10504                // Package declaring static a shared lib cannot be renamed since the package
10505                // name is synthetic and apps can't code around package manager internals.
10506                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10507                    throw new PackageManagerException(
10508                            "Packages declaring static-shared libs cannot be renamed");
10509                }
10510
10511                // Package declaring static a shared lib cannot declare child packages
10512                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10513                    throw new PackageManagerException(
10514                            "Packages declaring static-shared libs cannot have child packages");
10515                }
10516
10517                // Package declaring static a shared lib cannot declare dynamic libs
10518                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10519                    throw new PackageManagerException(
10520                            "Packages declaring static-shared libs cannot declare dynamic libs");
10521                }
10522
10523                // Package declaring static a shared lib cannot declare shared users
10524                if (pkg.mSharedUserId != null) {
10525                    throw new PackageManagerException(
10526                            "Packages declaring static-shared libs cannot declare shared users");
10527                }
10528
10529                // Static shared libs cannot declare activities
10530                if (!pkg.activities.isEmpty()) {
10531                    throw new PackageManagerException(
10532                            "Static shared libs cannot declare activities");
10533                }
10534
10535                // Static shared libs cannot declare services
10536                if (!pkg.services.isEmpty()) {
10537                    throw new PackageManagerException(
10538                            "Static shared libs cannot declare services");
10539                }
10540
10541                // Static shared libs cannot declare providers
10542                if (!pkg.providers.isEmpty()) {
10543                    throw new PackageManagerException(
10544                            "Static shared libs cannot declare content providers");
10545                }
10546
10547                // Static shared libs cannot declare receivers
10548                if (!pkg.receivers.isEmpty()) {
10549                    throw new PackageManagerException(
10550                            "Static shared libs cannot declare broadcast receivers");
10551                }
10552
10553                // Static shared libs cannot declare permission groups
10554                if (!pkg.permissionGroups.isEmpty()) {
10555                    throw new PackageManagerException(
10556                            "Static shared libs cannot declare permission groups");
10557                }
10558
10559                // Static shared libs cannot declare permissions
10560                if (!pkg.permissions.isEmpty()) {
10561                    throw new PackageManagerException(
10562                            "Static shared libs cannot declare permissions");
10563                }
10564
10565                // Static shared libs cannot declare protected broadcasts
10566                if (pkg.protectedBroadcasts != null) {
10567                    throw new PackageManagerException(
10568                            "Static shared libs cannot declare protected broadcasts");
10569                }
10570
10571                // Static shared libs cannot be overlay targets
10572                if (pkg.mOverlayTarget != null) {
10573                    throw new PackageManagerException(
10574                            "Static shared libs cannot be overlay targets");
10575                }
10576
10577                // The version codes must be ordered as lib versions
10578                long minVersionCode = Long.MIN_VALUE;
10579                long maxVersionCode = Long.MAX_VALUE;
10580
10581                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10582                        pkg.staticSharedLibName);
10583                if (versionedLib != null) {
10584                    final int versionCount = versionedLib.size();
10585                    for (int i = 0; i < versionCount; i++) {
10586                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10587                        final long libVersionCode = libInfo.getDeclaringPackage()
10588                                .getLongVersionCode();
10589                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10590                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10591                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10592                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10593                        } else {
10594                            minVersionCode = maxVersionCode = libVersionCode;
10595                            break;
10596                        }
10597                    }
10598                }
10599                if (pkg.getLongVersionCode() < minVersionCode
10600                        || pkg.getLongVersionCode() > maxVersionCode) {
10601                    throw new PackageManagerException("Static shared"
10602                            + " lib version codes must be ordered as lib versions");
10603                }
10604            }
10605
10606            // Only privileged apps and updated privileged apps can add child packages.
10607            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10608                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10609                    throw new PackageManagerException("Only privileged apps can add child "
10610                            + "packages. Ignoring package " + pkg.packageName);
10611                }
10612                final int childCount = pkg.childPackages.size();
10613                for (int i = 0; i < childCount; i++) {
10614                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10615                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10616                            childPkg.packageName)) {
10617                        throw new PackageManagerException("Can't override child of "
10618                                + "another disabled app. Ignoring package " + pkg.packageName);
10619                    }
10620                }
10621            }
10622
10623            // If we're only installing presumed-existing packages, require that the
10624            // scanned APK is both already known and at the path previously established
10625            // for it.  Previously unknown packages we pick up normally, but if we have an
10626            // a priori expectation about this package's install presence, enforce it.
10627            // With a singular exception for new system packages. When an OTA contains
10628            // a new system package, we allow the codepath to change from a system location
10629            // to the user-installed location. If we don't allow this change, any newer,
10630            // user-installed version of the application will be ignored.
10631            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10632                if (mExpectingBetter.containsKey(pkg.packageName)) {
10633                    logCriticalInfo(Log.WARN,
10634                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10635                } else {
10636                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10637                    if (known != null) {
10638                        if (DEBUG_PACKAGE_SCANNING) {
10639                            Log.d(TAG, "Examining " + pkg.codePath
10640                                    + " and requiring known paths " + known.codePathString
10641                                    + " & " + known.resourcePathString);
10642                        }
10643                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10644                                || !pkg.applicationInfo.getResourcePath().equals(
10645                                        known.resourcePathString)) {
10646                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10647                                    "Application package " + pkg.packageName
10648                                    + " found at " + pkg.applicationInfo.getCodePath()
10649                                    + " but expected at " + known.codePathString
10650                                    + "; ignoring.");
10651                        }
10652                    } else {
10653                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10654                                "Application package " + pkg.packageName
10655                                + " not found; ignoring.");
10656                    }
10657                }
10658            }
10659
10660            // Verify that this new package doesn't have any content providers
10661            // that conflict with existing packages.  Only do this if the
10662            // package isn't already installed, since we don't want to break
10663            // things that are installed.
10664            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10665                final int N = pkg.providers.size();
10666                int i;
10667                for (i=0; i<N; i++) {
10668                    PackageParser.Provider p = pkg.providers.get(i);
10669                    if (p.info.authority != null) {
10670                        String names[] = p.info.authority.split(";");
10671                        for (int j = 0; j < names.length; j++) {
10672                            if (mProvidersByAuthority.containsKey(names[j])) {
10673                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10674                                final String otherPackageName =
10675                                        ((other != null && other.getComponentName() != null) ?
10676                                                other.getComponentName().getPackageName() : "?");
10677                                throw new PackageManagerException(
10678                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10679                                        "Can't install because provider name " + names[j]
10680                                                + " (in package " + pkg.applicationInfo.packageName
10681                                                + ") is already used by " + otherPackageName);
10682                            }
10683                        }
10684                    }
10685                }
10686            }
10687        }
10688    }
10689
10690    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
10691            int type, String declaringPackageName, long declaringVersionCode) {
10692        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10693        if (versionedLib == null) {
10694            versionedLib = new LongSparseArray<>();
10695            mSharedLibraries.put(name, versionedLib);
10696            if (type == SharedLibraryInfo.TYPE_STATIC) {
10697                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10698            }
10699        } else if (versionedLib.indexOfKey(version) >= 0) {
10700            return false;
10701        }
10702        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10703                version, type, declaringPackageName, declaringVersionCode);
10704        versionedLib.put(version, libEntry);
10705        return true;
10706    }
10707
10708    private boolean removeSharedLibraryLPw(String name, long version) {
10709        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10710        if (versionedLib == null) {
10711            return false;
10712        }
10713        final int libIdx = versionedLib.indexOfKey(version);
10714        if (libIdx < 0) {
10715            return false;
10716        }
10717        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10718        versionedLib.remove(version);
10719        if (versionedLib.size() <= 0) {
10720            mSharedLibraries.remove(name);
10721            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10722                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10723                        .getPackageName());
10724            }
10725        }
10726        return true;
10727    }
10728
10729    /**
10730     * Adds a scanned package to the system. When this method is finished, the package will
10731     * be available for query, resolution, etc...
10732     */
10733    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10734            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
10735        final String pkgName = pkg.packageName;
10736        if (mCustomResolverComponentName != null &&
10737                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10738            setUpCustomResolverActivity(pkg);
10739        }
10740
10741        if (pkg.packageName.equals("android")) {
10742            synchronized (mPackages) {
10743                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10744                    // Set up information for our fall-back user intent resolution activity.
10745                    mPlatformPackage = pkg;
10746                    pkg.mVersionCode = mSdkVersion;
10747                    pkg.mVersionCodeMajor = 0;
10748                    mAndroidApplication = pkg.applicationInfo;
10749                    if (!mResolverReplaced) {
10750                        mResolveActivity.applicationInfo = mAndroidApplication;
10751                        mResolveActivity.name = ResolverActivity.class.getName();
10752                        mResolveActivity.packageName = mAndroidApplication.packageName;
10753                        mResolveActivity.processName = "system:ui";
10754                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10755                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10756                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10757                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10758                        mResolveActivity.exported = true;
10759                        mResolveActivity.enabled = true;
10760                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10761                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10762                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10763                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10764                                | ActivityInfo.CONFIG_ORIENTATION
10765                                | ActivityInfo.CONFIG_KEYBOARD
10766                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10767                        mResolveInfo.activityInfo = mResolveActivity;
10768                        mResolveInfo.priority = 0;
10769                        mResolveInfo.preferredOrder = 0;
10770                        mResolveInfo.match = 0;
10771                        mResolveComponentName = new ComponentName(
10772                                mAndroidApplication.packageName, mResolveActivity.name);
10773                    }
10774                }
10775            }
10776        }
10777
10778        ArrayList<PackageParser.Package> clientLibPkgs = null;
10779        // writer
10780        synchronized (mPackages) {
10781            boolean hasStaticSharedLibs = false;
10782
10783            // Any app can add new static shared libraries
10784            if (pkg.staticSharedLibName != null) {
10785                // Static shared libs don't allow renaming as they have synthetic package
10786                // names to allow install of multiple versions, so use name from manifest.
10787                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10788                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10789                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
10790                    hasStaticSharedLibs = true;
10791                } else {
10792                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10793                                + pkg.staticSharedLibName + " already exists; skipping");
10794                }
10795                // Static shared libs cannot be updated once installed since they
10796                // use synthetic package name which includes the version code, so
10797                // not need to update other packages's shared lib dependencies.
10798            }
10799
10800            if (!hasStaticSharedLibs
10801                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10802                // Only system apps can add new dynamic shared libraries.
10803                if (pkg.libraryNames != null) {
10804                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10805                        String name = pkg.libraryNames.get(i);
10806                        boolean allowed = false;
10807                        if (pkg.isUpdatedSystemApp()) {
10808                            // New library entries can only be added through the
10809                            // system image.  This is important to get rid of a lot
10810                            // of nasty edge cases: for example if we allowed a non-
10811                            // system update of the app to add a library, then uninstalling
10812                            // the update would make the library go away, and assumptions
10813                            // we made such as through app install filtering would now
10814                            // have allowed apps on the device which aren't compatible
10815                            // with it.  Better to just have the restriction here, be
10816                            // conservative, and create many fewer cases that can negatively
10817                            // impact the user experience.
10818                            final PackageSetting sysPs = mSettings
10819                                    .getDisabledSystemPkgLPr(pkg.packageName);
10820                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10821                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10822                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10823                                        allowed = true;
10824                                        break;
10825                                    }
10826                                }
10827                            }
10828                        } else {
10829                            allowed = true;
10830                        }
10831                        if (allowed) {
10832                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10833                                    SharedLibraryInfo.VERSION_UNDEFINED,
10834                                    SharedLibraryInfo.TYPE_DYNAMIC,
10835                                    pkg.packageName, pkg.getLongVersionCode())) {
10836                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10837                                        + name + " already exists; skipping");
10838                            }
10839                        } else {
10840                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10841                                    + name + " that is not declared on system image; skipping");
10842                        }
10843                    }
10844
10845                    if ((scanFlags & SCAN_BOOTING) == 0) {
10846                        // If we are not booting, we need to update any applications
10847                        // that are clients of our shared library.  If we are booting,
10848                        // this will all be done once the scan is complete.
10849                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10850                    }
10851                }
10852            }
10853        }
10854
10855        if ((scanFlags & SCAN_BOOTING) != 0) {
10856            // No apps can run during boot scan, so they don't need to be frozen
10857        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10858            // Caller asked to not kill app, so it's probably not frozen
10859        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10860            // Caller asked us to ignore frozen check for some reason; they
10861            // probably didn't know the package name
10862        } else {
10863            // We're doing major surgery on this package, so it better be frozen
10864            // right now to keep it from launching
10865            checkPackageFrozen(pkgName);
10866        }
10867
10868        // Also need to kill any apps that are dependent on the library.
10869        if (clientLibPkgs != null) {
10870            for (int i=0; i<clientLibPkgs.size(); i++) {
10871                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10872                killApplication(clientPkg.applicationInfo.packageName,
10873                        clientPkg.applicationInfo.uid, "update lib");
10874            }
10875        }
10876
10877        // writer
10878        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10879
10880        synchronized (mPackages) {
10881            // We don't expect installation to fail beyond this point
10882
10883            // Add the new setting to mSettings
10884            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10885            // Add the new setting to mPackages
10886            mPackages.put(pkg.applicationInfo.packageName, pkg);
10887            // Make sure we don't accidentally delete its data.
10888            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10889            while (iter.hasNext()) {
10890                PackageCleanItem item = iter.next();
10891                if (pkgName.equals(item.packageName)) {
10892                    iter.remove();
10893                }
10894            }
10895
10896            // Add the package's KeySets to the global KeySetManagerService
10897            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10898            ksms.addScannedPackageLPw(pkg);
10899
10900            int N = pkg.providers.size();
10901            StringBuilder r = null;
10902            int i;
10903            for (i=0; i<N; i++) {
10904                PackageParser.Provider p = pkg.providers.get(i);
10905                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10906                        p.info.processName);
10907                mProviders.addProvider(p);
10908                p.syncable = p.info.isSyncable;
10909                if (p.info.authority != null) {
10910                    String names[] = p.info.authority.split(";");
10911                    p.info.authority = null;
10912                    for (int j = 0; j < names.length; j++) {
10913                        if (j == 1 && p.syncable) {
10914                            // We only want the first authority for a provider to possibly be
10915                            // syncable, so if we already added this provider using a different
10916                            // authority clear the syncable flag. We copy the provider before
10917                            // changing it because the mProviders object contains a reference
10918                            // to a provider that we don't want to change.
10919                            // Only do this for the second authority since the resulting provider
10920                            // object can be the same for all future authorities for this provider.
10921                            p = new PackageParser.Provider(p);
10922                            p.syncable = false;
10923                        }
10924                        if (!mProvidersByAuthority.containsKey(names[j])) {
10925                            mProvidersByAuthority.put(names[j], p);
10926                            if (p.info.authority == null) {
10927                                p.info.authority = names[j];
10928                            } else {
10929                                p.info.authority = p.info.authority + ";" + names[j];
10930                            }
10931                            if (DEBUG_PACKAGE_SCANNING) {
10932                                if (chatty)
10933                                    Log.d(TAG, "Registered content provider: " + names[j]
10934                                            + ", className = " + p.info.name + ", isSyncable = "
10935                                            + p.info.isSyncable);
10936                            }
10937                        } else {
10938                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10939                            Slog.w(TAG, "Skipping provider name " + names[j] +
10940                                    " (in package " + pkg.applicationInfo.packageName +
10941                                    "): name already used by "
10942                                    + ((other != null && other.getComponentName() != null)
10943                                            ? other.getComponentName().getPackageName() : "?"));
10944                        }
10945                    }
10946                }
10947                if (chatty) {
10948                    if (r == null) {
10949                        r = new StringBuilder(256);
10950                    } else {
10951                        r.append(' ');
10952                    }
10953                    r.append(p.info.name);
10954                }
10955            }
10956            if (r != null) {
10957                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10958            }
10959
10960            N = pkg.services.size();
10961            r = null;
10962            for (i=0; i<N; i++) {
10963                PackageParser.Service s = pkg.services.get(i);
10964                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10965                        s.info.processName);
10966                mServices.addService(s);
10967                if (chatty) {
10968                    if (r == null) {
10969                        r = new StringBuilder(256);
10970                    } else {
10971                        r.append(' ');
10972                    }
10973                    r.append(s.info.name);
10974                }
10975            }
10976            if (r != null) {
10977                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10978            }
10979
10980            N = pkg.receivers.size();
10981            r = null;
10982            for (i=0; i<N; i++) {
10983                PackageParser.Activity a = pkg.receivers.get(i);
10984                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10985                        a.info.processName);
10986                mReceivers.addActivity(a, "receiver");
10987                if (chatty) {
10988                    if (r == null) {
10989                        r = new StringBuilder(256);
10990                    } else {
10991                        r.append(' ');
10992                    }
10993                    r.append(a.info.name);
10994                }
10995            }
10996            if (r != null) {
10997                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10998            }
10999
11000            N = pkg.activities.size();
11001            r = null;
11002            for (i=0; i<N; i++) {
11003                PackageParser.Activity a = pkg.activities.get(i);
11004                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11005                        a.info.processName);
11006                mActivities.addActivity(a, "activity");
11007                if (chatty) {
11008                    if (r == null) {
11009                        r = new StringBuilder(256);
11010                    } else {
11011                        r.append(' ');
11012                    }
11013                    r.append(a.info.name);
11014                }
11015            }
11016            if (r != null) {
11017                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11018            }
11019
11020            // Don't allow ephemeral applications to define new permissions groups.
11021            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11022                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11023                        + " ignored: instant apps cannot define new permission groups.");
11024            } else {
11025                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11026            }
11027
11028            // Don't allow ephemeral applications to define new permissions.
11029            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11030                Slog.w(TAG, "Permissions from package " + pkg.packageName
11031                        + " ignored: instant apps cannot define new permissions.");
11032            } else {
11033                mPermissionManager.addAllPermissions(pkg, chatty);
11034            }
11035
11036            N = pkg.instrumentation.size();
11037            r = null;
11038            for (i=0; i<N; i++) {
11039                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11040                a.info.packageName = pkg.applicationInfo.packageName;
11041                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11042                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11043                a.info.splitNames = pkg.splitNames;
11044                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11045                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11046                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11047                a.info.dataDir = pkg.applicationInfo.dataDir;
11048                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11049                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11050                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11051                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11052                mInstrumentation.put(a.getComponentName(), a);
11053                if (chatty) {
11054                    if (r == null) {
11055                        r = new StringBuilder(256);
11056                    } else {
11057                        r.append(' ');
11058                    }
11059                    r.append(a.info.name);
11060                }
11061            }
11062            if (r != null) {
11063                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11064            }
11065
11066            if (pkg.protectedBroadcasts != null) {
11067                N = pkg.protectedBroadcasts.size();
11068                synchronized (mProtectedBroadcasts) {
11069                    for (i = 0; i < N; i++) {
11070                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11071                    }
11072                }
11073            }
11074        }
11075
11076        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11077    }
11078
11079    /**
11080     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11081     * is derived purely on the basis of the contents of {@code scanFile} and
11082     * {@code cpuAbiOverride}.
11083     *
11084     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11085     */
11086    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11087            boolean extractLibs)
11088                    throws PackageManagerException {
11089        // Give ourselves some initial paths; we'll come back for another
11090        // pass once we've determined ABI below.
11091        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11092
11093        // We would never need to extract libs for forward-locked and external packages,
11094        // since the container service will do it for us. We shouldn't attempt to
11095        // extract libs from system app when it was not updated.
11096        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11097                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11098            extractLibs = false;
11099        }
11100
11101        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11102        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11103
11104        NativeLibraryHelper.Handle handle = null;
11105        try {
11106            handle = NativeLibraryHelper.Handle.create(pkg);
11107            // TODO(multiArch): This can be null for apps that didn't go through the
11108            // usual installation process. We can calculate it again, like we
11109            // do during install time.
11110            //
11111            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11112            // unnecessary.
11113            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11114
11115            // Null out the abis so that they can be recalculated.
11116            pkg.applicationInfo.primaryCpuAbi = null;
11117            pkg.applicationInfo.secondaryCpuAbi = null;
11118            if (isMultiArch(pkg.applicationInfo)) {
11119                // Warn if we've set an abiOverride for multi-lib packages..
11120                // By definition, we need to copy both 32 and 64 bit libraries for
11121                // such packages.
11122                if (pkg.cpuAbiOverride != null
11123                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11124                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11125                }
11126
11127                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11128                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11129                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11130                    if (extractLibs) {
11131                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11132                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11133                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11134                                useIsaSpecificSubdirs);
11135                    } else {
11136                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11137                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11138                    }
11139                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11140                }
11141
11142                // Shared library native code should be in the APK zip aligned
11143                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11144                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11145                            "Shared library native lib extraction not supported");
11146                }
11147
11148                maybeThrowExceptionForMultiArchCopy(
11149                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11150
11151                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11152                    if (extractLibs) {
11153                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11154                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11155                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11156                                useIsaSpecificSubdirs);
11157                    } else {
11158                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11159                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11160                    }
11161                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11162                }
11163
11164                maybeThrowExceptionForMultiArchCopy(
11165                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11166
11167                if (abi64 >= 0) {
11168                    // Shared library native libs should be in the APK zip aligned
11169                    if (extractLibs && pkg.isLibrary()) {
11170                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11171                                "Shared library native lib extraction not supported");
11172                    }
11173                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11174                }
11175
11176                if (abi32 >= 0) {
11177                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11178                    if (abi64 >= 0) {
11179                        if (pkg.use32bitAbi) {
11180                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11181                            pkg.applicationInfo.primaryCpuAbi = abi;
11182                        } else {
11183                            pkg.applicationInfo.secondaryCpuAbi = abi;
11184                        }
11185                    } else {
11186                        pkg.applicationInfo.primaryCpuAbi = abi;
11187                    }
11188                }
11189            } else {
11190                String[] abiList = (cpuAbiOverride != null) ?
11191                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11192
11193                // Enable gross and lame hacks for apps that are built with old
11194                // SDK tools. We must scan their APKs for renderscript bitcode and
11195                // not launch them if it's present. Don't bother checking on devices
11196                // that don't have 64 bit support.
11197                boolean needsRenderScriptOverride = false;
11198                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11199                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11200                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11201                    needsRenderScriptOverride = true;
11202                }
11203
11204                final int copyRet;
11205                if (extractLibs) {
11206                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11207                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11208                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11209                } else {
11210                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11211                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11212                }
11213                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11214
11215                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11216                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11217                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11218                }
11219
11220                if (copyRet >= 0) {
11221                    // Shared libraries that have native libs must be multi-architecture
11222                    if (pkg.isLibrary()) {
11223                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11224                                "Shared library with native libs must be multiarch");
11225                    }
11226                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11227                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11228                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11229                } else if (needsRenderScriptOverride) {
11230                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11231                }
11232            }
11233        } catch (IOException ioe) {
11234            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11235        } finally {
11236            IoUtils.closeQuietly(handle);
11237        }
11238
11239        // Now that we've calculated the ABIs and determined if it's an internal app,
11240        // we will go ahead and populate the nativeLibraryPath.
11241        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11242    }
11243
11244    /**
11245     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11246     * i.e, so that all packages can be run inside a single process if required.
11247     *
11248     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11249     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11250     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11251     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11252     * updating a package that belongs to a shared user.
11253     *
11254     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11255     * adds unnecessary complexity.
11256     */
11257    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11258            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11259        List<String> changedAbiCodePath = null;
11260        String requiredInstructionSet = null;
11261        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11262            requiredInstructionSet = VMRuntime.getInstructionSet(
11263                     scannedPackage.applicationInfo.primaryCpuAbi);
11264        }
11265
11266        PackageSetting requirer = null;
11267        for (PackageSetting ps : packagesForUser) {
11268            // If packagesForUser contains scannedPackage, we skip it. This will happen
11269            // when scannedPackage is an update of an existing package. Without this check,
11270            // we will never be able to change the ABI of any package belonging to a shared
11271            // user, even if it's compatible with other packages.
11272            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11273                if (ps.primaryCpuAbiString == null) {
11274                    continue;
11275                }
11276
11277                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11278                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11279                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11280                    // this but there's not much we can do.
11281                    String errorMessage = "Instruction set mismatch, "
11282                            + ((requirer == null) ? "[caller]" : requirer)
11283                            + " requires " + requiredInstructionSet + " whereas " + ps
11284                            + " requires " + instructionSet;
11285                    Slog.w(TAG, errorMessage);
11286                }
11287
11288                if (requiredInstructionSet == null) {
11289                    requiredInstructionSet = instructionSet;
11290                    requirer = ps;
11291                }
11292            }
11293        }
11294
11295        if (requiredInstructionSet != null) {
11296            String adjustedAbi;
11297            if (requirer != null) {
11298                // requirer != null implies that either scannedPackage was null or that scannedPackage
11299                // did not require an ABI, in which case we have to adjust scannedPackage to match
11300                // the ABI of the set (which is the same as requirer's ABI)
11301                adjustedAbi = requirer.primaryCpuAbiString;
11302                if (scannedPackage != null) {
11303                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11304                }
11305            } else {
11306                // requirer == null implies that we're updating all ABIs in the set to
11307                // match scannedPackage.
11308                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11309            }
11310
11311            for (PackageSetting ps : packagesForUser) {
11312                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11313                    if (ps.primaryCpuAbiString != null) {
11314                        continue;
11315                    }
11316
11317                    ps.primaryCpuAbiString = adjustedAbi;
11318                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11319                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11320                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11321                        if (DEBUG_ABI_SELECTION) {
11322                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11323                                    + " (requirer="
11324                                    + (requirer != null ? requirer.pkg : "null")
11325                                    + ", scannedPackage="
11326                                    + (scannedPackage != null ? scannedPackage : "null")
11327                                    + ")");
11328                        }
11329                        if (changedAbiCodePath == null) {
11330                            changedAbiCodePath = new ArrayList<>();
11331                        }
11332                        changedAbiCodePath.add(ps.codePathString);
11333                    }
11334                }
11335            }
11336        }
11337        return changedAbiCodePath;
11338    }
11339
11340    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11341        synchronized (mPackages) {
11342            mResolverReplaced = true;
11343            // Set up information for custom user intent resolution activity.
11344            mResolveActivity.applicationInfo = pkg.applicationInfo;
11345            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11346            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11347            mResolveActivity.processName = pkg.applicationInfo.packageName;
11348            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11349            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11350                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11351            mResolveActivity.theme = 0;
11352            mResolveActivity.exported = true;
11353            mResolveActivity.enabled = true;
11354            mResolveInfo.activityInfo = mResolveActivity;
11355            mResolveInfo.priority = 0;
11356            mResolveInfo.preferredOrder = 0;
11357            mResolveInfo.match = 0;
11358            mResolveComponentName = mCustomResolverComponentName;
11359            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11360                    mResolveComponentName);
11361        }
11362    }
11363
11364    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11365        if (installerActivity == null) {
11366            if (DEBUG_EPHEMERAL) {
11367                Slog.d(TAG, "Clear ephemeral installer activity");
11368            }
11369            mInstantAppInstallerActivity = null;
11370            return;
11371        }
11372
11373        if (DEBUG_EPHEMERAL) {
11374            Slog.d(TAG, "Set ephemeral installer activity: "
11375                    + installerActivity.getComponentName());
11376        }
11377        // Set up information for ephemeral installer activity
11378        mInstantAppInstallerActivity = installerActivity;
11379        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11380                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11381        mInstantAppInstallerActivity.exported = true;
11382        mInstantAppInstallerActivity.enabled = true;
11383        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11384        mInstantAppInstallerInfo.priority = 0;
11385        mInstantAppInstallerInfo.preferredOrder = 1;
11386        mInstantAppInstallerInfo.isDefault = true;
11387        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11388                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11389    }
11390
11391    private static String calculateBundledApkRoot(final String codePathString) {
11392        final File codePath = new File(codePathString);
11393        final File codeRoot;
11394        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11395            codeRoot = Environment.getRootDirectory();
11396        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11397            codeRoot = Environment.getOemDirectory();
11398        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11399            codeRoot = Environment.getVendorDirectory();
11400        } else {
11401            // Unrecognized code path; take its top real segment as the apk root:
11402            // e.g. /something/app/blah.apk => /something
11403            try {
11404                File f = codePath.getCanonicalFile();
11405                File parent = f.getParentFile();    // non-null because codePath is a file
11406                File tmp;
11407                while ((tmp = parent.getParentFile()) != null) {
11408                    f = parent;
11409                    parent = tmp;
11410                }
11411                codeRoot = f;
11412                Slog.w(TAG, "Unrecognized code path "
11413                        + codePath + " - using " + codeRoot);
11414            } catch (IOException e) {
11415                // Can't canonicalize the code path -- shenanigans?
11416                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11417                return Environment.getRootDirectory().getPath();
11418            }
11419        }
11420        return codeRoot.getPath();
11421    }
11422
11423    /**
11424     * Derive and set the location of native libraries for the given package,
11425     * which varies depending on where and how the package was installed.
11426     */
11427    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11428        final ApplicationInfo info = pkg.applicationInfo;
11429        final String codePath = pkg.codePath;
11430        final File codeFile = new File(codePath);
11431        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11432        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11433
11434        info.nativeLibraryRootDir = null;
11435        info.nativeLibraryRootRequiresIsa = false;
11436        info.nativeLibraryDir = null;
11437        info.secondaryNativeLibraryDir = null;
11438
11439        if (isApkFile(codeFile)) {
11440            // Monolithic install
11441            if (bundledApp) {
11442                // If "/system/lib64/apkname" exists, assume that is the per-package
11443                // native library directory to use; otherwise use "/system/lib/apkname".
11444                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11445                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11446                        getPrimaryInstructionSet(info));
11447
11448                // This is a bundled system app so choose the path based on the ABI.
11449                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11450                // is just the default path.
11451                final String apkName = deriveCodePathName(codePath);
11452                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11453                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11454                        apkName).getAbsolutePath();
11455
11456                if (info.secondaryCpuAbi != null) {
11457                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11458                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11459                            secondaryLibDir, apkName).getAbsolutePath();
11460                }
11461            } else if (asecApp) {
11462                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11463                        .getAbsolutePath();
11464            } else {
11465                final String apkName = deriveCodePathName(codePath);
11466                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11467                        .getAbsolutePath();
11468            }
11469
11470            info.nativeLibraryRootRequiresIsa = false;
11471            info.nativeLibraryDir = info.nativeLibraryRootDir;
11472        } else {
11473            // Cluster install
11474            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11475            info.nativeLibraryRootRequiresIsa = true;
11476
11477            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11478                    getPrimaryInstructionSet(info)).getAbsolutePath();
11479
11480            if (info.secondaryCpuAbi != null) {
11481                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11482                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11483            }
11484        }
11485    }
11486
11487    /**
11488     * Calculate the abis and roots for a bundled app. These can uniquely
11489     * be determined from the contents of the system partition, i.e whether
11490     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11491     * of this information, and instead assume that the system was built
11492     * sensibly.
11493     */
11494    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11495                                           PackageSetting pkgSetting) {
11496        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11497
11498        // If "/system/lib64/apkname" exists, assume that is the per-package
11499        // native library directory to use; otherwise use "/system/lib/apkname".
11500        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11501        setBundledAppAbi(pkg, apkRoot, apkName);
11502        // pkgSetting might be null during rescan following uninstall of updates
11503        // to a bundled app, so accommodate that possibility.  The settings in
11504        // that case will be established later from the parsed package.
11505        //
11506        // If the settings aren't null, sync them up with what we've just derived.
11507        // note that apkRoot isn't stored in the package settings.
11508        if (pkgSetting != null) {
11509            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11510            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11511        }
11512    }
11513
11514    /**
11515     * Deduces the ABI of a bundled app and sets the relevant fields on the
11516     * parsed pkg object.
11517     *
11518     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11519     *        under which system libraries are installed.
11520     * @param apkName the name of the installed package.
11521     */
11522    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11523        final File codeFile = new File(pkg.codePath);
11524
11525        final boolean has64BitLibs;
11526        final boolean has32BitLibs;
11527        if (isApkFile(codeFile)) {
11528            // Monolithic install
11529            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11530            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11531        } else {
11532            // Cluster install
11533            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11534            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11535                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11536                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11537                has64BitLibs = (new File(rootDir, isa)).exists();
11538            } else {
11539                has64BitLibs = false;
11540            }
11541            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11542                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11543                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11544                has32BitLibs = (new File(rootDir, isa)).exists();
11545            } else {
11546                has32BitLibs = false;
11547            }
11548        }
11549
11550        if (has64BitLibs && !has32BitLibs) {
11551            // The package has 64 bit libs, but not 32 bit libs. Its primary
11552            // ABI should be 64 bit. We can safely assume here that the bundled
11553            // native libraries correspond to the most preferred ABI in the list.
11554
11555            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11556            pkg.applicationInfo.secondaryCpuAbi = null;
11557        } else if (has32BitLibs && !has64BitLibs) {
11558            // The package has 32 bit libs but not 64 bit libs. Its primary
11559            // ABI should be 32 bit.
11560
11561            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11562            pkg.applicationInfo.secondaryCpuAbi = null;
11563        } else if (has32BitLibs && has64BitLibs) {
11564            // The application has both 64 and 32 bit bundled libraries. We check
11565            // here that the app declares multiArch support, and warn if it doesn't.
11566            //
11567            // We will be lenient here and record both ABIs. The primary will be the
11568            // ABI that's higher on the list, i.e, a device that's configured to prefer
11569            // 64 bit apps will see a 64 bit primary ABI,
11570
11571            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11572                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11573            }
11574
11575            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11576                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11577                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11578            } else {
11579                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11580                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11581            }
11582        } else {
11583            pkg.applicationInfo.primaryCpuAbi = null;
11584            pkg.applicationInfo.secondaryCpuAbi = null;
11585        }
11586    }
11587
11588    private void killApplication(String pkgName, int appId, String reason) {
11589        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11590    }
11591
11592    private void killApplication(String pkgName, int appId, int userId, String reason) {
11593        // Request the ActivityManager to kill the process(only for existing packages)
11594        // so that we do not end up in a confused state while the user is still using the older
11595        // version of the application while the new one gets installed.
11596        final long token = Binder.clearCallingIdentity();
11597        try {
11598            IActivityManager am = ActivityManager.getService();
11599            if (am != null) {
11600                try {
11601                    am.killApplication(pkgName, appId, userId, reason);
11602                } catch (RemoteException e) {
11603                }
11604            }
11605        } finally {
11606            Binder.restoreCallingIdentity(token);
11607        }
11608    }
11609
11610    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11611        // Remove the parent package setting
11612        PackageSetting ps = (PackageSetting) pkg.mExtras;
11613        if (ps != null) {
11614            removePackageLI(ps, chatty);
11615        }
11616        // Remove the child package setting
11617        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11618        for (int i = 0; i < childCount; i++) {
11619            PackageParser.Package childPkg = pkg.childPackages.get(i);
11620            ps = (PackageSetting) childPkg.mExtras;
11621            if (ps != null) {
11622                removePackageLI(ps, chatty);
11623            }
11624        }
11625    }
11626
11627    void removePackageLI(PackageSetting ps, boolean chatty) {
11628        if (DEBUG_INSTALL) {
11629            if (chatty)
11630                Log.d(TAG, "Removing package " + ps.name);
11631        }
11632
11633        // writer
11634        synchronized (mPackages) {
11635            mPackages.remove(ps.name);
11636            final PackageParser.Package pkg = ps.pkg;
11637            if (pkg != null) {
11638                cleanPackageDataStructuresLILPw(pkg, chatty);
11639            }
11640        }
11641    }
11642
11643    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11644        if (DEBUG_INSTALL) {
11645            if (chatty)
11646                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11647        }
11648
11649        // writer
11650        synchronized (mPackages) {
11651            // Remove the parent package
11652            mPackages.remove(pkg.applicationInfo.packageName);
11653            cleanPackageDataStructuresLILPw(pkg, chatty);
11654
11655            // Remove the child packages
11656            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11657            for (int i = 0; i < childCount; i++) {
11658                PackageParser.Package childPkg = pkg.childPackages.get(i);
11659                mPackages.remove(childPkg.applicationInfo.packageName);
11660                cleanPackageDataStructuresLILPw(childPkg, chatty);
11661            }
11662        }
11663    }
11664
11665    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11666        int N = pkg.providers.size();
11667        StringBuilder r = null;
11668        int i;
11669        for (i=0; i<N; i++) {
11670            PackageParser.Provider p = pkg.providers.get(i);
11671            mProviders.removeProvider(p);
11672            if (p.info.authority == null) {
11673
11674                /* There was another ContentProvider with this authority when
11675                 * this app was installed so this authority is null,
11676                 * Ignore it as we don't have to unregister the provider.
11677                 */
11678                continue;
11679            }
11680            String names[] = p.info.authority.split(";");
11681            for (int j = 0; j < names.length; j++) {
11682                if (mProvidersByAuthority.get(names[j]) == p) {
11683                    mProvidersByAuthority.remove(names[j]);
11684                    if (DEBUG_REMOVE) {
11685                        if (chatty)
11686                            Log.d(TAG, "Unregistered content provider: " + names[j]
11687                                    + ", className = " + p.info.name + ", isSyncable = "
11688                                    + p.info.isSyncable);
11689                    }
11690                }
11691            }
11692            if (DEBUG_REMOVE && chatty) {
11693                if (r == null) {
11694                    r = new StringBuilder(256);
11695                } else {
11696                    r.append(' ');
11697                }
11698                r.append(p.info.name);
11699            }
11700        }
11701        if (r != null) {
11702            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11703        }
11704
11705        N = pkg.services.size();
11706        r = null;
11707        for (i=0; i<N; i++) {
11708            PackageParser.Service s = pkg.services.get(i);
11709            mServices.removeService(s);
11710            if (chatty) {
11711                if (r == null) {
11712                    r = new StringBuilder(256);
11713                } else {
11714                    r.append(' ');
11715                }
11716                r.append(s.info.name);
11717            }
11718        }
11719        if (r != null) {
11720            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11721        }
11722
11723        N = pkg.receivers.size();
11724        r = null;
11725        for (i=0; i<N; i++) {
11726            PackageParser.Activity a = pkg.receivers.get(i);
11727            mReceivers.removeActivity(a, "receiver");
11728            if (DEBUG_REMOVE && chatty) {
11729                if (r == null) {
11730                    r = new StringBuilder(256);
11731                } else {
11732                    r.append(' ');
11733                }
11734                r.append(a.info.name);
11735            }
11736        }
11737        if (r != null) {
11738            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11739        }
11740
11741        N = pkg.activities.size();
11742        r = null;
11743        for (i=0; i<N; i++) {
11744            PackageParser.Activity a = pkg.activities.get(i);
11745            mActivities.removeActivity(a, "activity");
11746            if (DEBUG_REMOVE && chatty) {
11747                if (r == null) {
11748                    r = new StringBuilder(256);
11749                } else {
11750                    r.append(' ');
11751                }
11752                r.append(a.info.name);
11753            }
11754        }
11755        if (r != null) {
11756            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11757        }
11758
11759        mPermissionManager.removeAllPermissions(pkg, chatty);
11760
11761        N = pkg.instrumentation.size();
11762        r = null;
11763        for (i=0; i<N; i++) {
11764            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11765            mInstrumentation.remove(a.getComponentName());
11766            if (DEBUG_REMOVE && chatty) {
11767                if (r == null) {
11768                    r = new StringBuilder(256);
11769                } else {
11770                    r.append(' ');
11771                }
11772                r.append(a.info.name);
11773            }
11774        }
11775        if (r != null) {
11776            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11777        }
11778
11779        r = null;
11780        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11781            // Only system apps can hold shared libraries.
11782            if (pkg.libraryNames != null) {
11783                for (i = 0; i < pkg.libraryNames.size(); i++) {
11784                    String name = pkg.libraryNames.get(i);
11785                    if (removeSharedLibraryLPw(name, 0)) {
11786                        if (DEBUG_REMOVE && chatty) {
11787                            if (r == null) {
11788                                r = new StringBuilder(256);
11789                            } else {
11790                                r.append(' ');
11791                            }
11792                            r.append(name);
11793                        }
11794                    }
11795                }
11796            }
11797        }
11798
11799        r = null;
11800
11801        // Any package can hold static shared libraries.
11802        if (pkg.staticSharedLibName != null) {
11803            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11804                if (DEBUG_REMOVE && chatty) {
11805                    if (r == null) {
11806                        r = new StringBuilder(256);
11807                    } else {
11808                        r.append(' ');
11809                    }
11810                    r.append(pkg.staticSharedLibName);
11811                }
11812            }
11813        }
11814
11815        if (r != null) {
11816            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11817        }
11818    }
11819
11820
11821    final class ActivityIntentResolver
11822            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11823        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11824                boolean defaultOnly, int userId) {
11825            if (!sUserManager.exists(userId)) return null;
11826            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11827            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11828        }
11829
11830        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11831                int userId) {
11832            if (!sUserManager.exists(userId)) return null;
11833            mFlags = flags;
11834            return super.queryIntent(intent, resolvedType,
11835                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11836                    userId);
11837        }
11838
11839        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11840                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11841            if (!sUserManager.exists(userId)) return null;
11842            if (packageActivities == null) {
11843                return null;
11844            }
11845            mFlags = flags;
11846            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11847            final int N = packageActivities.size();
11848            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11849                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11850
11851            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11852            for (int i = 0; i < N; ++i) {
11853                intentFilters = packageActivities.get(i).intents;
11854                if (intentFilters != null && intentFilters.size() > 0) {
11855                    PackageParser.ActivityIntentInfo[] array =
11856                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11857                    intentFilters.toArray(array);
11858                    listCut.add(array);
11859                }
11860            }
11861            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11862        }
11863
11864        /**
11865         * Finds a privileged activity that matches the specified activity names.
11866         */
11867        private PackageParser.Activity findMatchingActivity(
11868                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11869            for (PackageParser.Activity sysActivity : activityList) {
11870                if (sysActivity.info.name.equals(activityInfo.name)) {
11871                    return sysActivity;
11872                }
11873                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11874                    return sysActivity;
11875                }
11876                if (sysActivity.info.targetActivity != null) {
11877                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11878                        return sysActivity;
11879                    }
11880                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11881                        return sysActivity;
11882                    }
11883                }
11884            }
11885            return null;
11886        }
11887
11888        public class IterGenerator<E> {
11889            public Iterator<E> generate(ActivityIntentInfo info) {
11890                return null;
11891            }
11892        }
11893
11894        public class ActionIterGenerator extends IterGenerator<String> {
11895            @Override
11896            public Iterator<String> generate(ActivityIntentInfo info) {
11897                return info.actionsIterator();
11898            }
11899        }
11900
11901        public class CategoriesIterGenerator extends IterGenerator<String> {
11902            @Override
11903            public Iterator<String> generate(ActivityIntentInfo info) {
11904                return info.categoriesIterator();
11905            }
11906        }
11907
11908        public class SchemesIterGenerator extends IterGenerator<String> {
11909            @Override
11910            public Iterator<String> generate(ActivityIntentInfo info) {
11911                return info.schemesIterator();
11912            }
11913        }
11914
11915        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11916            @Override
11917            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11918                return info.authoritiesIterator();
11919            }
11920        }
11921
11922        /**
11923         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11924         * MODIFIED. Do not pass in a list that should not be changed.
11925         */
11926        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11927                IterGenerator<T> generator, Iterator<T> searchIterator) {
11928            // loop through the set of actions; every one must be found in the intent filter
11929            while (searchIterator.hasNext()) {
11930                // we must have at least one filter in the list to consider a match
11931                if (intentList.size() == 0) {
11932                    break;
11933                }
11934
11935                final T searchAction = searchIterator.next();
11936
11937                // loop through the set of intent filters
11938                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11939                while (intentIter.hasNext()) {
11940                    final ActivityIntentInfo intentInfo = intentIter.next();
11941                    boolean selectionFound = false;
11942
11943                    // loop through the intent filter's selection criteria; at least one
11944                    // of them must match the searched criteria
11945                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11946                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11947                        final T intentSelection = intentSelectionIter.next();
11948                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11949                            selectionFound = true;
11950                            break;
11951                        }
11952                    }
11953
11954                    // the selection criteria wasn't found in this filter's set; this filter
11955                    // is not a potential match
11956                    if (!selectionFound) {
11957                        intentIter.remove();
11958                    }
11959                }
11960            }
11961        }
11962
11963        private boolean isProtectedAction(ActivityIntentInfo filter) {
11964            final Iterator<String> actionsIter = filter.actionsIterator();
11965            while (actionsIter != null && actionsIter.hasNext()) {
11966                final String filterAction = actionsIter.next();
11967                if (PROTECTED_ACTIONS.contains(filterAction)) {
11968                    return true;
11969                }
11970            }
11971            return false;
11972        }
11973
11974        /**
11975         * Adjusts the priority of the given intent filter according to policy.
11976         * <p>
11977         * <ul>
11978         * <li>The priority for non privileged applications is capped to '0'</li>
11979         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11980         * <li>The priority for unbundled updates to privileged applications is capped to the
11981         *      priority defined on the system partition</li>
11982         * </ul>
11983         * <p>
11984         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11985         * allowed to obtain any priority on any action.
11986         */
11987        private void adjustPriority(
11988                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11989            // nothing to do; priority is fine as-is
11990            if (intent.getPriority() <= 0) {
11991                return;
11992            }
11993
11994            final ActivityInfo activityInfo = intent.activity.info;
11995            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11996
11997            final boolean privilegedApp =
11998                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11999            if (!privilegedApp) {
12000                // non-privileged applications can never define a priority >0
12001                if (DEBUG_FILTERS) {
12002                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12003                            + " package: " + applicationInfo.packageName
12004                            + " activity: " + intent.activity.className
12005                            + " origPrio: " + intent.getPriority());
12006                }
12007                intent.setPriority(0);
12008                return;
12009            }
12010
12011            if (systemActivities == null) {
12012                // the system package is not disabled; we're parsing the system partition
12013                if (isProtectedAction(intent)) {
12014                    if (mDeferProtectedFilters) {
12015                        // We can't deal with these just yet. No component should ever obtain a
12016                        // >0 priority for a protected actions, with ONE exception -- the setup
12017                        // wizard. The setup wizard, however, cannot be known until we're able to
12018                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12019                        // until all intent filters have been processed. Chicken, meet egg.
12020                        // Let the filter temporarily have a high priority and rectify the
12021                        // priorities after all system packages have been scanned.
12022                        mProtectedFilters.add(intent);
12023                        if (DEBUG_FILTERS) {
12024                            Slog.i(TAG, "Protected action; save for later;"
12025                                    + " package: " + applicationInfo.packageName
12026                                    + " activity: " + intent.activity.className
12027                                    + " origPrio: " + intent.getPriority());
12028                        }
12029                        return;
12030                    } else {
12031                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12032                            Slog.i(TAG, "No setup wizard;"
12033                                + " All protected intents capped to priority 0");
12034                        }
12035                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12036                            if (DEBUG_FILTERS) {
12037                                Slog.i(TAG, "Found setup wizard;"
12038                                    + " allow priority " + intent.getPriority() + ";"
12039                                    + " package: " + intent.activity.info.packageName
12040                                    + " activity: " + intent.activity.className
12041                                    + " priority: " + intent.getPriority());
12042                            }
12043                            // setup wizard gets whatever it wants
12044                            return;
12045                        }
12046                        if (DEBUG_FILTERS) {
12047                            Slog.i(TAG, "Protected action; cap priority to 0;"
12048                                    + " package: " + intent.activity.info.packageName
12049                                    + " activity: " + intent.activity.className
12050                                    + " origPrio: " + intent.getPriority());
12051                        }
12052                        intent.setPriority(0);
12053                        return;
12054                    }
12055                }
12056                // privileged apps on the system image get whatever priority they request
12057                return;
12058            }
12059
12060            // privileged app unbundled update ... try to find the same activity
12061            final PackageParser.Activity foundActivity =
12062                    findMatchingActivity(systemActivities, activityInfo);
12063            if (foundActivity == null) {
12064                // this is a new activity; it cannot obtain >0 priority
12065                if (DEBUG_FILTERS) {
12066                    Slog.i(TAG, "New activity; cap priority to 0;"
12067                            + " package: " + applicationInfo.packageName
12068                            + " activity: " + intent.activity.className
12069                            + " origPrio: " + intent.getPriority());
12070                }
12071                intent.setPriority(0);
12072                return;
12073            }
12074
12075            // found activity, now check for filter equivalence
12076
12077            // a shallow copy is enough; we modify the list, not its contents
12078            final List<ActivityIntentInfo> intentListCopy =
12079                    new ArrayList<>(foundActivity.intents);
12080            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12081
12082            // find matching action subsets
12083            final Iterator<String> actionsIterator = intent.actionsIterator();
12084            if (actionsIterator != null) {
12085                getIntentListSubset(
12086                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12087                if (intentListCopy.size() == 0) {
12088                    // no more intents to match; we're not equivalent
12089                    if (DEBUG_FILTERS) {
12090                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12091                                + " package: " + applicationInfo.packageName
12092                                + " activity: " + intent.activity.className
12093                                + " origPrio: " + intent.getPriority());
12094                    }
12095                    intent.setPriority(0);
12096                    return;
12097                }
12098            }
12099
12100            // find matching category subsets
12101            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12102            if (categoriesIterator != null) {
12103                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12104                        categoriesIterator);
12105                if (intentListCopy.size() == 0) {
12106                    // no more intents to match; we're not equivalent
12107                    if (DEBUG_FILTERS) {
12108                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12109                                + " package: " + applicationInfo.packageName
12110                                + " activity: " + intent.activity.className
12111                                + " origPrio: " + intent.getPriority());
12112                    }
12113                    intent.setPriority(0);
12114                    return;
12115                }
12116            }
12117
12118            // find matching schemes subsets
12119            final Iterator<String> schemesIterator = intent.schemesIterator();
12120            if (schemesIterator != null) {
12121                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12122                        schemesIterator);
12123                if (intentListCopy.size() == 0) {
12124                    // no more intents to match; we're not equivalent
12125                    if (DEBUG_FILTERS) {
12126                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12127                                + " package: " + applicationInfo.packageName
12128                                + " activity: " + intent.activity.className
12129                                + " origPrio: " + intent.getPriority());
12130                    }
12131                    intent.setPriority(0);
12132                    return;
12133                }
12134            }
12135
12136            // find matching authorities subsets
12137            final Iterator<IntentFilter.AuthorityEntry>
12138                    authoritiesIterator = intent.authoritiesIterator();
12139            if (authoritiesIterator != null) {
12140                getIntentListSubset(intentListCopy,
12141                        new AuthoritiesIterGenerator(),
12142                        authoritiesIterator);
12143                if (intentListCopy.size() == 0) {
12144                    // no more intents to match; we're not equivalent
12145                    if (DEBUG_FILTERS) {
12146                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12147                                + " package: " + applicationInfo.packageName
12148                                + " activity: " + intent.activity.className
12149                                + " origPrio: " + intent.getPriority());
12150                    }
12151                    intent.setPriority(0);
12152                    return;
12153                }
12154            }
12155
12156            // we found matching filter(s); app gets the max priority of all intents
12157            int cappedPriority = 0;
12158            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12159                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12160            }
12161            if (intent.getPriority() > cappedPriority) {
12162                if (DEBUG_FILTERS) {
12163                    Slog.i(TAG, "Found matching filter(s);"
12164                            + " cap priority to " + cappedPriority + ";"
12165                            + " package: " + applicationInfo.packageName
12166                            + " activity: " + intent.activity.className
12167                            + " origPrio: " + intent.getPriority());
12168                }
12169                intent.setPriority(cappedPriority);
12170                return;
12171            }
12172            // all this for nothing; the requested priority was <= what was on the system
12173        }
12174
12175        public final void addActivity(PackageParser.Activity a, String type) {
12176            mActivities.put(a.getComponentName(), a);
12177            if (DEBUG_SHOW_INFO)
12178                Log.v(
12179                TAG, "  " + type + " " +
12180                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12181            if (DEBUG_SHOW_INFO)
12182                Log.v(TAG, "    Class=" + a.info.name);
12183            final int NI = a.intents.size();
12184            for (int j=0; j<NI; j++) {
12185                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12186                if ("activity".equals(type)) {
12187                    final PackageSetting ps =
12188                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12189                    final List<PackageParser.Activity> systemActivities =
12190                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12191                    adjustPriority(systemActivities, intent);
12192                }
12193                if (DEBUG_SHOW_INFO) {
12194                    Log.v(TAG, "    IntentFilter:");
12195                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12196                }
12197                if (!intent.debugCheck()) {
12198                    Log.w(TAG, "==> For Activity " + a.info.name);
12199                }
12200                addFilter(intent);
12201            }
12202        }
12203
12204        public final void removeActivity(PackageParser.Activity a, String type) {
12205            mActivities.remove(a.getComponentName());
12206            if (DEBUG_SHOW_INFO) {
12207                Log.v(TAG, "  " + type + " "
12208                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12209                                : a.info.name) + ":");
12210                Log.v(TAG, "    Class=" + a.info.name);
12211            }
12212            final int NI = a.intents.size();
12213            for (int j=0; j<NI; j++) {
12214                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12215                if (DEBUG_SHOW_INFO) {
12216                    Log.v(TAG, "    IntentFilter:");
12217                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12218                }
12219                removeFilter(intent);
12220            }
12221        }
12222
12223        @Override
12224        protected boolean allowFilterResult(
12225                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12226            ActivityInfo filterAi = filter.activity.info;
12227            for (int i=dest.size()-1; i>=0; i--) {
12228                ActivityInfo destAi = dest.get(i).activityInfo;
12229                if (destAi.name == filterAi.name
12230                        && destAi.packageName == filterAi.packageName) {
12231                    return false;
12232                }
12233            }
12234            return true;
12235        }
12236
12237        @Override
12238        protected ActivityIntentInfo[] newArray(int size) {
12239            return new ActivityIntentInfo[size];
12240        }
12241
12242        @Override
12243        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12244            if (!sUserManager.exists(userId)) return true;
12245            PackageParser.Package p = filter.activity.owner;
12246            if (p != null) {
12247                PackageSetting ps = (PackageSetting)p.mExtras;
12248                if (ps != null) {
12249                    // System apps are never considered stopped for purposes of
12250                    // filtering, because there may be no way for the user to
12251                    // actually re-launch them.
12252                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12253                            && ps.getStopped(userId);
12254                }
12255            }
12256            return false;
12257        }
12258
12259        @Override
12260        protected boolean isPackageForFilter(String packageName,
12261                PackageParser.ActivityIntentInfo info) {
12262            return packageName.equals(info.activity.owner.packageName);
12263        }
12264
12265        @Override
12266        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12267                int match, int userId) {
12268            if (!sUserManager.exists(userId)) return null;
12269            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12270                return null;
12271            }
12272            final PackageParser.Activity activity = info.activity;
12273            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12274            if (ps == null) {
12275                return null;
12276            }
12277            final PackageUserState userState = ps.readUserState(userId);
12278            ActivityInfo ai =
12279                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12280            if (ai == null) {
12281                return null;
12282            }
12283            final boolean matchExplicitlyVisibleOnly =
12284                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12285            final boolean matchVisibleToInstantApp =
12286                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12287            final boolean componentVisible =
12288                    matchVisibleToInstantApp
12289                    && info.isVisibleToInstantApp()
12290                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12291            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12292            // throw out filters that aren't visible to ephemeral apps
12293            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12294                return null;
12295            }
12296            // throw out instant app filters if we're not explicitly requesting them
12297            if (!matchInstantApp && userState.instantApp) {
12298                return null;
12299            }
12300            // throw out instant app filters if updates are available; will trigger
12301            // instant app resolution
12302            if (userState.instantApp && ps.isUpdateAvailable()) {
12303                return null;
12304            }
12305            final ResolveInfo res = new ResolveInfo();
12306            res.activityInfo = ai;
12307            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12308                res.filter = info;
12309            }
12310            if (info != null) {
12311                res.handleAllWebDataURI = info.handleAllWebDataURI();
12312            }
12313            res.priority = info.getPriority();
12314            res.preferredOrder = activity.owner.mPreferredOrder;
12315            //System.out.println("Result: " + res.activityInfo.className +
12316            //                   " = " + res.priority);
12317            res.match = match;
12318            res.isDefault = info.hasDefault;
12319            res.labelRes = info.labelRes;
12320            res.nonLocalizedLabel = info.nonLocalizedLabel;
12321            if (userNeedsBadging(userId)) {
12322                res.noResourceId = true;
12323            } else {
12324                res.icon = info.icon;
12325            }
12326            res.iconResourceId = info.icon;
12327            res.system = res.activityInfo.applicationInfo.isSystemApp();
12328            res.isInstantAppAvailable = userState.instantApp;
12329            return res;
12330        }
12331
12332        @Override
12333        protected void sortResults(List<ResolveInfo> results) {
12334            Collections.sort(results, mResolvePrioritySorter);
12335        }
12336
12337        @Override
12338        protected void dumpFilter(PrintWriter out, String prefix,
12339                PackageParser.ActivityIntentInfo filter) {
12340            out.print(prefix); out.print(
12341                    Integer.toHexString(System.identityHashCode(filter.activity)));
12342                    out.print(' ');
12343                    filter.activity.printComponentShortName(out);
12344                    out.print(" filter ");
12345                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12346        }
12347
12348        @Override
12349        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12350            return filter.activity;
12351        }
12352
12353        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12354            PackageParser.Activity activity = (PackageParser.Activity)label;
12355            out.print(prefix); out.print(
12356                    Integer.toHexString(System.identityHashCode(activity)));
12357                    out.print(' ');
12358                    activity.printComponentShortName(out);
12359            if (count > 1) {
12360                out.print(" ("); out.print(count); out.print(" filters)");
12361            }
12362            out.println();
12363        }
12364
12365        // Keys are String (activity class name), values are Activity.
12366        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12367                = new ArrayMap<ComponentName, PackageParser.Activity>();
12368        private int mFlags;
12369    }
12370
12371    private final class ServiceIntentResolver
12372            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12373        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12374                boolean defaultOnly, int userId) {
12375            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12376            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12377        }
12378
12379        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12380                int userId) {
12381            if (!sUserManager.exists(userId)) return null;
12382            mFlags = flags;
12383            return super.queryIntent(intent, resolvedType,
12384                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12385                    userId);
12386        }
12387
12388        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12389                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12390            if (!sUserManager.exists(userId)) return null;
12391            if (packageServices == null) {
12392                return null;
12393            }
12394            mFlags = flags;
12395            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12396            final int N = packageServices.size();
12397            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12398                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12399
12400            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12401            for (int i = 0; i < N; ++i) {
12402                intentFilters = packageServices.get(i).intents;
12403                if (intentFilters != null && intentFilters.size() > 0) {
12404                    PackageParser.ServiceIntentInfo[] array =
12405                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12406                    intentFilters.toArray(array);
12407                    listCut.add(array);
12408                }
12409            }
12410            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12411        }
12412
12413        public final void addService(PackageParser.Service s) {
12414            mServices.put(s.getComponentName(), s);
12415            if (DEBUG_SHOW_INFO) {
12416                Log.v(TAG, "  "
12417                        + (s.info.nonLocalizedLabel != null
12418                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12419                Log.v(TAG, "    Class=" + s.info.name);
12420            }
12421            final int NI = s.intents.size();
12422            int j;
12423            for (j=0; j<NI; j++) {
12424                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12425                if (DEBUG_SHOW_INFO) {
12426                    Log.v(TAG, "    IntentFilter:");
12427                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12428                }
12429                if (!intent.debugCheck()) {
12430                    Log.w(TAG, "==> For Service " + s.info.name);
12431                }
12432                addFilter(intent);
12433            }
12434        }
12435
12436        public final void removeService(PackageParser.Service s) {
12437            mServices.remove(s.getComponentName());
12438            if (DEBUG_SHOW_INFO) {
12439                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12440                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12441                Log.v(TAG, "    Class=" + s.info.name);
12442            }
12443            final int NI = s.intents.size();
12444            int j;
12445            for (j=0; j<NI; j++) {
12446                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12447                if (DEBUG_SHOW_INFO) {
12448                    Log.v(TAG, "    IntentFilter:");
12449                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12450                }
12451                removeFilter(intent);
12452            }
12453        }
12454
12455        @Override
12456        protected boolean allowFilterResult(
12457                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12458            ServiceInfo filterSi = filter.service.info;
12459            for (int i=dest.size()-1; i>=0; i--) {
12460                ServiceInfo destAi = dest.get(i).serviceInfo;
12461                if (destAi.name == filterSi.name
12462                        && destAi.packageName == filterSi.packageName) {
12463                    return false;
12464                }
12465            }
12466            return true;
12467        }
12468
12469        @Override
12470        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12471            return new PackageParser.ServiceIntentInfo[size];
12472        }
12473
12474        @Override
12475        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12476            if (!sUserManager.exists(userId)) return true;
12477            PackageParser.Package p = filter.service.owner;
12478            if (p != null) {
12479                PackageSetting ps = (PackageSetting)p.mExtras;
12480                if (ps != null) {
12481                    // System apps are never considered stopped for purposes of
12482                    // filtering, because there may be no way for the user to
12483                    // actually re-launch them.
12484                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12485                            && ps.getStopped(userId);
12486                }
12487            }
12488            return false;
12489        }
12490
12491        @Override
12492        protected boolean isPackageForFilter(String packageName,
12493                PackageParser.ServiceIntentInfo info) {
12494            return packageName.equals(info.service.owner.packageName);
12495        }
12496
12497        @Override
12498        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12499                int match, int userId) {
12500            if (!sUserManager.exists(userId)) return null;
12501            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12502            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12503                return null;
12504            }
12505            final PackageParser.Service service = info.service;
12506            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12507            if (ps == null) {
12508                return null;
12509            }
12510            final PackageUserState userState = ps.readUserState(userId);
12511            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12512                    userState, userId);
12513            if (si == null) {
12514                return null;
12515            }
12516            final boolean matchVisibleToInstantApp =
12517                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12518            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12519            // throw out filters that aren't visible to ephemeral apps
12520            if (matchVisibleToInstantApp
12521                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12522                return null;
12523            }
12524            // throw out ephemeral filters if we're not explicitly requesting them
12525            if (!isInstantApp && userState.instantApp) {
12526                return null;
12527            }
12528            // throw out instant app filters if updates are available; will trigger
12529            // instant app resolution
12530            if (userState.instantApp && ps.isUpdateAvailable()) {
12531                return null;
12532            }
12533            final ResolveInfo res = new ResolveInfo();
12534            res.serviceInfo = si;
12535            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12536                res.filter = filter;
12537            }
12538            res.priority = info.getPriority();
12539            res.preferredOrder = service.owner.mPreferredOrder;
12540            res.match = match;
12541            res.isDefault = info.hasDefault;
12542            res.labelRes = info.labelRes;
12543            res.nonLocalizedLabel = info.nonLocalizedLabel;
12544            res.icon = info.icon;
12545            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12546            return res;
12547        }
12548
12549        @Override
12550        protected void sortResults(List<ResolveInfo> results) {
12551            Collections.sort(results, mResolvePrioritySorter);
12552        }
12553
12554        @Override
12555        protected void dumpFilter(PrintWriter out, String prefix,
12556                PackageParser.ServiceIntentInfo filter) {
12557            out.print(prefix); out.print(
12558                    Integer.toHexString(System.identityHashCode(filter.service)));
12559                    out.print(' ');
12560                    filter.service.printComponentShortName(out);
12561                    out.print(" filter ");
12562                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12563                    if (filter.service.info.permission != null) {
12564                        out.print(" permission "); out.println(filter.service.info.permission);
12565                    } else {
12566                        out.println();
12567                    }
12568        }
12569
12570        @Override
12571        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12572            return filter.service;
12573        }
12574
12575        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12576            PackageParser.Service service = (PackageParser.Service)label;
12577            out.print(prefix); out.print(
12578                    Integer.toHexString(System.identityHashCode(service)));
12579                    out.print(' ');
12580                    service.printComponentShortName(out);
12581            if (count > 1) {
12582                out.print(" ("); out.print(count); out.print(" filters)");
12583            }
12584            out.println();
12585        }
12586
12587//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12588//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12589//            final List<ResolveInfo> retList = Lists.newArrayList();
12590//            while (i.hasNext()) {
12591//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12592//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12593//                    retList.add(resolveInfo);
12594//                }
12595//            }
12596//            return retList;
12597//        }
12598
12599        // Keys are String (activity class name), values are Activity.
12600        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12601                = new ArrayMap<ComponentName, PackageParser.Service>();
12602        private int mFlags;
12603    }
12604
12605    private final class ProviderIntentResolver
12606            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12607        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12608                boolean defaultOnly, int userId) {
12609            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12610            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12611        }
12612
12613        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12614                int userId) {
12615            if (!sUserManager.exists(userId))
12616                return null;
12617            mFlags = flags;
12618            return super.queryIntent(intent, resolvedType,
12619                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12620                    userId);
12621        }
12622
12623        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12624                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12625            if (!sUserManager.exists(userId))
12626                return null;
12627            if (packageProviders == null) {
12628                return null;
12629            }
12630            mFlags = flags;
12631            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12632            final int N = packageProviders.size();
12633            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12634                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12635
12636            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12637            for (int i = 0; i < N; ++i) {
12638                intentFilters = packageProviders.get(i).intents;
12639                if (intentFilters != null && intentFilters.size() > 0) {
12640                    PackageParser.ProviderIntentInfo[] array =
12641                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12642                    intentFilters.toArray(array);
12643                    listCut.add(array);
12644                }
12645            }
12646            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12647        }
12648
12649        public final void addProvider(PackageParser.Provider p) {
12650            if (mProviders.containsKey(p.getComponentName())) {
12651                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12652                return;
12653            }
12654
12655            mProviders.put(p.getComponentName(), p);
12656            if (DEBUG_SHOW_INFO) {
12657                Log.v(TAG, "  "
12658                        + (p.info.nonLocalizedLabel != null
12659                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12660                Log.v(TAG, "    Class=" + p.info.name);
12661            }
12662            final int NI = p.intents.size();
12663            int j;
12664            for (j = 0; j < NI; j++) {
12665                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12666                if (DEBUG_SHOW_INFO) {
12667                    Log.v(TAG, "    IntentFilter:");
12668                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12669                }
12670                if (!intent.debugCheck()) {
12671                    Log.w(TAG, "==> For Provider " + p.info.name);
12672                }
12673                addFilter(intent);
12674            }
12675        }
12676
12677        public final void removeProvider(PackageParser.Provider p) {
12678            mProviders.remove(p.getComponentName());
12679            if (DEBUG_SHOW_INFO) {
12680                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12681                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12682                Log.v(TAG, "    Class=" + p.info.name);
12683            }
12684            final int NI = p.intents.size();
12685            int j;
12686            for (j = 0; j < NI; j++) {
12687                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12688                if (DEBUG_SHOW_INFO) {
12689                    Log.v(TAG, "    IntentFilter:");
12690                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12691                }
12692                removeFilter(intent);
12693            }
12694        }
12695
12696        @Override
12697        protected boolean allowFilterResult(
12698                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12699            ProviderInfo filterPi = filter.provider.info;
12700            for (int i = dest.size() - 1; i >= 0; i--) {
12701                ProviderInfo destPi = dest.get(i).providerInfo;
12702                if (destPi.name == filterPi.name
12703                        && destPi.packageName == filterPi.packageName) {
12704                    return false;
12705                }
12706            }
12707            return true;
12708        }
12709
12710        @Override
12711        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12712            return new PackageParser.ProviderIntentInfo[size];
12713        }
12714
12715        @Override
12716        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12717            if (!sUserManager.exists(userId))
12718                return true;
12719            PackageParser.Package p = filter.provider.owner;
12720            if (p != null) {
12721                PackageSetting ps = (PackageSetting) p.mExtras;
12722                if (ps != null) {
12723                    // System apps are never considered stopped for purposes of
12724                    // filtering, because there may be no way for the user to
12725                    // actually re-launch them.
12726                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12727                            && ps.getStopped(userId);
12728                }
12729            }
12730            return false;
12731        }
12732
12733        @Override
12734        protected boolean isPackageForFilter(String packageName,
12735                PackageParser.ProviderIntentInfo info) {
12736            return packageName.equals(info.provider.owner.packageName);
12737        }
12738
12739        @Override
12740        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12741                int match, int userId) {
12742            if (!sUserManager.exists(userId))
12743                return null;
12744            final PackageParser.ProviderIntentInfo info = filter;
12745            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12746                return null;
12747            }
12748            final PackageParser.Provider provider = info.provider;
12749            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12750            if (ps == null) {
12751                return null;
12752            }
12753            final PackageUserState userState = ps.readUserState(userId);
12754            final boolean matchVisibleToInstantApp =
12755                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12756            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12757            // throw out filters that aren't visible to instant applications
12758            if (matchVisibleToInstantApp
12759                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12760                return null;
12761            }
12762            // throw out instant application filters if we're not explicitly requesting them
12763            if (!isInstantApp && userState.instantApp) {
12764                return null;
12765            }
12766            // throw out instant application filters if updates are available; will trigger
12767            // instant application resolution
12768            if (userState.instantApp && ps.isUpdateAvailable()) {
12769                return null;
12770            }
12771            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12772                    userState, userId);
12773            if (pi == null) {
12774                return null;
12775            }
12776            final ResolveInfo res = new ResolveInfo();
12777            res.providerInfo = pi;
12778            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12779                res.filter = filter;
12780            }
12781            res.priority = info.getPriority();
12782            res.preferredOrder = provider.owner.mPreferredOrder;
12783            res.match = match;
12784            res.isDefault = info.hasDefault;
12785            res.labelRes = info.labelRes;
12786            res.nonLocalizedLabel = info.nonLocalizedLabel;
12787            res.icon = info.icon;
12788            res.system = res.providerInfo.applicationInfo.isSystemApp();
12789            return res;
12790        }
12791
12792        @Override
12793        protected void sortResults(List<ResolveInfo> results) {
12794            Collections.sort(results, mResolvePrioritySorter);
12795        }
12796
12797        @Override
12798        protected void dumpFilter(PrintWriter out, String prefix,
12799                PackageParser.ProviderIntentInfo filter) {
12800            out.print(prefix);
12801            out.print(
12802                    Integer.toHexString(System.identityHashCode(filter.provider)));
12803            out.print(' ');
12804            filter.provider.printComponentShortName(out);
12805            out.print(" filter ");
12806            out.println(Integer.toHexString(System.identityHashCode(filter)));
12807        }
12808
12809        @Override
12810        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12811            return filter.provider;
12812        }
12813
12814        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12815            PackageParser.Provider provider = (PackageParser.Provider)label;
12816            out.print(prefix); out.print(
12817                    Integer.toHexString(System.identityHashCode(provider)));
12818                    out.print(' ');
12819                    provider.printComponentShortName(out);
12820            if (count > 1) {
12821                out.print(" ("); out.print(count); out.print(" filters)");
12822            }
12823            out.println();
12824        }
12825
12826        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12827                = new ArrayMap<ComponentName, PackageParser.Provider>();
12828        private int mFlags;
12829    }
12830
12831    static final class EphemeralIntentResolver
12832            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12833        /**
12834         * The result that has the highest defined order. Ordering applies on a
12835         * per-package basis. Mapping is from package name to Pair of order and
12836         * EphemeralResolveInfo.
12837         * <p>
12838         * NOTE: This is implemented as a field variable for convenience and efficiency.
12839         * By having a field variable, we're able to track filter ordering as soon as
12840         * a non-zero order is defined. Otherwise, multiple loops across the result set
12841         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12842         * this needs to be contained entirely within {@link #filterResults}.
12843         */
12844        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12845
12846        @Override
12847        protected AuxiliaryResolveInfo[] newArray(int size) {
12848            return new AuxiliaryResolveInfo[size];
12849        }
12850
12851        @Override
12852        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12853            return true;
12854        }
12855
12856        @Override
12857        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12858                int userId) {
12859            if (!sUserManager.exists(userId)) {
12860                return null;
12861            }
12862            final String packageName = responseObj.resolveInfo.getPackageName();
12863            final Integer order = responseObj.getOrder();
12864            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12865                    mOrderResult.get(packageName);
12866            // ordering is enabled and this item's order isn't high enough
12867            if (lastOrderResult != null && lastOrderResult.first >= order) {
12868                return null;
12869            }
12870            final InstantAppResolveInfo res = responseObj.resolveInfo;
12871            if (order > 0) {
12872                // non-zero order, enable ordering
12873                mOrderResult.put(packageName, new Pair<>(order, res));
12874            }
12875            return responseObj;
12876        }
12877
12878        @Override
12879        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12880            // only do work if ordering is enabled [most of the time it won't be]
12881            if (mOrderResult.size() == 0) {
12882                return;
12883            }
12884            int resultSize = results.size();
12885            for (int i = 0; i < resultSize; i++) {
12886                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12887                final String packageName = info.getPackageName();
12888                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12889                if (savedInfo == null) {
12890                    // package doesn't having ordering
12891                    continue;
12892                }
12893                if (savedInfo.second == info) {
12894                    // circled back to the highest ordered item; remove from order list
12895                    mOrderResult.remove(packageName);
12896                    if (mOrderResult.size() == 0) {
12897                        // no more ordered items
12898                        break;
12899                    }
12900                    continue;
12901                }
12902                // item has a worse order, remove it from the result list
12903                results.remove(i);
12904                resultSize--;
12905                i--;
12906            }
12907        }
12908    }
12909
12910    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12911            new Comparator<ResolveInfo>() {
12912        public int compare(ResolveInfo r1, ResolveInfo r2) {
12913            int v1 = r1.priority;
12914            int v2 = r2.priority;
12915            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12916            if (v1 != v2) {
12917                return (v1 > v2) ? -1 : 1;
12918            }
12919            v1 = r1.preferredOrder;
12920            v2 = r2.preferredOrder;
12921            if (v1 != v2) {
12922                return (v1 > v2) ? -1 : 1;
12923            }
12924            if (r1.isDefault != r2.isDefault) {
12925                return r1.isDefault ? -1 : 1;
12926            }
12927            v1 = r1.match;
12928            v2 = r2.match;
12929            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12930            if (v1 != v2) {
12931                return (v1 > v2) ? -1 : 1;
12932            }
12933            if (r1.system != r2.system) {
12934                return r1.system ? -1 : 1;
12935            }
12936            if (r1.activityInfo != null) {
12937                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12938            }
12939            if (r1.serviceInfo != null) {
12940                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12941            }
12942            if (r1.providerInfo != null) {
12943                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12944            }
12945            return 0;
12946        }
12947    };
12948
12949    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12950            new Comparator<ProviderInfo>() {
12951        public int compare(ProviderInfo p1, ProviderInfo p2) {
12952            final int v1 = p1.initOrder;
12953            final int v2 = p2.initOrder;
12954            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12955        }
12956    };
12957
12958    @Override
12959    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12960            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12961            final int[] userIds, int[] instantUserIds) {
12962        mHandler.post(new Runnable() {
12963            @Override
12964            public void run() {
12965                try {
12966                    final IActivityManager am = ActivityManager.getService();
12967                    if (am == null) return;
12968                    final int[] resolvedUserIds;
12969                    if (userIds == null) {
12970                        resolvedUserIds = am.getRunningUserIds();
12971                    } else {
12972                        resolvedUserIds = userIds;
12973                    }
12974                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12975                            resolvedUserIds, false);
12976                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
12977                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12978                                instantUserIds, true);
12979                    }
12980                } catch (RemoteException ex) {
12981                }
12982            }
12983        });
12984    }
12985
12986    /**
12987     * Sends a broadcast for the given action.
12988     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
12989     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
12990     * the system and applications allowed to see instant applications to receive package
12991     * lifecycle events for instant applications.
12992     */
12993    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
12994            int flags, String targetPkg, IIntentReceiver finishedReceiver,
12995            int[] userIds, boolean isInstantApp)
12996                    throws RemoteException {
12997        for (int id : userIds) {
12998            final Intent intent = new Intent(action,
12999                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13000            final String[] requiredPermissions =
13001                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13002            if (extras != null) {
13003                intent.putExtras(extras);
13004            }
13005            if (targetPkg != null) {
13006                intent.setPackage(targetPkg);
13007            }
13008            // Modify the UID when posting to other users
13009            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13010            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13011                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13012                intent.putExtra(Intent.EXTRA_UID, uid);
13013            }
13014            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13015            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13016            if (DEBUG_BROADCASTS) {
13017                RuntimeException here = new RuntimeException("here");
13018                here.fillInStackTrace();
13019                Slog.d(TAG, "Sending to user " + id + ": "
13020                        + intent.toShortString(false, true, false, false)
13021                        + " " + intent.getExtras(), here);
13022            }
13023            am.broadcastIntent(null, intent, null, finishedReceiver,
13024                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13025                    null, finishedReceiver != null, false, id);
13026        }
13027    }
13028
13029    /**
13030     * Check if the external storage media is available. This is true if there
13031     * is a mounted external storage medium or if the external storage is
13032     * emulated.
13033     */
13034    private boolean isExternalMediaAvailable() {
13035        return mMediaMounted || Environment.isExternalStorageEmulated();
13036    }
13037
13038    @Override
13039    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13040        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13041            return null;
13042        }
13043        if (!isExternalMediaAvailable()) {
13044                // If the external storage is no longer mounted at this point,
13045                // the caller may not have been able to delete all of this
13046                // packages files and can not delete any more.  Bail.
13047            return null;
13048        }
13049        synchronized (mPackages) {
13050            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13051            if (lastPackage != null) {
13052                pkgs.remove(lastPackage);
13053            }
13054            if (pkgs.size() > 0) {
13055                return pkgs.get(0);
13056            }
13057        }
13058        return null;
13059    }
13060
13061    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13062        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13063                userId, andCode ? 1 : 0, packageName);
13064        if (mSystemReady) {
13065            msg.sendToTarget();
13066        } else {
13067            if (mPostSystemReadyMessages == null) {
13068                mPostSystemReadyMessages = new ArrayList<>();
13069            }
13070            mPostSystemReadyMessages.add(msg);
13071        }
13072    }
13073
13074    void startCleaningPackages() {
13075        // reader
13076        if (!isExternalMediaAvailable()) {
13077            return;
13078        }
13079        synchronized (mPackages) {
13080            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13081                return;
13082            }
13083        }
13084        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13085        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13086        IActivityManager am = ActivityManager.getService();
13087        if (am != null) {
13088            int dcsUid = -1;
13089            synchronized (mPackages) {
13090                if (!mDefaultContainerWhitelisted) {
13091                    mDefaultContainerWhitelisted = true;
13092                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13093                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13094                }
13095            }
13096            try {
13097                if (dcsUid > 0) {
13098                    am.backgroundWhitelistUid(dcsUid);
13099                }
13100                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13101                        UserHandle.USER_SYSTEM);
13102            } catch (RemoteException e) {
13103            }
13104        }
13105    }
13106
13107    @Override
13108    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13109            int installFlags, String installerPackageName, int userId) {
13110        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13111
13112        final int callingUid = Binder.getCallingUid();
13113        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13114                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13115
13116        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13117            try {
13118                if (observer != null) {
13119                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13120                }
13121            } catch (RemoteException re) {
13122            }
13123            return;
13124        }
13125
13126        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13127            installFlags |= PackageManager.INSTALL_FROM_ADB;
13128
13129        } else {
13130            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13131            // about installerPackageName.
13132
13133            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13134            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13135        }
13136
13137        UserHandle user;
13138        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13139            user = UserHandle.ALL;
13140        } else {
13141            user = new UserHandle(userId);
13142        }
13143
13144        // Only system components can circumvent runtime permissions when installing.
13145        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13146                && mContext.checkCallingOrSelfPermission(Manifest.permission
13147                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13148            throw new SecurityException("You need the "
13149                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13150                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13151        }
13152
13153        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13154                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13155            throw new IllegalArgumentException(
13156                    "New installs into ASEC containers no longer supported");
13157        }
13158
13159        final File originFile = new File(originPath);
13160        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13161
13162        final Message msg = mHandler.obtainMessage(INIT_COPY);
13163        final VerificationInfo verificationInfo = new VerificationInfo(
13164                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13165        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13166                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13167                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13168                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13169        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13170        msg.obj = params;
13171
13172        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13173                System.identityHashCode(msg.obj));
13174        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13175                System.identityHashCode(msg.obj));
13176
13177        mHandler.sendMessage(msg);
13178    }
13179
13180
13181    /**
13182     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13183     * it is acting on behalf on an enterprise or the user).
13184     *
13185     * Note that the ordering of the conditionals in this method is important. The checks we perform
13186     * are as follows, in this order:
13187     *
13188     * 1) If the install is being performed by a system app, we can trust the app to have set the
13189     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13190     *    what it is.
13191     * 2) If the install is being performed by a device or profile owner app, the install reason
13192     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13193     *    set the install reason correctly. If the app targets an older SDK version where install
13194     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13195     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13196     * 3) In all other cases, the install is being performed by a regular app that is neither part
13197     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13198     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13199     *    set to enterprise policy and if so, change it to unknown instead.
13200     */
13201    private int fixUpInstallReason(String installerPackageName, int installerUid,
13202            int installReason) {
13203        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13204                == PERMISSION_GRANTED) {
13205            // If the install is being performed by a system app, we trust that app to have set the
13206            // install reason correctly.
13207            return installReason;
13208        }
13209
13210        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13211            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13212        if (dpm != null) {
13213            ComponentName owner = null;
13214            try {
13215                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13216                if (owner == null) {
13217                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13218                }
13219            } catch (RemoteException e) {
13220            }
13221            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13222                // If the install is being performed by a device or profile owner, the install
13223                // reason should be enterprise policy.
13224                return PackageManager.INSTALL_REASON_POLICY;
13225            }
13226        }
13227
13228        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13229            // If the install is being performed by a regular app (i.e. neither system app nor
13230            // device or profile owner), we have no reason to believe that the app is acting on
13231            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13232            // change it to unknown instead.
13233            return PackageManager.INSTALL_REASON_UNKNOWN;
13234        }
13235
13236        // If the install is being performed by a regular app and the install reason was set to any
13237        // value but enterprise policy, leave the install reason unchanged.
13238        return installReason;
13239    }
13240
13241    void installStage(String packageName, File stagedDir,
13242            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13243            String installerPackageName, int installerUid, UserHandle user,
13244            Certificate[][] certificates) {
13245        if (DEBUG_EPHEMERAL) {
13246            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13247                Slog.d(TAG, "Ephemeral install of " + packageName);
13248            }
13249        }
13250        final VerificationInfo verificationInfo = new VerificationInfo(
13251                sessionParams.originatingUri, sessionParams.referrerUri,
13252                sessionParams.originatingUid, installerUid);
13253
13254        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13255
13256        final Message msg = mHandler.obtainMessage(INIT_COPY);
13257        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13258                sessionParams.installReason);
13259        final InstallParams params = new InstallParams(origin, null, observer,
13260                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13261                verificationInfo, user, sessionParams.abiOverride,
13262                sessionParams.grantedRuntimePermissions, certificates, installReason);
13263        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13264        msg.obj = params;
13265
13266        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13267                System.identityHashCode(msg.obj));
13268        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13269                System.identityHashCode(msg.obj));
13270
13271        mHandler.sendMessage(msg);
13272    }
13273
13274    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13275            int userId) {
13276        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13277        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13278        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13279        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13280        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13281                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13282
13283        // Send a session commit broadcast
13284        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13285        info.installReason = pkgSetting.getInstallReason(userId);
13286        info.appPackageName = packageName;
13287        sendSessionCommitBroadcast(info, userId);
13288    }
13289
13290    @Override
13291    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13292            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13293        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13294            return;
13295        }
13296        Bundle extras = new Bundle(1);
13297        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13298        final int uid = UserHandle.getUid(
13299                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13300        extras.putInt(Intent.EXTRA_UID, uid);
13301
13302        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13303                packageName, extras, 0, null, null, userIds, instantUserIds);
13304        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13305            mHandler.post(() -> {
13306                        for (int userId : userIds) {
13307                            sendBootCompletedBroadcastToSystemApp(
13308                                    packageName, includeStopped, userId);
13309                        }
13310                    }
13311            );
13312        }
13313    }
13314
13315    /**
13316     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13317     * automatically without needing an explicit launch.
13318     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13319     */
13320    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13321            int userId) {
13322        // If user is not running, the app didn't miss any broadcast
13323        if (!mUserManagerInternal.isUserRunning(userId)) {
13324            return;
13325        }
13326        final IActivityManager am = ActivityManager.getService();
13327        try {
13328            // Deliver LOCKED_BOOT_COMPLETED first
13329            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13330                    .setPackage(packageName);
13331            if (includeStopped) {
13332                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13333            }
13334            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13335            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13336                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13337
13338            // Deliver BOOT_COMPLETED only if user is unlocked
13339            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13340                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13341                if (includeStopped) {
13342                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13343                }
13344                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13345                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13346            }
13347        } catch (RemoteException e) {
13348            throw e.rethrowFromSystemServer();
13349        }
13350    }
13351
13352    @Override
13353    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13354            int userId) {
13355        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13356        PackageSetting pkgSetting;
13357        final int callingUid = Binder.getCallingUid();
13358        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13359                true /* requireFullPermission */, true /* checkShell */,
13360                "setApplicationHiddenSetting for user " + userId);
13361
13362        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13363            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13364            return false;
13365        }
13366
13367        long callingId = Binder.clearCallingIdentity();
13368        try {
13369            boolean sendAdded = false;
13370            boolean sendRemoved = false;
13371            // writer
13372            synchronized (mPackages) {
13373                pkgSetting = mSettings.mPackages.get(packageName);
13374                if (pkgSetting == null) {
13375                    return false;
13376                }
13377                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13378                    return false;
13379                }
13380                // Do not allow "android" is being disabled
13381                if ("android".equals(packageName)) {
13382                    Slog.w(TAG, "Cannot hide package: android");
13383                    return false;
13384                }
13385                // Cannot hide static shared libs as they are considered
13386                // a part of the using app (emulating static linking). Also
13387                // static libs are installed always on internal storage.
13388                PackageParser.Package pkg = mPackages.get(packageName);
13389                if (pkg != null && pkg.staticSharedLibName != null) {
13390                    Slog.w(TAG, "Cannot hide package: " + packageName
13391                            + " providing static shared library: "
13392                            + pkg.staticSharedLibName);
13393                    return false;
13394                }
13395                // Only allow protected packages to hide themselves.
13396                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13397                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13398                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13399                    return false;
13400                }
13401
13402                if (pkgSetting.getHidden(userId) != hidden) {
13403                    pkgSetting.setHidden(hidden, userId);
13404                    mSettings.writePackageRestrictionsLPr(userId);
13405                    if (hidden) {
13406                        sendRemoved = true;
13407                    } else {
13408                        sendAdded = true;
13409                    }
13410                }
13411            }
13412            if (sendAdded) {
13413                sendPackageAddedForUser(packageName, pkgSetting, userId);
13414                return true;
13415            }
13416            if (sendRemoved) {
13417                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13418                        "hiding pkg");
13419                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13420                return true;
13421            }
13422        } finally {
13423            Binder.restoreCallingIdentity(callingId);
13424        }
13425        return false;
13426    }
13427
13428    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13429            int userId) {
13430        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13431        info.removedPackage = packageName;
13432        info.installerPackageName = pkgSetting.installerPackageName;
13433        info.removedUsers = new int[] {userId};
13434        info.broadcastUsers = new int[] {userId};
13435        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13436        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13437    }
13438
13439    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13440        if (pkgList.length > 0) {
13441            Bundle extras = new Bundle(1);
13442            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13443
13444            sendPackageBroadcast(
13445                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13446                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13447                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13448                    new int[] {userId}, null);
13449        }
13450    }
13451
13452    /**
13453     * Returns true if application is not found or there was an error. Otherwise it returns
13454     * the hidden state of the package for the given user.
13455     */
13456    @Override
13457    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13458        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13459        final int callingUid = Binder.getCallingUid();
13460        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13461                true /* requireFullPermission */, false /* checkShell */,
13462                "getApplicationHidden for user " + userId);
13463        PackageSetting ps;
13464        long callingId = Binder.clearCallingIdentity();
13465        try {
13466            // writer
13467            synchronized (mPackages) {
13468                ps = mSettings.mPackages.get(packageName);
13469                if (ps == null) {
13470                    return true;
13471                }
13472                if (filterAppAccessLPr(ps, callingUid, userId)) {
13473                    return true;
13474                }
13475                return ps.getHidden(userId);
13476            }
13477        } finally {
13478            Binder.restoreCallingIdentity(callingId);
13479        }
13480    }
13481
13482    /**
13483     * @hide
13484     */
13485    @Override
13486    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13487            int installReason) {
13488        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13489                null);
13490        PackageSetting pkgSetting;
13491        final int callingUid = Binder.getCallingUid();
13492        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13493                true /* requireFullPermission */, true /* checkShell */,
13494                "installExistingPackage for user " + userId);
13495        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13496            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13497        }
13498
13499        long callingId = Binder.clearCallingIdentity();
13500        try {
13501            boolean installed = false;
13502            final boolean instantApp =
13503                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13504            final boolean fullApp =
13505                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13506
13507            // writer
13508            synchronized (mPackages) {
13509                pkgSetting = mSettings.mPackages.get(packageName);
13510                if (pkgSetting == null) {
13511                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13512                }
13513                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13514                    // only allow the existing package to be used if it's installed as a full
13515                    // application for at least one user
13516                    boolean installAllowed = false;
13517                    for (int checkUserId : sUserManager.getUserIds()) {
13518                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13519                        if (installAllowed) {
13520                            break;
13521                        }
13522                    }
13523                    if (!installAllowed) {
13524                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13525                    }
13526                }
13527                if (!pkgSetting.getInstalled(userId)) {
13528                    pkgSetting.setInstalled(true, userId);
13529                    pkgSetting.setHidden(false, userId);
13530                    pkgSetting.setInstallReason(installReason, userId);
13531                    mSettings.writePackageRestrictionsLPr(userId);
13532                    mSettings.writeKernelMappingLPr(pkgSetting);
13533                    installed = true;
13534                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13535                    // upgrade app from instant to full; we don't allow app downgrade
13536                    installed = true;
13537                }
13538                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13539            }
13540
13541            if (installed) {
13542                if (pkgSetting.pkg != null) {
13543                    synchronized (mInstallLock) {
13544                        // We don't need to freeze for a brand new install
13545                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13546                    }
13547                }
13548                sendPackageAddedForUser(packageName, pkgSetting, userId);
13549                synchronized (mPackages) {
13550                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13551                }
13552            }
13553        } finally {
13554            Binder.restoreCallingIdentity(callingId);
13555        }
13556
13557        return PackageManager.INSTALL_SUCCEEDED;
13558    }
13559
13560    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13561            boolean instantApp, boolean fullApp) {
13562        // no state specified; do nothing
13563        if (!instantApp && !fullApp) {
13564            return;
13565        }
13566        if (userId != UserHandle.USER_ALL) {
13567            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13568                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13569            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13570                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13571            }
13572        } else {
13573            for (int currentUserId : sUserManager.getUserIds()) {
13574                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13575                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13576                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13577                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13578                }
13579            }
13580        }
13581    }
13582
13583    boolean isUserRestricted(int userId, String restrictionKey) {
13584        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13585        if (restrictions.getBoolean(restrictionKey, false)) {
13586            Log.w(TAG, "User is restricted: " + restrictionKey);
13587            return true;
13588        }
13589        return false;
13590    }
13591
13592    @Override
13593    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13594            int userId) {
13595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13596        final int callingUid = Binder.getCallingUid();
13597        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13598                true /* requireFullPermission */, true /* checkShell */,
13599                "setPackagesSuspended for user " + userId);
13600
13601        if (ArrayUtils.isEmpty(packageNames)) {
13602            return packageNames;
13603        }
13604
13605        // List of package names for whom the suspended state has changed.
13606        List<String> changedPackages = new ArrayList<>(packageNames.length);
13607        // List of package names for whom the suspended state is not set as requested in this
13608        // method.
13609        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13610        long callingId = Binder.clearCallingIdentity();
13611        try {
13612            for (int i = 0; i < packageNames.length; i++) {
13613                String packageName = packageNames[i];
13614                boolean changed = false;
13615                final int appId;
13616                synchronized (mPackages) {
13617                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13618                    if (pkgSetting == null
13619                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13620                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13621                                + "\". Skipping suspending/un-suspending.");
13622                        unactionedPackages.add(packageName);
13623                        continue;
13624                    }
13625                    appId = pkgSetting.appId;
13626                    if (pkgSetting.getSuspended(userId) != suspended) {
13627                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13628                            unactionedPackages.add(packageName);
13629                            continue;
13630                        }
13631                        pkgSetting.setSuspended(suspended, userId);
13632                        mSettings.writePackageRestrictionsLPr(userId);
13633                        changed = true;
13634                        changedPackages.add(packageName);
13635                    }
13636                }
13637
13638                if (changed && suspended) {
13639                    killApplication(packageName, UserHandle.getUid(userId, appId),
13640                            "suspending package");
13641                }
13642            }
13643        } finally {
13644            Binder.restoreCallingIdentity(callingId);
13645        }
13646
13647        if (!changedPackages.isEmpty()) {
13648            sendPackagesSuspendedForUser(changedPackages.toArray(
13649                    new String[changedPackages.size()]), userId, suspended);
13650        }
13651
13652        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13653    }
13654
13655    @Override
13656    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13657        final int callingUid = Binder.getCallingUid();
13658        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13659                true /* requireFullPermission */, false /* checkShell */,
13660                "isPackageSuspendedForUser for user " + userId);
13661        synchronized (mPackages) {
13662            final PackageSetting ps = mSettings.mPackages.get(packageName);
13663            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13664                throw new IllegalArgumentException("Unknown target package: " + packageName);
13665            }
13666            return ps.getSuspended(userId);
13667        }
13668    }
13669
13670    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13671        if (isPackageDeviceAdmin(packageName, userId)) {
13672            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13673                    + "\": has an active device admin");
13674            return false;
13675        }
13676
13677        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13678        if (packageName.equals(activeLauncherPackageName)) {
13679            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13680                    + "\": contains the active launcher");
13681            return false;
13682        }
13683
13684        if (packageName.equals(mRequiredInstallerPackage)) {
13685            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13686                    + "\": required for package installation");
13687            return false;
13688        }
13689
13690        if (packageName.equals(mRequiredUninstallerPackage)) {
13691            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13692                    + "\": required for package uninstallation");
13693            return false;
13694        }
13695
13696        if (packageName.equals(mRequiredVerifierPackage)) {
13697            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13698                    + "\": required for package verification");
13699            return false;
13700        }
13701
13702        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13703            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13704                    + "\": is the default dialer");
13705            return false;
13706        }
13707
13708        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13709            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13710                    + "\": protected package");
13711            return false;
13712        }
13713
13714        // Cannot suspend static shared libs as they are considered
13715        // a part of the using app (emulating static linking). Also
13716        // static libs are installed always on internal storage.
13717        PackageParser.Package pkg = mPackages.get(packageName);
13718        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13719            Slog.w(TAG, "Cannot suspend package: " + packageName
13720                    + " providing static shared library: "
13721                    + pkg.staticSharedLibName);
13722            return false;
13723        }
13724
13725        return true;
13726    }
13727
13728    private String getActiveLauncherPackageName(int userId) {
13729        Intent intent = new Intent(Intent.ACTION_MAIN);
13730        intent.addCategory(Intent.CATEGORY_HOME);
13731        ResolveInfo resolveInfo = resolveIntent(
13732                intent,
13733                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13734                PackageManager.MATCH_DEFAULT_ONLY,
13735                userId);
13736
13737        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13738    }
13739
13740    private String getDefaultDialerPackageName(int userId) {
13741        synchronized (mPackages) {
13742            return mSettings.getDefaultDialerPackageNameLPw(userId);
13743        }
13744    }
13745
13746    @Override
13747    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13748        mContext.enforceCallingOrSelfPermission(
13749                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13750                "Only package verification agents can verify applications");
13751
13752        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13753        final PackageVerificationResponse response = new PackageVerificationResponse(
13754                verificationCode, Binder.getCallingUid());
13755        msg.arg1 = id;
13756        msg.obj = response;
13757        mHandler.sendMessage(msg);
13758    }
13759
13760    @Override
13761    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13762            long millisecondsToDelay) {
13763        mContext.enforceCallingOrSelfPermission(
13764                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13765                "Only package verification agents can extend verification timeouts");
13766
13767        final PackageVerificationState state = mPendingVerification.get(id);
13768        final PackageVerificationResponse response = new PackageVerificationResponse(
13769                verificationCodeAtTimeout, Binder.getCallingUid());
13770
13771        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13772            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13773        }
13774        if (millisecondsToDelay < 0) {
13775            millisecondsToDelay = 0;
13776        }
13777        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13778                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13779            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13780        }
13781
13782        if ((state != null) && !state.timeoutExtended()) {
13783            state.extendTimeout();
13784
13785            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13786            msg.arg1 = id;
13787            msg.obj = response;
13788            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13789        }
13790    }
13791
13792    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13793            int verificationCode, UserHandle user) {
13794        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13795        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13796        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13797        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13798        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13799
13800        mContext.sendBroadcastAsUser(intent, user,
13801                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13802    }
13803
13804    private ComponentName matchComponentForVerifier(String packageName,
13805            List<ResolveInfo> receivers) {
13806        ActivityInfo targetReceiver = null;
13807
13808        final int NR = receivers.size();
13809        for (int i = 0; i < NR; i++) {
13810            final ResolveInfo info = receivers.get(i);
13811            if (info.activityInfo == null) {
13812                continue;
13813            }
13814
13815            if (packageName.equals(info.activityInfo.packageName)) {
13816                targetReceiver = info.activityInfo;
13817                break;
13818            }
13819        }
13820
13821        if (targetReceiver == null) {
13822            return null;
13823        }
13824
13825        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13826    }
13827
13828    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13829            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13830        if (pkgInfo.verifiers.length == 0) {
13831            return null;
13832        }
13833
13834        final int N = pkgInfo.verifiers.length;
13835        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13836        for (int i = 0; i < N; i++) {
13837            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13838
13839            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13840                    receivers);
13841            if (comp == null) {
13842                continue;
13843            }
13844
13845            final int verifierUid = getUidForVerifier(verifierInfo);
13846            if (verifierUid == -1) {
13847                continue;
13848            }
13849
13850            if (DEBUG_VERIFY) {
13851                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13852                        + " with the correct signature");
13853            }
13854            sufficientVerifiers.add(comp);
13855            verificationState.addSufficientVerifier(verifierUid);
13856        }
13857
13858        return sufficientVerifiers;
13859    }
13860
13861    private int getUidForVerifier(VerifierInfo verifierInfo) {
13862        synchronized (mPackages) {
13863            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13864            if (pkg == null) {
13865                return -1;
13866            } else if (pkg.mSignatures.length != 1) {
13867                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13868                        + " has more than one signature; ignoring");
13869                return -1;
13870            }
13871
13872            /*
13873             * If the public key of the package's signature does not match
13874             * our expected public key, then this is a different package and
13875             * we should skip.
13876             */
13877
13878            final byte[] expectedPublicKey;
13879            try {
13880                final Signature verifierSig = pkg.mSignatures[0];
13881                final PublicKey publicKey = verifierSig.getPublicKey();
13882                expectedPublicKey = publicKey.getEncoded();
13883            } catch (CertificateException e) {
13884                return -1;
13885            }
13886
13887            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13888
13889            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13890                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13891                        + " does not have the expected public key; ignoring");
13892                return -1;
13893            }
13894
13895            return pkg.applicationInfo.uid;
13896        }
13897    }
13898
13899    @Override
13900    public void finishPackageInstall(int token, boolean didLaunch) {
13901        enforceSystemOrRoot("Only the system is allowed to finish installs");
13902
13903        if (DEBUG_INSTALL) {
13904            Slog.v(TAG, "BM finishing package install for " + token);
13905        }
13906        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13907
13908        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13909        mHandler.sendMessage(msg);
13910    }
13911
13912    /**
13913     * Get the verification agent timeout.  Used for both the APK verifier and the
13914     * intent filter verifier.
13915     *
13916     * @return verification timeout in milliseconds
13917     */
13918    private long getVerificationTimeout() {
13919        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13920                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13921                DEFAULT_VERIFICATION_TIMEOUT);
13922    }
13923
13924    /**
13925     * Get the default verification agent response code.
13926     *
13927     * @return default verification response code
13928     */
13929    private int getDefaultVerificationResponse(UserHandle user) {
13930        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13931            return PackageManager.VERIFICATION_REJECT;
13932        }
13933        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13934                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13935                DEFAULT_VERIFICATION_RESPONSE);
13936    }
13937
13938    /**
13939     * Check whether or not package verification has been enabled.
13940     *
13941     * @return true if verification should be performed
13942     */
13943    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13944        if (!DEFAULT_VERIFY_ENABLE) {
13945            return false;
13946        }
13947
13948        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13949
13950        // Check if installing from ADB
13951        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13952            // Do not run verification in a test harness environment
13953            if (ActivityManager.isRunningInTestHarness()) {
13954                return false;
13955            }
13956            if (ensureVerifyAppsEnabled) {
13957                return true;
13958            }
13959            // Check if the developer does not want package verification for ADB installs
13960            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13961                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13962                return false;
13963            }
13964        } else {
13965            // only when not installed from ADB, skip verification for instant apps when
13966            // the installer and verifier are the same.
13967            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13968                if (mInstantAppInstallerActivity != null
13969                        && mInstantAppInstallerActivity.packageName.equals(
13970                                mRequiredVerifierPackage)) {
13971                    try {
13972                        mContext.getSystemService(AppOpsManager.class)
13973                                .checkPackage(installerUid, mRequiredVerifierPackage);
13974                        if (DEBUG_VERIFY) {
13975                            Slog.i(TAG, "disable verification for instant app");
13976                        }
13977                        return false;
13978                    } catch (SecurityException ignore) { }
13979                }
13980            }
13981        }
13982
13983        if (ensureVerifyAppsEnabled) {
13984            return true;
13985        }
13986
13987        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13988                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13989    }
13990
13991    @Override
13992    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13993            throws RemoteException {
13994        mContext.enforceCallingOrSelfPermission(
13995                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13996                "Only intentfilter verification agents can verify applications");
13997
13998        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13999        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14000                Binder.getCallingUid(), verificationCode, failedDomains);
14001        msg.arg1 = id;
14002        msg.obj = response;
14003        mHandler.sendMessage(msg);
14004    }
14005
14006    @Override
14007    public int getIntentVerificationStatus(String packageName, int userId) {
14008        final int callingUid = Binder.getCallingUid();
14009        if (UserHandle.getUserId(callingUid) != userId) {
14010            mContext.enforceCallingOrSelfPermission(
14011                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14012                    "getIntentVerificationStatus" + userId);
14013        }
14014        if (getInstantAppPackageName(callingUid) != null) {
14015            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14016        }
14017        synchronized (mPackages) {
14018            final PackageSetting ps = mSettings.mPackages.get(packageName);
14019            if (ps == null
14020                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14021                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14022            }
14023            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14024        }
14025    }
14026
14027    @Override
14028    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14029        mContext.enforceCallingOrSelfPermission(
14030                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14031
14032        boolean result = false;
14033        synchronized (mPackages) {
14034            final PackageSetting ps = mSettings.mPackages.get(packageName);
14035            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14036                return false;
14037            }
14038            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14039        }
14040        if (result) {
14041            scheduleWritePackageRestrictionsLocked(userId);
14042        }
14043        return result;
14044    }
14045
14046    @Override
14047    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14048            String packageName) {
14049        final int callingUid = Binder.getCallingUid();
14050        if (getInstantAppPackageName(callingUid) != null) {
14051            return ParceledListSlice.emptyList();
14052        }
14053        synchronized (mPackages) {
14054            final PackageSetting ps = mSettings.mPackages.get(packageName);
14055            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14056                return ParceledListSlice.emptyList();
14057            }
14058            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14059        }
14060    }
14061
14062    @Override
14063    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14064        if (TextUtils.isEmpty(packageName)) {
14065            return ParceledListSlice.emptyList();
14066        }
14067        final int callingUid = Binder.getCallingUid();
14068        final int callingUserId = UserHandle.getUserId(callingUid);
14069        synchronized (mPackages) {
14070            PackageParser.Package pkg = mPackages.get(packageName);
14071            if (pkg == null || pkg.activities == null) {
14072                return ParceledListSlice.emptyList();
14073            }
14074            if (pkg.mExtras == null) {
14075                return ParceledListSlice.emptyList();
14076            }
14077            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14078            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14079                return ParceledListSlice.emptyList();
14080            }
14081            final int count = pkg.activities.size();
14082            ArrayList<IntentFilter> result = new ArrayList<>();
14083            for (int n=0; n<count; n++) {
14084                PackageParser.Activity activity = pkg.activities.get(n);
14085                if (activity.intents != null && activity.intents.size() > 0) {
14086                    result.addAll(activity.intents);
14087                }
14088            }
14089            return new ParceledListSlice<>(result);
14090        }
14091    }
14092
14093    @Override
14094    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14095        mContext.enforceCallingOrSelfPermission(
14096                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14097        if (UserHandle.getCallingUserId() != userId) {
14098            mContext.enforceCallingOrSelfPermission(
14099                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14100        }
14101
14102        synchronized (mPackages) {
14103            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14104            if (packageName != null) {
14105                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14106                        packageName, userId);
14107            }
14108            return result;
14109        }
14110    }
14111
14112    @Override
14113    public String getDefaultBrowserPackageName(int userId) {
14114        if (UserHandle.getCallingUserId() != userId) {
14115            mContext.enforceCallingOrSelfPermission(
14116                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14117        }
14118        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14119            return null;
14120        }
14121        synchronized (mPackages) {
14122            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14123        }
14124    }
14125
14126    /**
14127     * Get the "allow unknown sources" setting.
14128     *
14129     * @return the current "allow unknown sources" setting
14130     */
14131    private int getUnknownSourcesSettings() {
14132        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14133                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14134                -1);
14135    }
14136
14137    @Override
14138    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14139        final int callingUid = Binder.getCallingUid();
14140        if (getInstantAppPackageName(callingUid) != null) {
14141            return;
14142        }
14143        // writer
14144        synchronized (mPackages) {
14145            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14146            if (targetPackageSetting == null
14147                    || filterAppAccessLPr(
14148                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14149                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14150            }
14151
14152            PackageSetting installerPackageSetting;
14153            if (installerPackageName != null) {
14154                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14155                if (installerPackageSetting == null) {
14156                    throw new IllegalArgumentException("Unknown installer package: "
14157                            + installerPackageName);
14158                }
14159            } else {
14160                installerPackageSetting = null;
14161            }
14162
14163            Signature[] callerSignature;
14164            Object obj = mSettings.getUserIdLPr(callingUid);
14165            if (obj != null) {
14166                if (obj instanceof SharedUserSetting) {
14167                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14168                } else if (obj instanceof PackageSetting) {
14169                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14170                } else {
14171                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14172                }
14173            } else {
14174                throw new SecurityException("Unknown calling UID: " + callingUid);
14175            }
14176
14177            // Verify: can't set installerPackageName to a package that is
14178            // not signed with the same cert as the caller.
14179            if (installerPackageSetting != null) {
14180                if (compareSignatures(callerSignature,
14181                        installerPackageSetting.signatures.mSignatures)
14182                        != PackageManager.SIGNATURE_MATCH) {
14183                    throw new SecurityException(
14184                            "Caller does not have same cert as new installer package "
14185                            + installerPackageName);
14186                }
14187            }
14188
14189            // Verify: if target already has an installer package, it must
14190            // be signed with the same cert as the caller.
14191            if (targetPackageSetting.installerPackageName != null) {
14192                PackageSetting setting = mSettings.mPackages.get(
14193                        targetPackageSetting.installerPackageName);
14194                // If the currently set package isn't valid, then it's always
14195                // okay to change it.
14196                if (setting != null) {
14197                    if (compareSignatures(callerSignature,
14198                            setting.signatures.mSignatures)
14199                            != PackageManager.SIGNATURE_MATCH) {
14200                        throw new SecurityException(
14201                                "Caller does not have same cert as old installer package "
14202                                + targetPackageSetting.installerPackageName);
14203                    }
14204                }
14205            }
14206
14207            // Okay!
14208            targetPackageSetting.installerPackageName = installerPackageName;
14209            if (installerPackageName != null) {
14210                mSettings.mInstallerPackages.add(installerPackageName);
14211            }
14212            scheduleWriteSettingsLocked();
14213        }
14214    }
14215
14216    @Override
14217    public void setApplicationCategoryHint(String packageName, int categoryHint,
14218            String callerPackageName) {
14219        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14220            throw new SecurityException("Instant applications don't have access to this method");
14221        }
14222        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14223                callerPackageName);
14224        synchronized (mPackages) {
14225            PackageSetting ps = mSettings.mPackages.get(packageName);
14226            if (ps == null) {
14227                throw new IllegalArgumentException("Unknown target package " + packageName);
14228            }
14229            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14230                throw new IllegalArgumentException("Unknown target package " + packageName);
14231            }
14232            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14233                throw new IllegalArgumentException("Calling package " + callerPackageName
14234                        + " is not installer for " + packageName);
14235            }
14236
14237            if (ps.categoryHint != categoryHint) {
14238                ps.categoryHint = categoryHint;
14239                scheduleWriteSettingsLocked();
14240            }
14241        }
14242    }
14243
14244    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14245        // Queue up an async operation since the package installation may take a little while.
14246        mHandler.post(new Runnable() {
14247            public void run() {
14248                mHandler.removeCallbacks(this);
14249                 // Result object to be returned
14250                PackageInstalledInfo res = new PackageInstalledInfo();
14251                res.setReturnCode(currentStatus);
14252                res.uid = -1;
14253                res.pkg = null;
14254                res.removedInfo = null;
14255                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14256                    args.doPreInstall(res.returnCode);
14257                    synchronized (mInstallLock) {
14258                        installPackageTracedLI(args, res);
14259                    }
14260                    args.doPostInstall(res.returnCode, res.uid);
14261                }
14262
14263                // A restore should be performed at this point if (a) the install
14264                // succeeded, (b) the operation is not an update, and (c) the new
14265                // package has not opted out of backup participation.
14266                final boolean update = res.removedInfo != null
14267                        && res.removedInfo.removedPackage != null;
14268                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14269                boolean doRestore = !update
14270                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14271
14272                // Set up the post-install work request bookkeeping.  This will be used
14273                // and cleaned up by the post-install event handling regardless of whether
14274                // there's a restore pass performed.  Token values are >= 1.
14275                int token;
14276                if (mNextInstallToken < 0) mNextInstallToken = 1;
14277                token = mNextInstallToken++;
14278
14279                PostInstallData data = new PostInstallData(args, res);
14280                mRunningInstalls.put(token, data);
14281                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14282
14283                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14284                    // Pass responsibility to the Backup Manager.  It will perform a
14285                    // restore if appropriate, then pass responsibility back to the
14286                    // Package Manager to run the post-install observer callbacks
14287                    // and broadcasts.
14288                    IBackupManager bm = IBackupManager.Stub.asInterface(
14289                            ServiceManager.getService(Context.BACKUP_SERVICE));
14290                    if (bm != null) {
14291                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14292                                + " to BM for possible restore");
14293                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14294                        try {
14295                            // TODO: http://b/22388012
14296                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14297                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14298                            } else {
14299                                doRestore = false;
14300                            }
14301                        } catch (RemoteException e) {
14302                            // can't happen; the backup manager is local
14303                        } catch (Exception e) {
14304                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14305                            doRestore = false;
14306                        }
14307                    } else {
14308                        Slog.e(TAG, "Backup Manager not found!");
14309                        doRestore = false;
14310                    }
14311                }
14312
14313                if (!doRestore) {
14314                    // No restore possible, or the Backup Manager was mysteriously not
14315                    // available -- just fire the post-install work request directly.
14316                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14317
14318                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14319
14320                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14321                    mHandler.sendMessage(msg);
14322                }
14323            }
14324        });
14325    }
14326
14327    /**
14328     * Callback from PackageSettings whenever an app is first transitioned out of the
14329     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14330     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14331     * here whether the app is the target of an ongoing install, and only send the
14332     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14333     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14334     * handling.
14335     */
14336    void notifyFirstLaunch(final String packageName, final String installerPackage,
14337            final int userId) {
14338        // Serialize this with the rest of the install-process message chain.  In the
14339        // restore-at-install case, this Runnable will necessarily run before the
14340        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14341        // are coherent.  In the non-restore case, the app has already completed install
14342        // and been launched through some other means, so it is not in a problematic
14343        // state for observers to see the FIRST_LAUNCH signal.
14344        mHandler.post(new Runnable() {
14345            @Override
14346            public void run() {
14347                for (int i = 0; i < mRunningInstalls.size(); i++) {
14348                    final PostInstallData data = mRunningInstalls.valueAt(i);
14349                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14350                        continue;
14351                    }
14352                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14353                        // right package; but is it for the right user?
14354                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14355                            if (userId == data.res.newUsers[uIndex]) {
14356                                if (DEBUG_BACKUP) {
14357                                    Slog.i(TAG, "Package " + packageName
14358                                            + " being restored so deferring FIRST_LAUNCH");
14359                                }
14360                                return;
14361                            }
14362                        }
14363                    }
14364                }
14365                // didn't find it, so not being restored
14366                if (DEBUG_BACKUP) {
14367                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14368                }
14369                final boolean isInstantApp = isInstantApp(packageName, userId);
14370                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14371                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14372                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14373            }
14374        });
14375    }
14376
14377    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14378            int[] userIds, int[] instantUserIds) {
14379        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14380                installerPkg, null, userIds, instantUserIds);
14381    }
14382
14383    private abstract class HandlerParams {
14384        private static final int MAX_RETRIES = 4;
14385
14386        /**
14387         * Number of times startCopy() has been attempted and had a non-fatal
14388         * error.
14389         */
14390        private int mRetries = 0;
14391
14392        /** User handle for the user requesting the information or installation. */
14393        private final UserHandle mUser;
14394        String traceMethod;
14395        int traceCookie;
14396
14397        HandlerParams(UserHandle user) {
14398            mUser = user;
14399        }
14400
14401        UserHandle getUser() {
14402            return mUser;
14403        }
14404
14405        HandlerParams setTraceMethod(String traceMethod) {
14406            this.traceMethod = traceMethod;
14407            return this;
14408        }
14409
14410        HandlerParams setTraceCookie(int traceCookie) {
14411            this.traceCookie = traceCookie;
14412            return this;
14413        }
14414
14415        final boolean startCopy() {
14416            boolean res;
14417            try {
14418                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14419
14420                if (++mRetries > MAX_RETRIES) {
14421                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14422                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14423                    handleServiceError();
14424                    return false;
14425                } else {
14426                    handleStartCopy();
14427                    res = true;
14428                }
14429            } catch (RemoteException e) {
14430                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14431                mHandler.sendEmptyMessage(MCS_RECONNECT);
14432                res = false;
14433            }
14434            handleReturnCode();
14435            return res;
14436        }
14437
14438        final void serviceError() {
14439            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14440            handleServiceError();
14441            handleReturnCode();
14442        }
14443
14444        abstract void handleStartCopy() throws RemoteException;
14445        abstract void handleServiceError();
14446        abstract void handleReturnCode();
14447    }
14448
14449    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14450        for (File path : paths) {
14451            try {
14452                mcs.clearDirectory(path.getAbsolutePath());
14453            } catch (RemoteException e) {
14454            }
14455        }
14456    }
14457
14458    static class OriginInfo {
14459        /**
14460         * Location where install is coming from, before it has been
14461         * copied/renamed into place. This could be a single monolithic APK
14462         * file, or a cluster directory. This location may be untrusted.
14463         */
14464        final File file;
14465
14466        /**
14467         * Flag indicating that {@link #file} or {@link #cid} has already been
14468         * staged, meaning downstream users don't need to defensively copy the
14469         * contents.
14470         */
14471        final boolean staged;
14472
14473        /**
14474         * Flag indicating that {@link #file} or {@link #cid} is an already
14475         * installed app that is being moved.
14476         */
14477        final boolean existing;
14478
14479        final String resolvedPath;
14480        final File resolvedFile;
14481
14482        static OriginInfo fromNothing() {
14483            return new OriginInfo(null, false, false);
14484        }
14485
14486        static OriginInfo fromUntrustedFile(File file) {
14487            return new OriginInfo(file, false, false);
14488        }
14489
14490        static OriginInfo fromExistingFile(File file) {
14491            return new OriginInfo(file, false, true);
14492        }
14493
14494        static OriginInfo fromStagedFile(File file) {
14495            return new OriginInfo(file, true, false);
14496        }
14497
14498        private OriginInfo(File file, boolean staged, boolean existing) {
14499            this.file = file;
14500            this.staged = staged;
14501            this.existing = existing;
14502
14503            if (file != null) {
14504                resolvedPath = file.getAbsolutePath();
14505                resolvedFile = file;
14506            } else {
14507                resolvedPath = null;
14508                resolvedFile = null;
14509            }
14510        }
14511    }
14512
14513    static class MoveInfo {
14514        final int moveId;
14515        final String fromUuid;
14516        final String toUuid;
14517        final String packageName;
14518        final String dataAppName;
14519        final int appId;
14520        final String seinfo;
14521        final int targetSdkVersion;
14522
14523        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14524                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14525            this.moveId = moveId;
14526            this.fromUuid = fromUuid;
14527            this.toUuid = toUuid;
14528            this.packageName = packageName;
14529            this.dataAppName = dataAppName;
14530            this.appId = appId;
14531            this.seinfo = seinfo;
14532            this.targetSdkVersion = targetSdkVersion;
14533        }
14534    }
14535
14536    static class VerificationInfo {
14537        /** A constant used to indicate that a uid value is not present. */
14538        public static final int NO_UID = -1;
14539
14540        /** URI referencing where the package was downloaded from. */
14541        final Uri originatingUri;
14542
14543        /** HTTP referrer URI associated with the originatingURI. */
14544        final Uri referrer;
14545
14546        /** UID of the application that the install request originated from. */
14547        final int originatingUid;
14548
14549        /** UID of application requesting the install */
14550        final int installerUid;
14551
14552        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14553            this.originatingUri = originatingUri;
14554            this.referrer = referrer;
14555            this.originatingUid = originatingUid;
14556            this.installerUid = installerUid;
14557        }
14558    }
14559
14560    class InstallParams extends HandlerParams {
14561        final OriginInfo origin;
14562        final MoveInfo move;
14563        final IPackageInstallObserver2 observer;
14564        int installFlags;
14565        final String installerPackageName;
14566        final String volumeUuid;
14567        private InstallArgs mArgs;
14568        private int mRet;
14569        final String packageAbiOverride;
14570        final String[] grantedRuntimePermissions;
14571        final VerificationInfo verificationInfo;
14572        final Certificate[][] certificates;
14573        final int installReason;
14574
14575        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14576                int installFlags, String installerPackageName, String volumeUuid,
14577                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14578                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14579            super(user);
14580            this.origin = origin;
14581            this.move = move;
14582            this.observer = observer;
14583            this.installFlags = installFlags;
14584            this.installerPackageName = installerPackageName;
14585            this.volumeUuid = volumeUuid;
14586            this.verificationInfo = verificationInfo;
14587            this.packageAbiOverride = packageAbiOverride;
14588            this.grantedRuntimePermissions = grantedPermissions;
14589            this.certificates = certificates;
14590            this.installReason = installReason;
14591        }
14592
14593        @Override
14594        public String toString() {
14595            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14596                    + " file=" + origin.file + "}";
14597        }
14598
14599        private int installLocationPolicy(PackageInfoLite pkgLite) {
14600            String packageName = pkgLite.packageName;
14601            int installLocation = pkgLite.installLocation;
14602            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14603            // reader
14604            synchronized (mPackages) {
14605                // Currently installed package which the new package is attempting to replace or
14606                // null if no such package is installed.
14607                PackageParser.Package installedPkg = mPackages.get(packageName);
14608                // Package which currently owns the data which the new package will own if installed.
14609                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14610                // will be null whereas dataOwnerPkg will contain information about the package
14611                // which was uninstalled while keeping its data.
14612                PackageParser.Package dataOwnerPkg = installedPkg;
14613                if (dataOwnerPkg  == null) {
14614                    PackageSetting ps = mSettings.mPackages.get(packageName);
14615                    if (ps != null) {
14616                        dataOwnerPkg = ps.pkg;
14617                    }
14618                }
14619
14620                if (dataOwnerPkg != null) {
14621                    // If installed, the package will get access to data left on the device by its
14622                    // predecessor. As a security measure, this is permited only if this is not a
14623                    // version downgrade or if the predecessor package is marked as debuggable and
14624                    // a downgrade is explicitly requested.
14625                    //
14626                    // On debuggable platform builds, downgrades are permitted even for
14627                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14628                    // not offer security guarantees and thus it's OK to disable some security
14629                    // mechanisms to make debugging/testing easier on those builds. However, even on
14630                    // debuggable builds downgrades of packages are permitted only if requested via
14631                    // installFlags. This is because we aim to keep the behavior of debuggable
14632                    // platform builds as close as possible to the behavior of non-debuggable
14633                    // platform builds.
14634                    final boolean downgradeRequested =
14635                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14636                    final boolean packageDebuggable =
14637                                (dataOwnerPkg.applicationInfo.flags
14638                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14639                    final boolean downgradePermitted =
14640                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14641                    if (!downgradePermitted) {
14642                        try {
14643                            checkDowngrade(dataOwnerPkg, pkgLite);
14644                        } catch (PackageManagerException e) {
14645                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14646                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14647                        }
14648                    }
14649                }
14650
14651                if (installedPkg != null) {
14652                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14653                        // Check for updated system application.
14654                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14655                            if (onSd) {
14656                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14657                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14658                            }
14659                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14660                        } else {
14661                            if (onSd) {
14662                                // Install flag overrides everything.
14663                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14664                            }
14665                            // If current upgrade specifies particular preference
14666                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14667                                // Application explicitly specified internal.
14668                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14669                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14670                                // App explictly prefers external. Let policy decide
14671                            } else {
14672                                // Prefer previous location
14673                                if (isExternal(installedPkg)) {
14674                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14675                                }
14676                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14677                            }
14678                        }
14679                    } else {
14680                        // Invalid install. Return error code
14681                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14682                    }
14683                }
14684            }
14685            // All the special cases have been taken care of.
14686            // Return result based on recommended install location.
14687            if (onSd) {
14688                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14689            }
14690            return pkgLite.recommendedInstallLocation;
14691        }
14692
14693        /*
14694         * Invoke remote method to get package information and install
14695         * location values. Override install location based on default
14696         * policy if needed and then create install arguments based
14697         * on the install location.
14698         */
14699        public void handleStartCopy() throws RemoteException {
14700            int ret = PackageManager.INSTALL_SUCCEEDED;
14701
14702            // If we're already staged, we've firmly committed to an install location
14703            if (origin.staged) {
14704                if (origin.file != null) {
14705                    installFlags |= PackageManager.INSTALL_INTERNAL;
14706                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14707                } else {
14708                    throw new IllegalStateException("Invalid stage location");
14709                }
14710            }
14711
14712            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14713            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14714            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14715            PackageInfoLite pkgLite = null;
14716
14717            if (onInt && onSd) {
14718                // Check if both bits are set.
14719                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14720                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14721            } else if (onSd && ephemeral) {
14722                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14723                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14724            } else {
14725                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14726                        packageAbiOverride);
14727
14728                if (DEBUG_EPHEMERAL && ephemeral) {
14729                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14730                }
14731
14732                /*
14733                 * If we have too little free space, try to free cache
14734                 * before giving up.
14735                 */
14736                if (!origin.staged && pkgLite.recommendedInstallLocation
14737                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14738                    // TODO: focus freeing disk space on the target device
14739                    final StorageManager storage = StorageManager.from(mContext);
14740                    final long lowThreshold = storage.getStorageLowBytes(
14741                            Environment.getDataDirectory());
14742
14743                    final long sizeBytes = mContainerService.calculateInstalledSize(
14744                            origin.resolvedPath, packageAbiOverride);
14745
14746                    try {
14747                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14748                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14749                                installFlags, packageAbiOverride);
14750                    } catch (InstallerException e) {
14751                        Slog.w(TAG, "Failed to free cache", e);
14752                    }
14753
14754                    /*
14755                     * The cache free must have deleted the file we
14756                     * downloaded to install.
14757                     *
14758                     * TODO: fix the "freeCache" call to not delete
14759                     *       the file we care about.
14760                     */
14761                    if (pkgLite.recommendedInstallLocation
14762                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14763                        pkgLite.recommendedInstallLocation
14764                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14765                    }
14766                }
14767            }
14768
14769            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14770                int loc = pkgLite.recommendedInstallLocation;
14771                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14772                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14773                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14774                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14775                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14776                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14777                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14778                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14779                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14780                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14781                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14782                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14783                } else {
14784                    // Override with defaults if needed.
14785                    loc = installLocationPolicy(pkgLite);
14786                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14787                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14788                    } else if (!onSd && !onInt) {
14789                        // Override install location with flags
14790                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14791                            // Set the flag to install on external media.
14792                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14793                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14794                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14795                            if (DEBUG_EPHEMERAL) {
14796                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14797                            }
14798                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14799                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14800                                    |PackageManager.INSTALL_INTERNAL);
14801                        } else {
14802                            // Make sure the flag for installing on external
14803                            // media is unset
14804                            installFlags |= PackageManager.INSTALL_INTERNAL;
14805                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14806                        }
14807                    }
14808                }
14809            }
14810
14811            final InstallArgs args = createInstallArgs(this);
14812            mArgs = args;
14813
14814            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14815                // TODO: http://b/22976637
14816                // Apps installed for "all" users use the device owner to verify the app
14817                UserHandle verifierUser = getUser();
14818                if (verifierUser == UserHandle.ALL) {
14819                    verifierUser = UserHandle.SYSTEM;
14820                }
14821
14822                /*
14823                 * Determine if we have any installed package verifiers. If we
14824                 * do, then we'll defer to them to verify the packages.
14825                 */
14826                final int requiredUid = mRequiredVerifierPackage == null ? -1
14827                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14828                                verifierUser.getIdentifier());
14829                final int installerUid =
14830                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14831                if (!origin.existing && requiredUid != -1
14832                        && isVerificationEnabled(
14833                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14834                    final Intent verification = new Intent(
14835                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14836                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14837                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14838                            PACKAGE_MIME_TYPE);
14839                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14840
14841                    // Query all live verifiers based on current user state
14842                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14843                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14844                            false /*allowDynamicSplits*/);
14845
14846                    if (DEBUG_VERIFY) {
14847                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14848                                + verification.toString() + " with " + pkgLite.verifiers.length
14849                                + " optional verifiers");
14850                    }
14851
14852                    final int verificationId = mPendingVerificationToken++;
14853
14854                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14855
14856                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14857                            installerPackageName);
14858
14859                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14860                            installFlags);
14861
14862                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14863                            pkgLite.packageName);
14864
14865                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14866                            pkgLite.versionCode);
14867
14868                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
14869                            pkgLite.getLongVersionCode());
14870
14871                    if (verificationInfo != null) {
14872                        if (verificationInfo.originatingUri != null) {
14873                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14874                                    verificationInfo.originatingUri);
14875                        }
14876                        if (verificationInfo.referrer != null) {
14877                            verification.putExtra(Intent.EXTRA_REFERRER,
14878                                    verificationInfo.referrer);
14879                        }
14880                        if (verificationInfo.originatingUid >= 0) {
14881                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14882                                    verificationInfo.originatingUid);
14883                        }
14884                        if (verificationInfo.installerUid >= 0) {
14885                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14886                                    verificationInfo.installerUid);
14887                        }
14888                    }
14889
14890                    final PackageVerificationState verificationState = new PackageVerificationState(
14891                            requiredUid, args);
14892
14893                    mPendingVerification.append(verificationId, verificationState);
14894
14895                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14896                            receivers, verificationState);
14897
14898                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14899                    final long idleDuration = getVerificationTimeout();
14900
14901                    /*
14902                     * If any sufficient verifiers were listed in the package
14903                     * manifest, attempt to ask them.
14904                     */
14905                    if (sufficientVerifiers != null) {
14906                        final int N = sufficientVerifiers.size();
14907                        if (N == 0) {
14908                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14909                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14910                        } else {
14911                            for (int i = 0; i < N; i++) {
14912                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14913                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14914                                        verifierComponent.getPackageName(), idleDuration,
14915                                        verifierUser.getIdentifier(), false, "package verifier");
14916
14917                                final Intent sufficientIntent = new Intent(verification);
14918                                sufficientIntent.setComponent(verifierComponent);
14919                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14920                            }
14921                        }
14922                    }
14923
14924                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14925                            mRequiredVerifierPackage, receivers);
14926                    if (ret == PackageManager.INSTALL_SUCCEEDED
14927                            && mRequiredVerifierPackage != null) {
14928                        Trace.asyncTraceBegin(
14929                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14930                        /*
14931                         * Send the intent to the required verification agent,
14932                         * but only start the verification timeout after the
14933                         * target BroadcastReceivers have run.
14934                         */
14935                        verification.setComponent(requiredVerifierComponent);
14936                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14937                                mRequiredVerifierPackage, idleDuration,
14938                                verifierUser.getIdentifier(), false, "package verifier");
14939                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14940                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14941                                new BroadcastReceiver() {
14942                                    @Override
14943                                    public void onReceive(Context context, Intent intent) {
14944                                        final Message msg = mHandler
14945                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14946                                        msg.arg1 = verificationId;
14947                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14948                                    }
14949                                }, null, 0, null, null);
14950
14951                        /*
14952                         * We don't want the copy to proceed until verification
14953                         * succeeds, so null out this field.
14954                         */
14955                        mArgs = null;
14956                    }
14957                } else {
14958                    /*
14959                     * No package verification is enabled, so immediately start
14960                     * the remote call to initiate copy using temporary file.
14961                     */
14962                    ret = args.copyApk(mContainerService, true);
14963                }
14964            }
14965
14966            mRet = ret;
14967        }
14968
14969        @Override
14970        void handleReturnCode() {
14971            // If mArgs is null, then MCS couldn't be reached. When it
14972            // reconnects, it will try again to install. At that point, this
14973            // will succeed.
14974            if (mArgs != null) {
14975                processPendingInstall(mArgs, mRet);
14976            }
14977        }
14978
14979        @Override
14980        void handleServiceError() {
14981            mArgs = createInstallArgs(this);
14982            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14983        }
14984    }
14985
14986    private InstallArgs createInstallArgs(InstallParams params) {
14987        if (params.move != null) {
14988            return new MoveInstallArgs(params);
14989        } else {
14990            return new FileInstallArgs(params);
14991        }
14992    }
14993
14994    /**
14995     * Create args that describe an existing installed package. Typically used
14996     * when cleaning up old installs, or used as a move source.
14997     */
14998    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14999            String resourcePath, String[] instructionSets) {
15000        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15001    }
15002
15003    static abstract class InstallArgs {
15004        /** @see InstallParams#origin */
15005        final OriginInfo origin;
15006        /** @see InstallParams#move */
15007        final MoveInfo move;
15008
15009        final IPackageInstallObserver2 observer;
15010        // Always refers to PackageManager flags only
15011        final int installFlags;
15012        final String installerPackageName;
15013        final String volumeUuid;
15014        final UserHandle user;
15015        final String abiOverride;
15016        final String[] installGrantPermissions;
15017        /** If non-null, drop an async trace when the install completes */
15018        final String traceMethod;
15019        final int traceCookie;
15020        final Certificate[][] certificates;
15021        final int installReason;
15022
15023        // The list of instruction sets supported by this app. This is currently
15024        // only used during the rmdex() phase to clean up resources. We can get rid of this
15025        // if we move dex files under the common app path.
15026        /* nullable */ String[] instructionSets;
15027
15028        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15029                int installFlags, String installerPackageName, String volumeUuid,
15030                UserHandle user, String[] instructionSets,
15031                String abiOverride, String[] installGrantPermissions,
15032                String traceMethod, int traceCookie, Certificate[][] certificates,
15033                int installReason) {
15034            this.origin = origin;
15035            this.move = move;
15036            this.installFlags = installFlags;
15037            this.observer = observer;
15038            this.installerPackageName = installerPackageName;
15039            this.volumeUuid = volumeUuid;
15040            this.user = user;
15041            this.instructionSets = instructionSets;
15042            this.abiOverride = abiOverride;
15043            this.installGrantPermissions = installGrantPermissions;
15044            this.traceMethod = traceMethod;
15045            this.traceCookie = traceCookie;
15046            this.certificates = certificates;
15047            this.installReason = installReason;
15048        }
15049
15050        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15051        abstract int doPreInstall(int status);
15052
15053        /**
15054         * Rename package into final resting place. All paths on the given
15055         * scanned package should be updated to reflect the rename.
15056         */
15057        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15058        abstract int doPostInstall(int status, int uid);
15059
15060        /** @see PackageSettingBase#codePathString */
15061        abstract String getCodePath();
15062        /** @see PackageSettingBase#resourcePathString */
15063        abstract String getResourcePath();
15064
15065        // Need installer lock especially for dex file removal.
15066        abstract void cleanUpResourcesLI();
15067        abstract boolean doPostDeleteLI(boolean delete);
15068
15069        /**
15070         * Called before the source arguments are copied. This is used mostly
15071         * for MoveParams when it needs to read the source file to put it in the
15072         * destination.
15073         */
15074        int doPreCopy() {
15075            return PackageManager.INSTALL_SUCCEEDED;
15076        }
15077
15078        /**
15079         * Called after the source arguments are copied. This is used mostly for
15080         * MoveParams when it needs to read the source file to put it in the
15081         * destination.
15082         */
15083        int doPostCopy(int uid) {
15084            return PackageManager.INSTALL_SUCCEEDED;
15085        }
15086
15087        protected boolean isFwdLocked() {
15088            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15089        }
15090
15091        protected boolean isExternalAsec() {
15092            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15093        }
15094
15095        protected boolean isEphemeral() {
15096            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15097        }
15098
15099        UserHandle getUser() {
15100            return user;
15101        }
15102    }
15103
15104    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15105        if (!allCodePaths.isEmpty()) {
15106            if (instructionSets == null) {
15107                throw new IllegalStateException("instructionSet == null");
15108            }
15109            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15110            for (String codePath : allCodePaths) {
15111                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15112                    try {
15113                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15114                    } catch (InstallerException ignored) {
15115                    }
15116                }
15117            }
15118        }
15119    }
15120
15121    /**
15122     * Logic to handle installation of non-ASEC applications, including copying
15123     * and renaming logic.
15124     */
15125    class FileInstallArgs extends InstallArgs {
15126        private File codeFile;
15127        private File resourceFile;
15128
15129        // Example topology:
15130        // /data/app/com.example/base.apk
15131        // /data/app/com.example/split_foo.apk
15132        // /data/app/com.example/lib/arm/libfoo.so
15133        // /data/app/com.example/lib/arm64/libfoo.so
15134        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15135
15136        /** New install */
15137        FileInstallArgs(InstallParams params) {
15138            super(params.origin, params.move, params.observer, params.installFlags,
15139                    params.installerPackageName, params.volumeUuid,
15140                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15141                    params.grantedRuntimePermissions,
15142                    params.traceMethod, params.traceCookie, params.certificates,
15143                    params.installReason);
15144            if (isFwdLocked()) {
15145                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15146            }
15147        }
15148
15149        /** Existing install */
15150        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15151            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15152                    null, null, null, 0, null /*certificates*/,
15153                    PackageManager.INSTALL_REASON_UNKNOWN);
15154            this.codeFile = (codePath != null) ? new File(codePath) : null;
15155            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15156        }
15157
15158        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15159            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15160            try {
15161                return doCopyApk(imcs, temp);
15162            } finally {
15163                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15164            }
15165        }
15166
15167        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15168            if (origin.staged) {
15169                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15170                codeFile = origin.file;
15171                resourceFile = origin.file;
15172                return PackageManager.INSTALL_SUCCEEDED;
15173            }
15174
15175            try {
15176                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15177                final File tempDir =
15178                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15179                codeFile = tempDir;
15180                resourceFile = tempDir;
15181            } catch (IOException e) {
15182                Slog.w(TAG, "Failed to create copy file: " + e);
15183                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15184            }
15185
15186            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15187                @Override
15188                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15189                    if (!FileUtils.isValidExtFilename(name)) {
15190                        throw new IllegalArgumentException("Invalid filename: " + name);
15191                    }
15192                    try {
15193                        final File file = new File(codeFile, name);
15194                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15195                                O_RDWR | O_CREAT, 0644);
15196                        Os.chmod(file.getAbsolutePath(), 0644);
15197                        return new ParcelFileDescriptor(fd);
15198                    } catch (ErrnoException e) {
15199                        throw new RemoteException("Failed to open: " + e.getMessage());
15200                    }
15201                }
15202            };
15203
15204            int ret = PackageManager.INSTALL_SUCCEEDED;
15205            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15206            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15207                Slog.e(TAG, "Failed to copy package");
15208                return ret;
15209            }
15210
15211            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15212            NativeLibraryHelper.Handle handle = null;
15213            try {
15214                handle = NativeLibraryHelper.Handle.create(codeFile);
15215                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15216                        abiOverride);
15217            } catch (IOException e) {
15218                Slog.e(TAG, "Copying native libraries failed", e);
15219                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15220            } finally {
15221                IoUtils.closeQuietly(handle);
15222            }
15223
15224            return ret;
15225        }
15226
15227        int doPreInstall(int status) {
15228            if (status != PackageManager.INSTALL_SUCCEEDED) {
15229                cleanUp();
15230            }
15231            return status;
15232        }
15233
15234        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15235            if (status != PackageManager.INSTALL_SUCCEEDED) {
15236                cleanUp();
15237                return false;
15238            }
15239
15240            final File targetDir = codeFile.getParentFile();
15241            final File beforeCodeFile = codeFile;
15242            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15243
15244            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15245            try {
15246                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15247            } catch (ErrnoException e) {
15248                Slog.w(TAG, "Failed to rename", e);
15249                return false;
15250            }
15251
15252            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15253                Slog.w(TAG, "Failed to restorecon");
15254                return false;
15255            }
15256
15257            // Reflect the rename internally
15258            codeFile = afterCodeFile;
15259            resourceFile = afterCodeFile;
15260
15261            // Reflect the rename in scanned details
15262            try {
15263                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15264            } catch (IOException e) {
15265                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15266                return false;
15267            }
15268            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15269                    afterCodeFile, pkg.baseCodePath));
15270            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15271                    afterCodeFile, pkg.splitCodePaths));
15272
15273            // Reflect the rename in app info
15274            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15275            pkg.setApplicationInfoCodePath(pkg.codePath);
15276            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15277            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15278            pkg.setApplicationInfoResourcePath(pkg.codePath);
15279            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15280            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15281
15282            return true;
15283        }
15284
15285        int doPostInstall(int status, int uid) {
15286            if (status != PackageManager.INSTALL_SUCCEEDED) {
15287                cleanUp();
15288            }
15289            return status;
15290        }
15291
15292        @Override
15293        String getCodePath() {
15294            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15295        }
15296
15297        @Override
15298        String getResourcePath() {
15299            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15300        }
15301
15302        private boolean cleanUp() {
15303            if (codeFile == null || !codeFile.exists()) {
15304                return false;
15305            }
15306
15307            removeCodePathLI(codeFile);
15308
15309            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15310                resourceFile.delete();
15311            }
15312
15313            return true;
15314        }
15315
15316        void cleanUpResourcesLI() {
15317            // Try enumerating all code paths before deleting
15318            List<String> allCodePaths = Collections.EMPTY_LIST;
15319            if (codeFile != null && codeFile.exists()) {
15320                try {
15321                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15322                    allCodePaths = pkg.getAllCodePaths();
15323                } catch (PackageParserException e) {
15324                    // Ignored; we tried our best
15325                }
15326            }
15327
15328            cleanUp();
15329            removeDexFiles(allCodePaths, instructionSets);
15330        }
15331
15332        boolean doPostDeleteLI(boolean delete) {
15333            // XXX err, shouldn't we respect the delete flag?
15334            cleanUpResourcesLI();
15335            return true;
15336        }
15337    }
15338
15339    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15340            PackageManagerException {
15341        if (copyRet < 0) {
15342            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15343                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15344                throw new PackageManagerException(copyRet, message);
15345            }
15346        }
15347    }
15348
15349    /**
15350     * Extract the StorageManagerService "container ID" from the full code path of an
15351     * .apk.
15352     */
15353    static String cidFromCodePath(String fullCodePath) {
15354        int eidx = fullCodePath.lastIndexOf("/");
15355        String subStr1 = fullCodePath.substring(0, eidx);
15356        int sidx = subStr1.lastIndexOf("/");
15357        return subStr1.substring(sidx+1, eidx);
15358    }
15359
15360    /**
15361     * Logic to handle movement of existing installed applications.
15362     */
15363    class MoveInstallArgs extends InstallArgs {
15364        private File codeFile;
15365        private File resourceFile;
15366
15367        /** New install */
15368        MoveInstallArgs(InstallParams params) {
15369            super(params.origin, params.move, params.observer, params.installFlags,
15370                    params.installerPackageName, params.volumeUuid,
15371                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15372                    params.grantedRuntimePermissions,
15373                    params.traceMethod, params.traceCookie, params.certificates,
15374                    params.installReason);
15375        }
15376
15377        int copyApk(IMediaContainerService imcs, boolean temp) {
15378            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15379                    + move.fromUuid + " to " + move.toUuid);
15380            synchronized (mInstaller) {
15381                try {
15382                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15383                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15384                } catch (InstallerException e) {
15385                    Slog.w(TAG, "Failed to move app", e);
15386                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15387                }
15388            }
15389
15390            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15391            resourceFile = codeFile;
15392            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15393
15394            return PackageManager.INSTALL_SUCCEEDED;
15395        }
15396
15397        int doPreInstall(int status) {
15398            if (status != PackageManager.INSTALL_SUCCEEDED) {
15399                cleanUp(move.toUuid);
15400            }
15401            return status;
15402        }
15403
15404        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15405            if (status != PackageManager.INSTALL_SUCCEEDED) {
15406                cleanUp(move.toUuid);
15407                return false;
15408            }
15409
15410            // Reflect the move in app info
15411            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15412            pkg.setApplicationInfoCodePath(pkg.codePath);
15413            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15414            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15415            pkg.setApplicationInfoResourcePath(pkg.codePath);
15416            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15417            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15418
15419            return true;
15420        }
15421
15422        int doPostInstall(int status, int uid) {
15423            if (status == PackageManager.INSTALL_SUCCEEDED) {
15424                cleanUp(move.fromUuid);
15425            } else {
15426                cleanUp(move.toUuid);
15427            }
15428            return status;
15429        }
15430
15431        @Override
15432        String getCodePath() {
15433            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15434        }
15435
15436        @Override
15437        String getResourcePath() {
15438            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15439        }
15440
15441        private boolean cleanUp(String volumeUuid) {
15442            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15443                    move.dataAppName);
15444            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15445            final int[] userIds = sUserManager.getUserIds();
15446            synchronized (mInstallLock) {
15447                // Clean up both app data and code
15448                // All package moves are frozen until finished
15449                for (int userId : userIds) {
15450                    try {
15451                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15452                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15453                    } catch (InstallerException e) {
15454                        Slog.w(TAG, String.valueOf(e));
15455                    }
15456                }
15457                removeCodePathLI(codeFile);
15458            }
15459            return true;
15460        }
15461
15462        void cleanUpResourcesLI() {
15463            throw new UnsupportedOperationException();
15464        }
15465
15466        boolean doPostDeleteLI(boolean delete) {
15467            throw new UnsupportedOperationException();
15468        }
15469    }
15470
15471    static String getAsecPackageName(String packageCid) {
15472        int idx = packageCid.lastIndexOf("-");
15473        if (idx == -1) {
15474            return packageCid;
15475        }
15476        return packageCid.substring(0, idx);
15477    }
15478
15479    // Utility method used to create code paths based on package name and available index.
15480    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15481        String idxStr = "";
15482        int idx = 1;
15483        // Fall back to default value of idx=1 if prefix is not
15484        // part of oldCodePath
15485        if (oldCodePath != null) {
15486            String subStr = oldCodePath;
15487            // Drop the suffix right away
15488            if (suffix != null && subStr.endsWith(suffix)) {
15489                subStr = subStr.substring(0, subStr.length() - suffix.length());
15490            }
15491            // If oldCodePath already contains prefix find out the
15492            // ending index to either increment or decrement.
15493            int sidx = subStr.lastIndexOf(prefix);
15494            if (sidx != -1) {
15495                subStr = subStr.substring(sidx + prefix.length());
15496                if (subStr != null) {
15497                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15498                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15499                    }
15500                    try {
15501                        idx = Integer.parseInt(subStr);
15502                        if (idx <= 1) {
15503                            idx++;
15504                        } else {
15505                            idx--;
15506                        }
15507                    } catch(NumberFormatException e) {
15508                    }
15509                }
15510            }
15511        }
15512        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15513        return prefix + idxStr;
15514    }
15515
15516    private File getNextCodePath(File targetDir, String packageName) {
15517        File result;
15518        SecureRandom random = new SecureRandom();
15519        byte[] bytes = new byte[16];
15520        do {
15521            random.nextBytes(bytes);
15522            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15523            result = new File(targetDir, packageName + "-" + suffix);
15524        } while (result.exists());
15525        return result;
15526    }
15527
15528    // Utility method that returns the relative package path with respect
15529    // to the installation directory. Like say for /data/data/com.test-1.apk
15530    // string com.test-1 is returned.
15531    static String deriveCodePathName(String codePath) {
15532        if (codePath == null) {
15533            return null;
15534        }
15535        final File codeFile = new File(codePath);
15536        final String name = codeFile.getName();
15537        if (codeFile.isDirectory()) {
15538            return name;
15539        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15540            final int lastDot = name.lastIndexOf('.');
15541            return name.substring(0, lastDot);
15542        } else {
15543            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15544            return null;
15545        }
15546    }
15547
15548    static class PackageInstalledInfo {
15549        String name;
15550        int uid;
15551        // The set of users that originally had this package installed.
15552        int[] origUsers;
15553        // The set of users that now have this package installed.
15554        int[] newUsers;
15555        PackageParser.Package pkg;
15556        int returnCode;
15557        String returnMsg;
15558        String installerPackageName;
15559        PackageRemovedInfo removedInfo;
15560        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15561
15562        public void setError(int code, String msg) {
15563            setReturnCode(code);
15564            setReturnMessage(msg);
15565            Slog.w(TAG, msg);
15566        }
15567
15568        public void setError(String msg, PackageParserException e) {
15569            setReturnCode(e.error);
15570            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15571            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15572            for (int i = 0; i < childCount; i++) {
15573                addedChildPackages.valueAt(i).setError(msg, e);
15574            }
15575            Slog.w(TAG, msg, e);
15576        }
15577
15578        public void setError(String msg, PackageManagerException e) {
15579            returnCode = e.error;
15580            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15581            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15582            for (int i = 0; i < childCount; i++) {
15583                addedChildPackages.valueAt(i).setError(msg, e);
15584            }
15585            Slog.w(TAG, msg, e);
15586        }
15587
15588        public void setReturnCode(int returnCode) {
15589            this.returnCode = returnCode;
15590            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15591            for (int i = 0; i < childCount; i++) {
15592                addedChildPackages.valueAt(i).returnCode = returnCode;
15593            }
15594        }
15595
15596        private void setReturnMessage(String returnMsg) {
15597            this.returnMsg = returnMsg;
15598            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15599            for (int i = 0; i < childCount; i++) {
15600                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15601            }
15602        }
15603
15604        // In some error cases we want to convey more info back to the observer
15605        String origPackage;
15606        String origPermission;
15607    }
15608
15609    /*
15610     * Install a non-existing package.
15611     */
15612    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15613            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15614            String volumeUuid, PackageInstalledInfo res, int installReason) {
15615        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15616
15617        // Remember this for later, in case we need to rollback this install
15618        String pkgName = pkg.packageName;
15619
15620        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15621
15622        synchronized(mPackages) {
15623            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15624            if (renamedPackage != null) {
15625                // A package with the same name is already installed, though
15626                // it has been renamed to an older name.  The package we
15627                // are trying to install should be installed as an update to
15628                // the existing one, but that has not been requested, so bail.
15629                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15630                        + " without first uninstalling package running as "
15631                        + renamedPackage);
15632                return;
15633            }
15634            if (mPackages.containsKey(pkgName)) {
15635                // Don't allow installation over an existing package with the same name.
15636                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15637                        + " without first uninstalling.");
15638                return;
15639            }
15640        }
15641
15642        try {
15643            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15644                    System.currentTimeMillis(), user);
15645
15646            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15647
15648            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15649                prepareAppDataAfterInstallLIF(newPackage);
15650
15651            } else {
15652                // Remove package from internal structures, but keep around any
15653                // data that might have already existed
15654                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15655                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15656            }
15657        } catch (PackageManagerException e) {
15658            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15659        }
15660
15661        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15662    }
15663
15664    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15665        try (DigestInputStream digestStream =
15666                new DigestInputStream(new FileInputStream(file), digest)) {
15667            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15668        }
15669    }
15670
15671    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15672            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15673            PackageInstalledInfo res, int installReason) {
15674        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15675
15676        final PackageParser.Package oldPackage;
15677        final PackageSetting ps;
15678        final String pkgName = pkg.packageName;
15679        final int[] allUsers;
15680        final int[] installedUsers;
15681
15682        synchronized(mPackages) {
15683            oldPackage = mPackages.get(pkgName);
15684            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15685
15686            // don't allow upgrade to target a release SDK from a pre-release SDK
15687            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15688                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15689            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15690                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15691            if (oldTargetsPreRelease
15692                    && !newTargetsPreRelease
15693                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15694                Slog.w(TAG, "Can't install package targeting released sdk");
15695                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15696                return;
15697            }
15698
15699            ps = mSettings.mPackages.get(pkgName);
15700
15701            // verify signatures are valid
15702            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15703            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15704                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15705                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15706                            "New package not signed by keys specified by upgrade-keysets: "
15707                                    + pkgName);
15708                    return;
15709                }
15710            } else {
15711                // default to original signature matching
15712                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15713                        != PackageManager.SIGNATURE_MATCH) {
15714                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15715                            "New package has a different signature: " + pkgName);
15716                    return;
15717                }
15718            }
15719
15720            // don't allow a system upgrade unless the upgrade hash matches
15721            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15722                byte[] digestBytes = null;
15723                try {
15724                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15725                    updateDigest(digest, new File(pkg.baseCodePath));
15726                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15727                        for (String path : pkg.splitCodePaths) {
15728                            updateDigest(digest, new File(path));
15729                        }
15730                    }
15731                    digestBytes = digest.digest();
15732                } catch (NoSuchAlgorithmException | IOException e) {
15733                    res.setError(INSTALL_FAILED_INVALID_APK,
15734                            "Could not compute hash: " + pkgName);
15735                    return;
15736                }
15737                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15738                    res.setError(INSTALL_FAILED_INVALID_APK,
15739                            "New package fails restrict-update check: " + pkgName);
15740                    return;
15741                }
15742                // retain upgrade restriction
15743                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15744            }
15745
15746            // Check for shared user id changes
15747            String invalidPackageName =
15748                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15749            if (invalidPackageName != null) {
15750                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15751                        "Package " + invalidPackageName + " tried to change user "
15752                                + oldPackage.mSharedUserId);
15753                return;
15754            }
15755
15756            // check if the new package supports all of the abis which the old package supports
15757            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
15758            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
15759            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
15760                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15761                        "Update to package " + pkgName + " doesn't support multi arch");
15762                return;
15763            }
15764
15765            // In case of rollback, remember per-user/profile install state
15766            allUsers = sUserManager.getUserIds();
15767            installedUsers = ps.queryInstalledUsers(allUsers, true);
15768
15769            // don't allow an upgrade from full to ephemeral
15770            if (isInstantApp) {
15771                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15772                    for (int currentUser : allUsers) {
15773                        if (!ps.getInstantApp(currentUser)) {
15774                            // can't downgrade from full to instant
15775                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15776                                    + " for user: " + currentUser);
15777                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15778                            return;
15779                        }
15780                    }
15781                } else if (!ps.getInstantApp(user.getIdentifier())) {
15782                    // can't downgrade from full to instant
15783                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15784                            + " for user: " + user.getIdentifier());
15785                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15786                    return;
15787                }
15788            }
15789        }
15790
15791        // Update what is removed
15792        res.removedInfo = new PackageRemovedInfo(this);
15793        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15794        res.removedInfo.removedPackage = oldPackage.packageName;
15795        res.removedInfo.installerPackageName = ps.installerPackageName;
15796        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15797        res.removedInfo.isUpdate = true;
15798        res.removedInfo.origUsers = installedUsers;
15799        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15800        for (int i = 0; i < installedUsers.length; i++) {
15801            final int userId = installedUsers[i];
15802            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15803        }
15804
15805        final int childCount = (oldPackage.childPackages != null)
15806                ? oldPackage.childPackages.size() : 0;
15807        for (int i = 0; i < childCount; i++) {
15808            boolean childPackageUpdated = false;
15809            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15810            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15811            if (res.addedChildPackages != null) {
15812                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15813                if (childRes != null) {
15814                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15815                    childRes.removedInfo.removedPackage = childPkg.packageName;
15816                    if (childPs != null) {
15817                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15818                    }
15819                    childRes.removedInfo.isUpdate = true;
15820                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15821                    childPackageUpdated = true;
15822                }
15823            }
15824            if (!childPackageUpdated) {
15825                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15826                childRemovedRes.removedPackage = childPkg.packageName;
15827                if (childPs != null) {
15828                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15829                }
15830                childRemovedRes.isUpdate = false;
15831                childRemovedRes.dataRemoved = true;
15832                synchronized (mPackages) {
15833                    if (childPs != null) {
15834                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15835                    }
15836                }
15837                if (res.removedInfo.removedChildPackages == null) {
15838                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15839                }
15840                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15841            }
15842        }
15843
15844        boolean sysPkg = (isSystemApp(oldPackage));
15845        if (sysPkg) {
15846            // Set the system/privileged/oem/vendor flags as needed
15847            final boolean privileged =
15848                    (oldPackage.applicationInfo.privateFlags
15849                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15850            final boolean oem =
15851                    (oldPackage.applicationInfo.privateFlags
15852                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15853            final boolean vendor =
15854                    (oldPackage.applicationInfo.privateFlags
15855                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
15856            final @ParseFlags int systemParseFlags = parseFlags;
15857            final @ScanFlags int systemScanFlags = scanFlags
15858                    | SCAN_AS_SYSTEM
15859                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15860                    | (oem ? SCAN_AS_OEM : 0)
15861                    | (vendor ? SCAN_AS_VENDOR : 0);
15862
15863            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15864                    user, allUsers, installerPackageName, res, installReason);
15865        } else {
15866            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15867                    user, allUsers, installerPackageName, res, installReason);
15868        }
15869    }
15870
15871    @Override
15872    public List<String> getPreviousCodePaths(String packageName) {
15873        final int callingUid = Binder.getCallingUid();
15874        final List<String> result = new ArrayList<>();
15875        if (getInstantAppPackageName(callingUid) != null) {
15876            return result;
15877        }
15878        final PackageSetting ps = mSettings.mPackages.get(packageName);
15879        if (ps != null
15880                && ps.oldCodePaths != null
15881                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15882            result.addAll(ps.oldCodePaths);
15883        }
15884        return result;
15885    }
15886
15887    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15888            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15889            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15890            String installerPackageName, PackageInstalledInfo res, int installReason) {
15891        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15892                + deletedPackage);
15893
15894        String pkgName = deletedPackage.packageName;
15895        boolean deletedPkg = true;
15896        boolean addedPkg = false;
15897        boolean updatedSettings = false;
15898        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15899        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15900                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15901
15902        final long origUpdateTime = (pkg.mExtras != null)
15903                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15904
15905        // First delete the existing package while retaining the data directory
15906        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15907                res.removedInfo, true, pkg)) {
15908            // If the existing package wasn't successfully deleted
15909            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15910            deletedPkg = false;
15911        } else {
15912            // Successfully deleted the old package; proceed with replace.
15913
15914            // If deleted package lived in a container, give users a chance to
15915            // relinquish resources before killing.
15916            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15917                if (DEBUG_INSTALL) {
15918                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15919                }
15920                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15921                final ArrayList<String> pkgList = new ArrayList<String>(1);
15922                pkgList.add(deletedPackage.applicationInfo.packageName);
15923                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15924            }
15925
15926            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15927                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15928            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15929
15930            try {
15931                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15932                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15933                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15934                        installReason);
15935
15936                // Update the in-memory copy of the previous code paths.
15937                PackageSetting ps = mSettings.mPackages.get(pkgName);
15938                if (!killApp) {
15939                    if (ps.oldCodePaths == null) {
15940                        ps.oldCodePaths = new ArraySet<>();
15941                    }
15942                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15943                    if (deletedPackage.splitCodePaths != null) {
15944                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15945                    }
15946                } else {
15947                    ps.oldCodePaths = null;
15948                }
15949                if (ps.childPackageNames != null) {
15950                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15951                        final String childPkgName = ps.childPackageNames.get(i);
15952                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15953                        childPs.oldCodePaths = ps.oldCodePaths;
15954                    }
15955                }
15956                // set instant app status, but, only if it's explicitly specified
15957                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15958                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15959                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15960                prepareAppDataAfterInstallLIF(newPackage);
15961                addedPkg = true;
15962                mDexManager.notifyPackageUpdated(newPackage.packageName,
15963                        newPackage.baseCodePath, newPackage.splitCodePaths);
15964            } catch (PackageManagerException e) {
15965                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15966            }
15967        }
15968
15969        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15970            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15971
15972            // Revert all internal state mutations and added folders for the failed install
15973            if (addedPkg) {
15974                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15975                        res.removedInfo, true, null);
15976            }
15977
15978            // Restore the old package
15979            if (deletedPkg) {
15980                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15981                File restoreFile = new File(deletedPackage.codePath);
15982                // Parse old package
15983                boolean oldExternal = isExternal(deletedPackage);
15984                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15985                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15986                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15987                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15988                try {
15989                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15990                            null);
15991                } catch (PackageManagerException e) {
15992                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15993                            + e.getMessage());
15994                    return;
15995                }
15996
15997                synchronized (mPackages) {
15998                    // Ensure the installer package name up to date
15999                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16000
16001                    // Update permissions for restored package
16002                    mPermissionManager.updatePermissions(
16003                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16004                            mPermissionCallback);
16005
16006                    mSettings.writeLPr();
16007                }
16008
16009                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16010            }
16011        } else {
16012            synchronized (mPackages) {
16013                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16014                if (ps != null) {
16015                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16016                    if (res.removedInfo.removedChildPackages != null) {
16017                        final int childCount = res.removedInfo.removedChildPackages.size();
16018                        // Iterate in reverse as we may modify the collection
16019                        for (int i = childCount - 1; i >= 0; i--) {
16020                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16021                            if (res.addedChildPackages.containsKey(childPackageName)) {
16022                                res.removedInfo.removedChildPackages.removeAt(i);
16023                            } else {
16024                                PackageRemovedInfo childInfo = res.removedInfo
16025                                        .removedChildPackages.valueAt(i);
16026                                childInfo.removedForAllUsers = mPackages.get(
16027                                        childInfo.removedPackage) == null;
16028                            }
16029                        }
16030                    }
16031                }
16032            }
16033        }
16034    }
16035
16036    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16037            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16038            final @ScanFlags int scanFlags, UserHandle user,
16039            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16040            int installReason) {
16041        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16042                + ", old=" + deletedPackage);
16043
16044        final boolean disabledSystem;
16045
16046        // Remove existing system package
16047        removePackageLI(deletedPackage, true);
16048
16049        synchronized (mPackages) {
16050            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16051        }
16052        if (!disabledSystem) {
16053            // We didn't need to disable the .apk as a current system package,
16054            // which means we are replacing another update that is already
16055            // installed.  We need to make sure to delete the older one's .apk.
16056            res.removedInfo.args = createInstallArgsForExisting(0,
16057                    deletedPackage.applicationInfo.getCodePath(),
16058                    deletedPackage.applicationInfo.getResourcePath(),
16059                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16060        } else {
16061            res.removedInfo.args = null;
16062        }
16063
16064        // Successfully disabled the old package. Now proceed with re-installation
16065        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16066                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16067        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16068
16069        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16070        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16071                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16072
16073        PackageParser.Package newPackage = null;
16074        try {
16075            // Add the package to the internal data structures
16076            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16077
16078            // Set the update and install times
16079            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16080            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16081                    System.currentTimeMillis());
16082
16083            // Update the package dynamic state if succeeded
16084            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16085                // Now that the install succeeded make sure we remove data
16086                // directories for any child package the update removed.
16087                final int deletedChildCount = (deletedPackage.childPackages != null)
16088                        ? deletedPackage.childPackages.size() : 0;
16089                final int newChildCount = (newPackage.childPackages != null)
16090                        ? newPackage.childPackages.size() : 0;
16091                for (int i = 0; i < deletedChildCount; i++) {
16092                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16093                    boolean childPackageDeleted = true;
16094                    for (int j = 0; j < newChildCount; j++) {
16095                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16096                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16097                            childPackageDeleted = false;
16098                            break;
16099                        }
16100                    }
16101                    if (childPackageDeleted) {
16102                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16103                                deletedChildPkg.packageName);
16104                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16105                            PackageRemovedInfo removedChildRes = res.removedInfo
16106                                    .removedChildPackages.get(deletedChildPkg.packageName);
16107                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16108                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16109                        }
16110                    }
16111                }
16112
16113                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16114                        installReason);
16115                prepareAppDataAfterInstallLIF(newPackage);
16116
16117                mDexManager.notifyPackageUpdated(newPackage.packageName,
16118                            newPackage.baseCodePath, newPackage.splitCodePaths);
16119            }
16120        } catch (PackageManagerException e) {
16121            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16122            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16123        }
16124
16125        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16126            // Re installation failed. Restore old information
16127            // Remove new pkg information
16128            if (newPackage != null) {
16129                removeInstalledPackageLI(newPackage, true);
16130            }
16131            // Add back the old system package
16132            try {
16133                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16134            } catch (PackageManagerException e) {
16135                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16136            }
16137
16138            synchronized (mPackages) {
16139                if (disabledSystem) {
16140                    enableSystemPackageLPw(deletedPackage);
16141                }
16142
16143                // Ensure the installer package name up to date
16144                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16145
16146                // Update permissions for restored package
16147                mPermissionManager.updatePermissions(
16148                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16149                        mPermissionCallback);
16150
16151                mSettings.writeLPr();
16152            }
16153
16154            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16155                    + " after failed upgrade");
16156        }
16157    }
16158
16159    /**
16160     * Checks whether the parent or any of the child packages have a change shared
16161     * user. For a package to be a valid update the shred users of the parent and
16162     * the children should match. We may later support changing child shared users.
16163     * @param oldPkg The updated package.
16164     * @param newPkg The update package.
16165     * @return The shared user that change between the versions.
16166     */
16167    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16168            PackageParser.Package newPkg) {
16169        // Check parent shared user
16170        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16171            return newPkg.packageName;
16172        }
16173        // Check child shared users
16174        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16175        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16176        for (int i = 0; i < newChildCount; i++) {
16177            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16178            // If this child was present, did it have the same shared user?
16179            for (int j = 0; j < oldChildCount; j++) {
16180                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16181                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16182                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16183                    return newChildPkg.packageName;
16184                }
16185            }
16186        }
16187        return null;
16188    }
16189
16190    private void removeNativeBinariesLI(PackageSetting ps) {
16191        // Remove the lib path for the parent package
16192        if (ps != null) {
16193            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16194            // Remove the lib path for the child packages
16195            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16196            for (int i = 0; i < childCount; i++) {
16197                PackageSetting childPs = null;
16198                synchronized (mPackages) {
16199                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16200                }
16201                if (childPs != null) {
16202                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16203                            .legacyNativeLibraryPathString);
16204                }
16205            }
16206        }
16207    }
16208
16209    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16210        // Enable the parent package
16211        mSettings.enableSystemPackageLPw(pkg.packageName);
16212        // Enable the child packages
16213        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16214        for (int i = 0; i < childCount; i++) {
16215            PackageParser.Package childPkg = pkg.childPackages.get(i);
16216            mSettings.enableSystemPackageLPw(childPkg.packageName);
16217        }
16218    }
16219
16220    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16221            PackageParser.Package newPkg) {
16222        // Disable the parent package (parent always replaced)
16223        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16224        // Disable the child packages
16225        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16226        for (int i = 0; i < childCount; i++) {
16227            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16228            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16229            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16230        }
16231        return disabled;
16232    }
16233
16234    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16235            String installerPackageName) {
16236        // Enable the parent package
16237        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16238        // Enable the child packages
16239        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16240        for (int i = 0; i < childCount; i++) {
16241            PackageParser.Package childPkg = pkg.childPackages.get(i);
16242            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16243        }
16244    }
16245
16246    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16247            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16248        // Update the parent package setting
16249        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16250                res, user, installReason);
16251        // Update the child packages setting
16252        final int childCount = (newPackage.childPackages != null)
16253                ? newPackage.childPackages.size() : 0;
16254        for (int i = 0; i < childCount; i++) {
16255            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16256            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16257            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16258                    childRes.origUsers, childRes, user, installReason);
16259        }
16260    }
16261
16262    private void updateSettingsInternalLI(PackageParser.Package pkg,
16263            String installerPackageName, int[] allUsers, int[] installedForUsers,
16264            PackageInstalledInfo res, UserHandle user, int installReason) {
16265        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16266
16267        String pkgName = pkg.packageName;
16268        synchronized (mPackages) {
16269            //write settings. the installStatus will be incomplete at this stage.
16270            //note that the new package setting would have already been
16271            //added to mPackages. It hasn't been persisted yet.
16272            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16273            // TODO: Remove this write? It's also written at the end of this method
16274            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16275            mSettings.writeLPr();
16276            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16277        }
16278
16279        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16280        synchronized (mPackages) {
16281// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16282            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16283                    mPermissionCallback);
16284            // For system-bundled packages, we assume that installing an upgraded version
16285            // of the package implies that the user actually wants to run that new code,
16286            // so we enable the package.
16287            PackageSetting ps = mSettings.mPackages.get(pkgName);
16288            final int userId = user.getIdentifier();
16289            if (ps != null) {
16290                if (isSystemApp(pkg)) {
16291                    if (DEBUG_INSTALL) {
16292                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16293                    }
16294                    // Enable system package for requested users
16295                    if (res.origUsers != null) {
16296                        for (int origUserId : res.origUsers) {
16297                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16298                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16299                                        origUserId, installerPackageName);
16300                            }
16301                        }
16302                    }
16303                    // Also convey the prior install/uninstall state
16304                    if (allUsers != null && installedForUsers != null) {
16305                        for (int currentUserId : allUsers) {
16306                            final boolean installed = ArrayUtils.contains(
16307                                    installedForUsers, currentUserId);
16308                            if (DEBUG_INSTALL) {
16309                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16310                            }
16311                            ps.setInstalled(installed, currentUserId);
16312                        }
16313                        // these install state changes will be persisted in the
16314                        // upcoming call to mSettings.writeLPr().
16315                    }
16316                }
16317                // It's implied that when a user requests installation, they want the app to be
16318                // installed and enabled.
16319                if (userId != UserHandle.USER_ALL) {
16320                    ps.setInstalled(true, userId);
16321                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16322                }
16323
16324                // When replacing an existing package, preserve the original install reason for all
16325                // users that had the package installed before.
16326                final Set<Integer> previousUserIds = new ArraySet<>();
16327                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16328                    final int installReasonCount = res.removedInfo.installReasons.size();
16329                    for (int i = 0; i < installReasonCount; i++) {
16330                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16331                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16332                        ps.setInstallReason(previousInstallReason, previousUserId);
16333                        previousUserIds.add(previousUserId);
16334                    }
16335                }
16336
16337                // Set install reason for users that are having the package newly installed.
16338                if (userId == UserHandle.USER_ALL) {
16339                    for (int currentUserId : sUserManager.getUserIds()) {
16340                        if (!previousUserIds.contains(currentUserId)) {
16341                            ps.setInstallReason(installReason, currentUserId);
16342                        }
16343                    }
16344                } else if (!previousUserIds.contains(userId)) {
16345                    ps.setInstallReason(installReason, userId);
16346                }
16347                mSettings.writeKernelMappingLPr(ps);
16348            }
16349            res.name = pkgName;
16350            res.uid = pkg.applicationInfo.uid;
16351            res.pkg = pkg;
16352            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16353            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16354            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16355            //to update install status
16356            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16357            mSettings.writeLPr();
16358            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16359        }
16360
16361        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16362    }
16363
16364    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16365        try {
16366            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16367            installPackageLI(args, res);
16368        } finally {
16369            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16370        }
16371    }
16372
16373    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16374        final int installFlags = args.installFlags;
16375        final String installerPackageName = args.installerPackageName;
16376        final String volumeUuid = args.volumeUuid;
16377        final File tmpPackageFile = new File(args.getCodePath());
16378        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16379        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16380                || (args.volumeUuid != null));
16381        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16382        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16383        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16384        final boolean virtualPreload =
16385                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16386        boolean replace = false;
16387        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16388        if (args.move != null) {
16389            // moving a complete application; perform an initial scan on the new install location
16390            scanFlags |= SCAN_INITIAL;
16391        }
16392        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16393            scanFlags |= SCAN_DONT_KILL_APP;
16394        }
16395        if (instantApp) {
16396            scanFlags |= SCAN_AS_INSTANT_APP;
16397        }
16398        if (fullApp) {
16399            scanFlags |= SCAN_AS_FULL_APP;
16400        }
16401        if (virtualPreload) {
16402            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16403        }
16404
16405        // Result object to be returned
16406        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16407        res.installerPackageName = installerPackageName;
16408
16409        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16410
16411        // Sanity check
16412        if (instantApp && (forwardLocked || onExternal)) {
16413            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16414                    + " external=" + onExternal);
16415            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16416            return;
16417        }
16418
16419        // Retrieve PackageSettings and parse package
16420        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16421                | PackageParser.PARSE_ENFORCE_CODE
16422                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16423                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16424                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16425                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16426        PackageParser pp = new PackageParser();
16427        pp.setSeparateProcesses(mSeparateProcesses);
16428        pp.setDisplayMetrics(mMetrics);
16429        pp.setCallback(mPackageParserCallback);
16430
16431        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16432        final PackageParser.Package pkg;
16433        try {
16434            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16435        } catch (PackageParserException e) {
16436            res.setError("Failed parse during installPackageLI", e);
16437            return;
16438        } finally {
16439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16440        }
16441
16442        // App targetSdkVersion is below min supported version
16443        if (!forceSdk && pkg.applicationInfo.isTargetingDeprecatedSdkVersion()) {
16444            Slog.w(TAG, "App " + pkg.packageName + " targets deprecated sdk");
16445
16446            res.setError(INSTALL_FAILED_NEWER_SDK,
16447                    "App is targeting deprecated sdk (targetSdkVersion should be at least "
16448                    + Build.VERSION.MIN_SUPPORTED_TARGET_SDK_INT + ").");
16449            return;
16450        }
16451
16452        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16453        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16454            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16455            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16456                    "Instant app package must target O");
16457            return;
16458        }
16459        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16460            Slog.w(TAG, "Instant app package " + pkg.packageName
16461                    + " does not target targetSandboxVersion 2");
16462            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16463                    "Instant app package must use targetSanboxVersion 2");
16464            return;
16465        }
16466
16467        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16468            // Static shared libraries have synthetic package names
16469            renameStaticSharedLibraryPackage(pkg);
16470
16471            // No static shared libs on external storage
16472            if (onExternal) {
16473                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16474                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16475                        "Packages declaring static-shared libs cannot be updated");
16476                return;
16477            }
16478        }
16479
16480        // If we are installing a clustered package add results for the children
16481        if (pkg.childPackages != null) {
16482            synchronized (mPackages) {
16483                final int childCount = pkg.childPackages.size();
16484                for (int i = 0; i < childCount; i++) {
16485                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16486                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16487                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16488                    childRes.pkg = childPkg;
16489                    childRes.name = childPkg.packageName;
16490                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16491                    if (childPs != null) {
16492                        childRes.origUsers = childPs.queryInstalledUsers(
16493                                sUserManager.getUserIds(), true);
16494                    }
16495                    if ((mPackages.containsKey(childPkg.packageName))) {
16496                        childRes.removedInfo = new PackageRemovedInfo(this);
16497                        childRes.removedInfo.removedPackage = childPkg.packageName;
16498                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16499                    }
16500                    if (res.addedChildPackages == null) {
16501                        res.addedChildPackages = new ArrayMap<>();
16502                    }
16503                    res.addedChildPackages.put(childPkg.packageName, childRes);
16504                }
16505            }
16506        }
16507
16508        // If package doesn't declare API override, mark that we have an install
16509        // time CPU ABI override.
16510        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16511            pkg.cpuAbiOverride = args.abiOverride;
16512        }
16513
16514        String pkgName = res.name = pkg.packageName;
16515        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16516            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16517                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16518                return;
16519            }
16520        }
16521
16522        try {
16523            // either use what we've been given or parse directly from the APK
16524            if (args.certificates != null) {
16525                try {
16526                    PackageParser.populateCertificates(pkg, args.certificates);
16527                } catch (PackageParserException e) {
16528                    // there was something wrong with the certificates we were given;
16529                    // try to pull them from the APK
16530                    PackageParser.collectCertificates(pkg, parseFlags);
16531                }
16532            } else {
16533                PackageParser.collectCertificates(pkg, parseFlags);
16534            }
16535        } catch (PackageParserException e) {
16536            res.setError("Failed collect during installPackageLI", e);
16537            return;
16538        }
16539
16540        // Get rid of all references to package scan path via parser.
16541        pp = null;
16542        String oldCodePath = null;
16543        boolean systemApp = false;
16544        synchronized (mPackages) {
16545            // Check if installing already existing package
16546            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16547                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16548                if (pkg.mOriginalPackages != null
16549                        && pkg.mOriginalPackages.contains(oldName)
16550                        && mPackages.containsKey(oldName)) {
16551                    // This package is derived from an original package,
16552                    // and this device has been updating from that original
16553                    // name.  We must continue using the original name, so
16554                    // rename the new package here.
16555                    pkg.setPackageName(oldName);
16556                    pkgName = pkg.packageName;
16557                    replace = true;
16558                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16559                            + oldName + " pkgName=" + pkgName);
16560                } else if (mPackages.containsKey(pkgName)) {
16561                    // This package, under its official name, already exists
16562                    // on the device; we should replace it.
16563                    replace = true;
16564                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16565                }
16566
16567                // Child packages are installed through the parent package
16568                if (pkg.parentPackage != null) {
16569                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16570                            "Package " + pkg.packageName + " is child of package "
16571                                    + pkg.parentPackage.parentPackage + ". Child packages "
16572                                    + "can be updated only through the parent package.");
16573                    return;
16574                }
16575
16576                if (replace) {
16577                    // Prevent apps opting out from runtime permissions
16578                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16579                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16580                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16581                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16582                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16583                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16584                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16585                                        + " doesn't support runtime permissions but the old"
16586                                        + " target SDK " + oldTargetSdk + " does.");
16587                        return;
16588                    }
16589                    // Prevent persistent apps from being updated
16590                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16591                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16592                                "Package " + oldPackage.packageName + " is a persistent app. "
16593                                        + "Persistent apps are not updateable.");
16594                        return;
16595                    }
16596                    // Prevent apps from downgrading their targetSandbox.
16597                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16598                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16599                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16600                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16601                                "Package " + pkg.packageName + " new target sandbox "
16602                                + newTargetSandbox + " is incompatible with the previous value of"
16603                                + oldTargetSandbox + ".");
16604                        return;
16605                    }
16606
16607                    // Prevent installing of child packages
16608                    if (oldPackage.parentPackage != null) {
16609                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16610                                "Package " + pkg.packageName + " is child of package "
16611                                        + oldPackage.parentPackage + ". Child packages "
16612                                        + "can be updated only through the parent package.");
16613                        return;
16614                    }
16615                }
16616            }
16617
16618            PackageSetting ps = mSettings.mPackages.get(pkgName);
16619            if (ps != null) {
16620                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16621
16622                // Static shared libs have same package with different versions where
16623                // we internally use a synthetic package name to allow multiple versions
16624                // of the same package, therefore we need to compare signatures against
16625                // the package setting for the latest library version.
16626                PackageSetting signatureCheckPs = ps;
16627                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16628                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16629                    if (libraryEntry != null) {
16630                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16631                    }
16632                }
16633
16634                // Quick sanity check that we're signed correctly if updating;
16635                // we'll check this again later when scanning, but we want to
16636                // bail early here before tripping over redefined permissions.
16637                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16638                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16639                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16640                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16641                                + pkg.packageName + " upgrade keys do not match the "
16642                                + "previously installed version");
16643                        return;
16644                    }
16645                } else {
16646                    try {
16647                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16648                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16649                        final boolean compatMatch = verifySignatures(
16650                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16651                        // The new KeySets will be re-added later in the scanning process.
16652                        if (compatMatch) {
16653                            synchronized (mPackages) {
16654                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16655                            }
16656                        }
16657                    } catch (PackageManagerException e) {
16658                        res.setError(e.error, e.getMessage());
16659                        return;
16660                    }
16661                }
16662
16663                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16664                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16665                    systemApp = (ps.pkg.applicationInfo.flags &
16666                            ApplicationInfo.FLAG_SYSTEM) != 0;
16667                }
16668                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16669            }
16670
16671            int N = pkg.permissions.size();
16672            for (int i = N-1; i >= 0; i--) {
16673                final PackageParser.Permission perm = pkg.permissions.get(i);
16674                final BasePermission bp =
16675                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16676
16677                // Don't allow anyone but the system to define ephemeral permissions.
16678                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16679                        && !systemApp) {
16680                    Slog.w(TAG, "Non-System package " + pkg.packageName
16681                            + " attempting to delcare ephemeral permission "
16682                            + perm.info.name + "; Removing ephemeral.");
16683                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16684                }
16685
16686                // Check whether the newly-scanned package wants to define an already-defined perm
16687                if (bp != null) {
16688                    // If the defining package is signed with our cert, it's okay.  This
16689                    // also includes the "updating the same package" case, of course.
16690                    // "updating same package" could also involve key-rotation.
16691                    final boolean sigsOk;
16692                    final String sourcePackageName = bp.getSourcePackageName();
16693                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16694                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16695                    if (sourcePackageName.equals(pkg.packageName)
16696                            && (ksms.shouldCheckUpgradeKeySetLocked(
16697                                    sourcePackageSetting, scanFlags))) {
16698                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16699                    } else {
16700                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16701                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16702                    }
16703                    if (!sigsOk) {
16704                        // If the owning package is the system itself, we log but allow
16705                        // install to proceed; we fail the install on all other permission
16706                        // redefinitions.
16707                        if (!sourcePackageName.equals("android")) {
16708                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16709                                    + pkg.packageName + " attempting to redeclare permission "
16710                                    + perm.info.name + " already owned by " + sourcePackageName);
16711                            res.origPermission = perm.info.name;
16712                            res.origPackage = sourcePackageName;
16713                            return;
16714                        } else {
16715                            Slog.w(TAG, "Package " + pkg.packageName
16716                                    + " attempting to redeclare system permission "
16717                                    + perm.info.name + "; ignoring new declaration");
16718                            pkg.permissions.remove(i);
16719                        }
16720                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16721                        // Prevent apps to change protection level to dangerous from any other
16722                        // type as this would allow a privilege escalation where an app adds a
16723                        // normal/signature permission in other app's group and later redefines
16724                        // it as dangerous leading to the group auto-grant.
16725                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16726                                == PermissionInfo.PROTECTION_DANGEROUS) {
16727                            if (bp != null && !bp.isRuntime()) {
16728                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16729                                        + "non-runtime permission " + perm.info.name
16730                                        + " to runtime; keeping old protection level");
16731                                perm.info.protectionLevel = bp.getProtectionLevel();
16732                            }
16733                        }
16734                    }
16735                }
16736            }
16737        }
16738
16739        if (systemApp) {
16740            if (onExternal) {
16741                // Abort update; system app can't be replaced with app on sdcard
16742                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16743                        "Cannot install updates to system apps on sdcard");
16744                return;
16745            } else if (instantApp) {
16746                // Abort update; system app can't be replaced with an instant app
16747                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16748                        "Cannot update a system app with an instant app");
16749                return;
16750            }
16751        }
16752
16753        if (args.move != null) {
16754            // We did an in-place move, so dex is ready to roll
16755            scanFlags |= SCAN_NO_DEX;
16756            scanFlags |= SCAN_MOVE;
16757
16758            synchronized (mPackages) {
16759                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16760                if (ps == null) {
16761                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16762                            "Missing settings for moved package " + pkgName);
16763                }
16764
16765                // We moved the entire application as-is, so bring over the
16766                // previously derived ABI information.
16767                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16768                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16769            }
16770
16771        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16772            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16773            scanFlags |= SCAN_NO_DEX;
16774
16775            try {
16776                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16777                    args.abiOverride : pkg.cpuAbiOverride);
16778                final boolean extractNativeLibs = !pkg.isLibrary();
16779                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
16780            } catch (PackageManagerException pme) {
16781                Slog.e(TAG, "Error deriving application ABI", pme);
16782                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16783                return;
16784            }
16785
16786            // Shared libraries for the package need to be updated.
16787            synchronized (mPackages) {
16788                try {
16789                    updateSharedLibrariesLPr(pkg, null);
16790                } catch (PackageManagerException e) {
16791                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16792                }
16793            }
16794        }
16795
16796        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16797            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16798            return;
16799        }
16800
16801        if (!instantApp) {
16802            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16803        } else {
16804            if (DEBUG_DOMAIN_VERIFICATION) {
16805                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16806            }
16807        }
16808
16809        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16810                "installPackageLI")) {
16811            if (replace) {
16812                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16813                    // Static libs have a synthetic package name containing the version
16814                    // and cannot be updated as an update would get a new package name,
16815                    // unless this is the exact same version code which is useful for
16816                    // development.
16817                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16818                    if (existingPkg != null &&
16819                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
16820                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16821                                + "static-shared libs cannot be updated");
16822                        return;
16823                    }
16824                }
16825                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16826                        installerPackageName, res, args.installReason);
16827            } else {
16828                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16829                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16830            }
16831        }
16832
16833        // Check whether we need to dexopt the app.
16834        //
16835        // NOTE: it is IMPORTANT to call dexopt:
16836        //   - after doRename which will sync the package data from PackageParser.Package and its
16837        //     corresponding ApplicationInfo.
16838        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
16839        //     uid of the application (pkg.applicationInfo.uid).
16840        //     This update happens in place!
16841        //
16842        // We only need to dexopt if the package meets ALL of the following conditions:
16843        //   1) it is not forward locked.
16844        //   2) it is not on on an external ASEC container.
16845        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16846        //
16847        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16848        // complete, so we skip this step during installation. Instead, we'll take extra time
16849        // the first time the instant app starts. It's preferred to do it this way to provide
16850        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16851        // middle of running an instant app. The default behaviour can be overridden
16852        // via gservices.
16853        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
16854                && !forwardLocked
16855                && !pkg.applicationInfo.isExternalAsec()
16856                && (!instantApp || Global.getInt(mContext.getContentResolver(),
16857                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16858
16859        if (performDexopt) {
16860            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16861            // Do not run PackageDexOptimizer through the local performDexOpt
16862            // method because `pkg` may not be in `mPackages` yet.
16863            //
16864            // Also, don't fail application installs if the dexopt step fails.
16865            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16866                    REASON_INSTALL,
16867                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
16868            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16869                    null /* instructionSets */,
16870                    getOrCreateCompilerPackageStats(pkg),
16871                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16872                    dexoptOptions);
16873            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16874        }
16875
16876        // Notify BackgroundDexOptService that the package has been changed.
16877        // If this is an update of a package which used to fail to compile,
16878        // BackgroundDexOptService will remove it from its blacklist.
16879        // TODO: Layering violation
16880        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16881
16882        synchronized (mPackages) {
16883            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16884            if (ps != null) {
16885                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16886                ps.setUpdateAvailable(false /*updateAvailable*/);
16887            }
16888
16889            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16890            for (int i = 0; i < childCount; i++) {
16891                PackageParser.Package childPkg = pkg.childPackages.get(i);
16892                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16893                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16894                if (childPs != null) {
16895                    childRes.newUsers = childPs.queryInstalledUsers(
16896                            sUserManager.getUserIds(), true);
16897                }
16898            }
16899
16900            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16901                updateSequenceNumberLP(ps, res.newUsers);
16902                updateInstantAppInstallerLocked(pkgName);
16903            }
16904        }
16905    }
16906
16907    private void startIntentFilterVerifications(int userId, boolean replacing,
16908            PackageParser.Package pkg) {
16909        if (mIntentFilterVerifierComponent == null) {
16910            Slog.w(TAG, "No IntentFilter verification will not be done as "
16911                    + "there is no IntentFilterVerifier available!");
16912            return;
16913        }
16914
16915        final int verifierUid = getPackageUid(
16916                mIntentFilterVerifierComponent.getPackageName(),
16917                MATCH_DEBUG_TRIAGED_MISSING,
16918                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16919
16920        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16921        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16922        mHandler.sendMessage(msg);
16923
16924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16925        for (int i = 0; i < childCount; i++) {
16926            PackageParser.Package childPkg = pkg.childPackages.get(i);
16927            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16928            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16929            mHandler.sendMessage(msg);
16930        }
16931    }
16932
16933    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16934            PackageParser.Package pkg) {
16935        int size = pkg.activities.size();
16936        if (size == 0) {
16937            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16938                    "No activity, so no need to verify any IntentFilter!");
16939            return;
16940        }
16941
16942        final boolean hasDomainURLs = hasDomainURLs(pkg);
16943        if (!hasDomainURLs) {
16944            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16945                    "No domain URLs, so no need to verify any IntentFilter!");
16946            return;
16947        }
16948
16949        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16950                + " if any IntentFilter from the " + size
16951                + " Activities needs verification ...");
16952
16953        int count = 0;
16954        final String packageName = pkg.packageName;
16955
16956        synchronized (mPackages) {
16957            // If this is a new install and we see that we've already run verification for this
16958            // package, we have nothing to do: it means the state was restored from backup.
16959            if (!replacing) {
16960                IntentFilterVerificationInfo ivi =
16961                        mSettings.getIntentFilterVerificationLPr(packageName);
16962                if (ivi != null) {
16963                    if (DEBUG_DOMAIN_VERIFICATION) {
16964                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16965                                + ivi.getStatusString());
16966                    }
16967                    return;
16968                }
16969            }
16970
16971            // If any filters need to be verified, then all need to be.
16972            boolean needToVerify = false;
16973            for (PackageParser.Activity a : pkg.activities) {
16974                for (ActivityIntentInfo filter : a.intents) {
16975                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16976                        if (DEBUG_DOMAIN_VERIFICATION) {
16977                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16978                        }
16979                        needToVerify = true;
16980                        break;
16981                    }
16982                }
16983            }
16984
16985            if (needToVerify) {
16986                final int verificationId = mIntentFilterVerificationToken++;
16987                for (PackageParser.Activity a : pkg.activities) {
16988                    for (ActivityIntentInfo filter : a.intents) {
16989                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16990                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16991                                    "Verification needed for IntentFilter:" + filter.toString());
16992                            mIntentFilterVerifier.addOneIntentFilterVerification(
16993                                    verifierUid, userId, verificationId, filter, packageName);
16994                            count++;
16995                        }
16996                    }
16997                }
16998            }
16999        }
17000
17001        if (count > 0) {
17002            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17003                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17004                    +  " for userId:" + userId);
17005            mIntentFilterVerifier.startVerifications(userId);
17006        } else {
17007            if (DEBUG_DOMAIN_VERIFICATION) {
17008                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17009            }
17010        }
17011    }
17012
17013    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17014        final ComponentName cn  = filter.activity.getComponentName();
17015        final String packageName = cn.getPackageName();
17016
17017        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17018                packageName);
17019        if (ivi == null) {
17020            return true;
17021        }
17022        int status = ivi.getStatus();
17023        switch (status) {
17024            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17025            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17026                return true;
17027
17028            default:
17029                // Nothing to do
17030                return false;
17031        }
17032    }
17033
17034    private static boolean isMultiArch(ApplicationInfo info) {
17035        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17036    }
17037
17038    private static boolean isExternal(PackageParser.Package pkg) {
17039        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17040    }
17041
17042    private static boolean isExternal(PackageSetting ps) {
17043        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17044    }
17045
17046    private static boolean isSystemApp(PackageParser.Package pkg) {
17047        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17048    }
17049
17050    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17051        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17052    }
17053
17054    private static boolean isOemApp(PackageParser.Package pkg) {
17055        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17056    }
17057
17058    private static boolean isVendorApp(PackageParser.Package pkg) {
17059        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17060    }
17061
17062    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17063        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17064    }
17065
17066    private static boolean isSystemApp(PackageSetting ps) {
17067        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17068    }
17069
17070    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17071        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17072    }
17073
17074    private int packageFlagsToInstallFlags(PackageSetting ps) {
17075        int installFlags = 0;
17076        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17077            // This existing package was an external ASEC install when we have
17078            // the external flag without a UUID
17079            installFlags |= PackageManager.INSTALL_EXTERNAL;
17080        }
17081        if (ps.isForwardLocked()) {
17082            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17083        }
17084        return installFlags;
17085    }
17086
17087    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17088        if (isExternal(pkg)) {
17089            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17090                return mSettings.getExternalVersion();
17091            } else {
17092                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17093            }
17094        } else {
17095            return mSettings.getInternalVersion();
17096        }
17097    }
17098
17099    private void deleteTempPackageFiles() {
17100        final FilenameFilter filter = new FilenameFilter() {
17101            public boolean accept(File dir, String name) {
17102                return name.startsWith("vmdl") && name.endsWith(".tmp");
17103            }
17104        };
17105        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17106            file.delete();
17107        }
17108    }
17109
17110    @Override
17111    public void deletePackageAsUser(String packageName, int versionCode,
17112            IPackageDeleteObserver observer, int userId, int flags) {
17113        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17114                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17115    }
17116
17117    @Override
17118    public void deletePackageVersioned(VersionedPackage versionedPackage,
17119            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17120        final int callingUid = Binder.getCallingUid();
17121        mContext.enforceCallingOrSelfPermission(
17122                android.Manifest.permission.DELETE_PACKAGES, null);
17123        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17124        Preconditions.checkNotNull(versionedPackage);
17125        Preconditions.checkNotNull(observer);
17126        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17127                PackageManager.VERSION_CODE_HIGHEST,
17128                Long.MAX_VALUE, "versionCode must be >= -1");
17129
17130        final String packageName = versionedPackage.getPackageName();
17131        final long versionCode = versionedPackage.getLongVersionCode();
17132        final String internalPackageName;
17133        synchronized (mPackages) {
17134            // Normalize package name to handle renamed packages and static libs
17135            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17136        }
17137
17138        final int uid = Binder.getCallingUid();
17139        if (!isOrphaned(internalPackageName)
17140                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17141            try {
17142                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17143                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17144                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17145                observer.onUserActionRequired(intent);
17146            } catch (RemoteException re) {
17147            }
17148            return;
17149        }
17150        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17151        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17152        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17153            mContext.enforceCallingOrSelfPermission(
17154                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17155                    "deletePackage for user " + userId);
17156        }
17157
17158        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17159            try {
17160                observer.onPackageDeleted(packageName,
17161                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17162            } catch (RemoteException re) {
17163            }
17164            return;
17165        }
17166
17167        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17168            try {
17169                observer.onPackageDeleted(packageName,
17170                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17171            } catch (RemoteException re) {
17172            }
17173            return;
17174        }
17175
17176        if (DEBUG_REMOVE) {
17177            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17178                    + " deleteAllUsers: " + deleteAllUsers + " version="
17179                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17180                    ? "VERSION_CODE_HIGHEST" : versionCode));
17181        }
17182        // Queue up an async operation since the package deletion may take a little while.
17183        mHandler.post(new Runnable() {
17184            public void run() {
17185                mHandler.removeCallbacks(this);
17186                int returnCode;
17187                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17188                boolean doDeletePackage = true;
17189                if (ps != null) {
17190                    final boolean targetIsInstantApp =
17191                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17192                    doDeletePackage = !targetIsInstantApp
17193                            || canViewInstantApps;
17194                }
17195                if (doDeletePackage) {
17196                    if (!deleteAllUsers) {
17197                        returnCode = deletePackageX(internalPackageName, versionCode,
17198                                userId, deleteFlags);
17199                    } else {
17200                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17201                                internalPackageName, users);
17202                        // If nobody is blocking uninstall, proceed with delete for all users
17203                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17204                            returnCode = deletePackageX(internalPackageName, versionCode,
17205                                    userId, deleteFlags);
17206                        } else {
17207                            // Otherwise uninstall individually for users with blockUninstalls=false
17208                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17209                            for (int userId : users) {
17210                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17211                                    returnCode = deletePackageX(internalPackageName, versionCode,
17212                                            userId, userFlags);
17213                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17214                                        Slog.w(TAG, "Package delete failed for user " + userId
17215                                                + ", returnCode " + returnCode);
17216                                    }
17217                                }
17218                            }
17219                            // The app has only been marked uninstalled for certain users.
17220                            // We still need to report that delete was blocked
17221                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17222                        }
17223                    }
17224                } else {
17225                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17226                }
17227                try {
17228                    observer.onPackageDeleted(packageName, returnCode, null);
17229                } catch (RemoteException e) {
17230                    Log.i(TAG, "Observer no longer exists.");
17231                } //end catch
17232            } //end run
17233        });
17234    }
17235
17236    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17237        if (pkg.staticSharedLibName != null) {
17238            return pkg.manifestPackageName;
17239        }
17240        return pkg.packageName;
17241    }
17242
17243    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17244        // Handle renamed packages
17245        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17246        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17247
17248        // Is this a static library?
17249        LongSparseArray<SharedLibraryEntry> versionedLib =
17250                mStaticLibsByDeclaringPackage.get(packageName);
17251        if (versionedLib == null || versionedLib.size() <= 0) {
17252            return packageName;
17253        }
17254
17255        // Figure out which lib versions the caller can see
17256        LongSparseLongArray versionsCallerCanSee = null;
17257        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17258        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17259                && callingAppId != Process.ROOT_UID) {
17260            versionsCallerCanSee = new LongSparseLongArray();
17261            String libName = versionedLib.valueAt(0).info.getName();
17262            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17263            if (uidPackages != null) {
17264                for (String uidPackage : uidPackages) {
17265                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17266                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17267                    if (libIdx >= 0) {
17268                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17269                        versionsCallerCanSee.append(libVersion, libVersion);
17270                    }
17271                }
17272            }
17273        }
17274
17275        // Caller can see nothing - done
17276        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17277            return packageName;
17278        }
17279
17280        // Find the version the caller can see and the app version code
17281        SharedLibraryEntry highestVersion = null;
17282        final int versionCount = versionedLib.size();
17283        for (int i = 0; i < versionCount; i++) {
17284            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17285            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17286                    libEntry.info.getLongVersion()) < 0) {
17287                continue;
17288            }
17289            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17290            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17291                if (libVersionCode == versionCode) {
17292                    return libEntry.apk;
17293                }
17294            } else if (highestVersion == null) {
17295                highestVersion = libEntry;
17296            } else if (libVersionCode  > highestVersion.info
17297                    .getDeclaringPackage().getLongVersionCode()) {
17298                highestVersion = libEntry;
17299            }
17300        }
17301
17302        if (highestVersion != null) {
17303            return highestVersion.apk;
17304        }
17305
17306        return packageName;
17307    }
17308
17309    boolean isCallerVerifier(int callingUid) {
17310        final int callingUserId = UserHandle.getUserId(callingUid);
17311        return mRequiredVerifierPackage != null &&
17312                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17313    }
17314
17315    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17316        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17317              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17318            return true;
17319        }
17320        final int callingUserId = UserHandle.getUserId(callingUid);
17321        // If the caller installed the pkgName, then allow it to silently uninstall.
17322        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17323            return true;
17324        }
17325
17326        // Allow package verifier to silently uninstall.
17327        if (mRequiredVerifierPackage != null &&
17328                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17329            return true;
17330        }
17331
17332        // Allow package uninstaller to silently uninstall.
17333        if (mRequiredUninstallerPackage != null &&
17334                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17335            return true;
17336        }
17337
17338        // Allow storage manager to silently uninstall.
17339        if (mStorageManagerPackage != null &&
17340                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17341            return true;
17342        }
17343
17344        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17345        // uninstall for device owner provisioning.
17346        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17347                == PERMISSION_GRANTED) {
17348            return true;
17349        }
17350
17351        return false;
17352    }
17353
17354    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17355        int[] result = EMPTY_INT_ARRAY;
17356        for (int userId : userIds) {
17357            if (getBlockUninstallForUser(packageName, userId)) {
17358                result = ArrayUtils.appendInt(result, userId);
17359            }
17360        }
17361        return result;
17362    }
17363
17364    @Override
17365    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17366        final int callingUid = Binder.getCallingUid();
17367        if (getInstantAppPackageName(callingUid) != null
17368                && !isCallerSameApp(packageName, callingUid)) {
17369            return false;
17370        }
17371        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17372    }
17373
17374    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17375        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17376                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17377        try {
17378            if (dpm != null) {
17379                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17380                        /* callingUserOnly =*/ false);
17381                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17382                        : deviceOwnerComponentName.getPackageName();
17383                // Does the package contains the device owner?
17384                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17385                // this check is probably not needed, since DO should be registered as a device
17386                // admin on some user too. (Original bug for this: b/17657954)
17387                if (packageName.equals(deviceOwnerPackageName)) {
17388                    return true;
17389                }
17390                // Does it contain a device admin for any user?
17391                int[] users;
17392                if (userId == UserHandle.USER_ALL) {
17393                    users = sUserManager.getUserIds();
17394                } else {
17395                    users = new int[]{userId};
17396                }
17397                for (int i = 0; i < users.length; ++i) {
17398                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17399                        return true;
17400                    }
17401                }
17402            }
17403        } catch (RemoteException e) {
17404        }
17405        return false;
17406    }
17407
17408    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17409        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17410    }
17411
17412    /**
17413     *  This method is an internal method that could be get invoked either
17414     *  to delete an installed package or to clean up a failed installation.
17415     *  After deleting an installed package, a broadcast is sent to notify any
17416     *  listeners that the package has been removed. For cleaning up a failed
17417     *  installation, the broadcast is not necessary since the package's
17418     *  installation wouldn't have sent the initial broadcast either
17419     *  The key steps in deleting a package are
17420     *  deleting the package information in internal structures like mPackages,
17421     *  deleting the packages base directories through installd
17422     *  updating mSettings to reflect current status
17423     *  persisting settings for later use
17424     *  sending a broadcast if necessary
17425     */
17426    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17427        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17428        final boolean res;
17429
17430        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17431                ? UserHandle.USER_ALL : userId;
17432
17433        if (isPackageDeviceAdmin(packageName, removeUser)) {
17434            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17435            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17436        }
17437
17438        PackageSetting uninstalledPs = null;
17439        PackageParser.Package pkg = null;
17440
17441        // for the uninstall-updates case and restricted profiles, remember the per-
17442        // user handle installed state
17443        int[] allUsers;
17444        synchronized (mPackages) {
17445            uninstalledPs = mSettings.mPackages.get(packageName);
17446            if (uninstalledPs == null) {
17447                Slog.w(TAG, "Not removing non-existent package " + packageName);
17448                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17449            }
17450
17451            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17452                    && uninstalledPs.versionCode != versionCode) {
17453                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17454                        + uninstalledPs.versionCode + " != " + versionCode);
17455                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17456            }
17457
17458            // Static shared libs can be declared by any package, so let us not
17459            // allow removing a package if it provides a lib others depend on.
17460            pkg = mPackages.get(packageName);
17461
17462            allUsers = sUserManager.getUserIds();
17463
17464            if (pkg != null && pkg.staticSharedLibName != null) {
17465                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17466                        pkg.staticSharedLibVersion);
17467                if (libEntry != null) {
17468                    for (int currUserId : allUsers) {
17469                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17470                            continue;
17471                        }
17472                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17473                                libEntry.info, 0, currUserId);
17474                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17475                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17476                                    + " hosting lib " + libEntry.info.getName() + " version "
17477                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17478                                    + " for user " + currUserId);
17479                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17480                        }
17481                    }
17482                }
17483            }
17484
17485            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17486        }
17487
17488        final int freezeUser;
17489        if (isUpdatedSystemApp(uninstalledPs)
17490                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17491            // We're downgrading a system app, which will apply to all users, so
17492            // freeze them all during the downgrade
17493            freezeUser = UserHandle.USER_ALL;
17494        } else {
17495            freezeUser = removeUser;
17496        }
17497
17498        synchronized (mInstallLock) {
17499            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17500            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17501                    deleteFlags, "deletePackageX")) {
17502                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17503                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17504            }
17505            synchronized (mPackages) {
17506                if (res) {
17507                    if (pkg != null) {
17508                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17509                    }
17510                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17511                    updateInstantAppInstallerLocked(packageName);
17512                }
17513            }
17514        }
17515
17516        if (res) {
17517            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17518            info.sendPackageRemovedBroadcasts(killApp);
17519            info.sendSystemPackageUpdatedBroadcasts();
17520            info.sendSystemPackageAppearedBroadcasts();
17521        }
17522        // Force a gc here.
17523        Runtime.getRuntime().gc();
17524        // Delete the resources here after sending the broadcast to let
17525        // other processes clean up before deleting resources.
17526        if (info.args != null) {
17527            synchronized (mInstallLock) {
17528                info.args.doPostDeleteLI(true);
17529            }
17530        }
17531
17532        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17533    }
17534
17535    static class PackageRemovedInfo {
17536        final PackageSender packageSender;
17537        String removedPackage;
17538        String installerPackageName;
17539        int uid = -1;
17540        int removedAppId = -1;
17541        int[] origUsers;
17542        int[] removedUsers = null;
17543        int[] broadcastUsers = null;
17544        int[] instantUserIds = null;
17545        SparseArray<Integer> installReasons;
17546        boolean isRemovedPackageSystemUpdate = false;
17547        boolean isUpdate;
17548        boolean dataRemoved;
17549        boolean removedForAllUsers;
17550        boolean isStaticSharedLib;
17551        // Clean up resources deleted packages.
17552        InstallArgs args = null;
17553        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17554        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17555
17556        PackageRemovedInfo(PackageSender packageSender) {
17557            this.packageSender = packageSender;
17558        }
17559
17560        void sendPackageRemovedBroadcasts(boolean killApp) {
17561            sendPackageRemovedBroadcastInternal(killApp);
17562            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17563            for (int i = 0; i < childCount; i++) {
17564                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17565                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17566            }
17567        }
17568
17569        void sendSystemPackageUpdatedBroadcasts() {
17570            if (isRemovedPackageSystemUpdate) {
17571                sendSystemPackageUpdatedBroadcastsInternal();
17572                final int childCount = (removedChildPackages != null)
17573                        ? removedChildPackages.size() : 0;
17574                for (int i = 0; i < childCount; i++) {
17575                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17576                    if (childInfo.isRemovedPackageSystemUpdate) {
17577                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17578                    }
17579                }
17580            }
17581        }
17582
17583        void sendSystemPackageAppearedBroadcasts() {
17584            final int packageCount = (appearedChildPackages != null)
17585                    ? appearedChildPackages.size() : 0;
17586            for (int i = 0; i < packageCount; i++) {
17587                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17588                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17589                    true /*sendBootCompleted*/, false /*startReceiver*/,
17590                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17591            }
17592        }
17593
17594        private void sendSystemPackageUpdatedBroadcastsInternal() {
17595            Bundle extras = new Bundle(2);
17596            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17597            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17598            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17599                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17600            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17601                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17602            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17603                null, null, 0, removedPackage, null, null, null);
17604            if (installerPackageName != null) {
17605                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17606                        removedPackage, extras, 0 /*flags*/,
17607                        installerPackageName, null, null, null);
17608                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17609                        removedPackage, extras, 0 /*flags*/,
17610                        installerPackageName, null, null, null);
17611            }
17612        }
17613
17614        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17615            // Don't send static shared library removal broadcasts as these
17616            // libs are visible only the the apps that depend on them an one
17617            // cannot remove the library if it has a dependency.
17618            if (isStaticSharedLib) {
17619                return;
17620            }
17621            Bundle extras = new Bundle(2);
17622            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17623            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17624            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17625            if (isUpdate || isRemovedPackageSystemUpdate) {
17626                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17627            }
17628            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17629            if (removedPackage != null) {
17630                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17631                    removedPackage, extras, 0, null /*targetPackage*/, null,
17632                    broadcastUsers, instantUserIds);
17633                if (installerPackageName != null) {
17634                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17635                            removedPackage, extras, 0 /*flags*/,
17636                            installerPackageName, null, broadcastUsers, instantUserIds);
17637                }
17638                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17639                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17640                        removedPackage, extras,
17641                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17642                        null, null, broadcastUsers, instantUserIds);
17643                }
17644            }
17645            if (removedAppId >= 0) {
17646                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17647                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17648                    null, null, broadcastUsers, instantUserIds);
17649            }
17650        }
17651
17652        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17653            removedUsers = userIds;
17654            if (removedUsers == null) {
17655                broadcastUsers = null;
17656                return;
17657            }
17658
17659            broadcastUsers = EMPTY_INT_ARRAY;
17660            instantUserIds = EMPTY_INT_ARRAY;
17661            for (int i = userIds.length - 1; i >= 0; --i) {
17662                final int userId = userIds[i];
17663                if (deletedPackageSetting.getInstantApp(userId)) {
17664                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
17665                } else {
17666                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17667                }
17668            }
17669        }
17670    }
17671
17672    /*
17673     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17674     * flag is not set, the data directory is removed as well.
17675     * make sure this flag is set for partially installed apps. If not its meaningless to
17676     * delete a partially installed application.
17677     */
17678    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17679            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17680        String packageName = ps.name;
17681        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17682        // Retrieve object to delete permissions for shared user later on
17683        final PackageParser.Package deletedPkg;
17684        final PackageSetting deletedPs;
17685        // reader
17686        synchronized (mPackages) {
17687            deletedPkg = mPackages.get(packageName);
17688            deletedPs = mSettings.mPackages.get(packageName);
17689            if (outInfo != null) {
17690                outInfo.removedPackage = packageName;
17691                outInfo.installerPackageName = ps.installerPackageName;
17692                outInfo.isStaticSharedLib = deletedPkg != null
17693                        && deletedPkg.staticSharedLibName != null;
17694                outInfo.populateUsers(deletedPs == null ? null
17695                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17696            }
17697        }
17698
17699        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17700
17701        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17702            final PackageParser.Package resolvedPkg;
17703            if (deletedPkg != null) {
17704                resolvedPkg = deletedPkg;
17705            } else {
17706                // We don't have a parsed package when it lives on an ejected
17707                // adopted storage device, so fake something together
17708                resolvedPkg = new PackageParser.Package(ps.name);
17709                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17710            }
17711            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17712                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17713            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17714            if (outInfo != null) {
17715                outInfo.dataRemoved = true;
17716            }
17717            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17718        }
17719
17720        int removedAppId = -1;
17721
17722        // writer
17723        synchronized (mPackages) {
17724            boolean installedStateChanged = false;
17725            if (deletedPs != null) {
17726                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17727                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17728                    clearDefaultBrowserIfNeeded(packageName);
17729                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17730                    removedAppId = mSettings.removePackageLPw(packageName);
17731                    if (outInfo != null) {
17732                        outInfo.removedAppId = removedAppId;
17733                    }
17734                    mPermissionManager.updatePermissions(
17735                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17736                    if (deletedPs.sharedUser != null) {
17737                        // Remove permissions associated with package. Since runtime
17738                        // permissions are per user we have to kill the removed package
17739                        // or packages running under the shared user of the removed
17740                        // package if revoking the permissions requested only by the removed
17741                        // package is successful and this causes a change in gids.
17742                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17743                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17744                                    userId);
17745                            if (userIdToKill == UserHandle.USER_ALL
17746                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17747                                // If gids changed for this user, kill all affected packages.
17748                                mHandler.post(new Runnable() {
17749                                    @Override
17750                                    public void run() {
17751                                        // This has to happen with no lock held.
17752                                        killApplication(deletedPs.name, deletedPs.appId,
17753                                                KILL_APP_REASON_GIDS_CHANGED);
17754                                    }
17755                                });
17756                                break;
17757                            }
17758                        }
17759                    }
17760                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17761                }
17762                // make sure to preserve per-user disabled state if this removal was just
17763                // a downgrade of a system app to the factory package
17764                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17765                    if (DEBUG_REMOVE) {
17766                        Slog.d(TAG, "Propagating install state across downgrade");
17767                    }
17768                    for (int userId : allUserHandles) {
17769                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17770                        if (DEBUG_REMOVE) {
17771                            Slog.d(TAG, "    user " + userId + " => " + installed);
17772                        }
17773                        if (installed != ps.getInstalled(userId)) {
17774                            installedStateChanged = true;
17775                        }
17776                        ps.setInstalled(installed, userId);
17777                    }
17778                }
17779            }
17780            // can downgrade to reader
17781            if (writeSettings) {
17782                // Save settings now
17783                mSettings.writeLPr();
17784            }
17785            if (installedStateChanged) {
17786                mSettings.writeKernelMappingLPr(ps);
17787            }
17788        }
17789        if (removedAppId != -1) {
17790            // A user ID was deleted here. Go through all users and remove it
17791            // from KeyStore.
17792            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17793        }
17794    }
17795
17796    static boolean locationIsPrivileged(String path) {
17797        try {
17798            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17799            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
17800            return path.startsWith(privilegedAppDir.getCanonicalPath())
17801                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath());
17802        } catch (IOException e) {
17803            Slog.e(TAG, "Unable to access code path " + path);
17804        }
17805        return false;
17806    }
17807
17808    static boolean locationIsOem(String path) {
17809        try {
17810            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
17811        } catch (IOException e) {
17812            Slog.e(TAG, "Unable to access code path " + path);
17813        }
17814        return false;
17815    }
17816
17817    static boolean locationIsVendor(String path) {
17818        try {
17819            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
17820        } catch (IOException e) {
17821            Slog.e(TAG, "Unable to access code path " + path);
17822        }
17823        return false;
17824    }
17825
17826    /*
17827     * Tries to delete system package.
17828     */
17829    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17830            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17831            boolean writeSettings) {
17832        if (deletedPs.parentPackageName != null) {
17833            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17834            return false;
17835        }
17836
17837        final boolean applyUserRestrictions
17838                = (allUserHandles != null) && (outInfo.origUsers != null);
17839        final PackageSetting disabledPs;
17840        // Confirm if the system package has been updated
17841        // An updated system app can be deleted. This will also have to restore
17842        // the system pkg from system partition
17843        // reader
17844        synchronized (mPackages) {
17845            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17846        }
17847
17848        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17849                + " disabledPs=" + disabledPs);
17850
17851        if (disabledPs == null) {
17852            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17853            return false;
17854        } else if (DEBUG_REMOVE) {
17855            Slog.d(TAG, "Deleting system pkg from data partition");
17856        }
17857
17858        if (DEBUG_REMOVE) {
17859            if (applyUserRestrictions) {
17860                Slog.d(TAG, "Remembering install states:");
17861                for (int userId : allUserHandles) {
17862                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17863                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17864                }
17865            }
17866        }
17867
17868        // Delete the updated package
17869        outInfo.isRemovedPackageSystemUpdate = true;
17870        if (outInfo.removedChildPackages != null) {
17871            final int childCount = (deletedPs.childPackageNames != null)
17872                    ? deletedPs.childPackageNames.size() : 0;
17873            for (int i = 0; i < childCount; i++) {
17874                String childPackageName = deletedPs.childPackageNames.get(i);
17875                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17876                        .contains(childPackageName)) {
17877                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17878                            childPackageName);
17879                    if (childInfo != null) {
17880                        childInfo.isRemovedPackageSystemUpdate = true;
17881                    }
17882                }
17883            }
17884        }
17885
17886        if (disabledPs.versionCode < deletedPs.versionCode) {
17887            // Delete data for downgrades
17888            flags &= ~PackageManager.DELETE_KEEP_DATA;
17889        } else {
17890            // Preserve data by setting flag
17891            flags |= PackageManager.DELETE_KEEP_DATA;
17892        }
17893
17894        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17895                outInfo, writeSettings, disabledPs.pkg);
17896        if (!ret) {
17897            return false;
17898        }
17899
17900        // writer
17901        synchronized (mPackages) {
17902            // NOTE: The system package always needs to be enabled; even if it's for
17903            // a compressed stub. If we don't, installing the system package fails
17904            // during scan [scanning checks the disabled packages]. We will reverse
17905            // this later, after we've "installed" the stub.
17906            // Reinstate the old system package
17907            enableSystemPackageLPw(disabledPs.pkg);
17908            // Remove any native libraries from the upgraded package.
17909            removeNativeBinariesLI(deletedPs);
17910        }
17911
17912        // Install the system package
17913        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17914        try {
17915            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
17916                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17917        } catch (PackageManagerException e) {
17918            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17919                    + e.getMessage());
17920            return false;
17921        } finally {
17922            if (disabledPs.pkg.isStub) {
17923                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17924            }
17925        }
17926        return true;
17927    }
17928
17929    /**
17930     * Installs a package that's already on the system partition.
17931     */
17932    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
17933            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17934            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17935                    throws PackageManagerException {
17936        @ParseFlags int parseFlags =
17937                mDefParseFlags
17938                | PackageParser.PARSE_MUST_BE_APK
17939                | PackageParser.PARSE_IS_SYSTEM_DIR;
17940        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17941        if (isPrivileged || locationIsPrivileged(codePathString)) {
17942            scanFlags |= SCAN_AS_PRIVILEGED;
17943        }
17944        if (locationIsOem(codePathString)) {
17945            scanFlags |= SCAN_AS_OEM;
17946        }
17947        if (locationIsVendor(codePathString)) {
17948            scanFlags |= SCAN_AS_VENDOR;
17949        }
17950
17951        final File codePath = new File(codePathString);
17952        final PackageParser.Package pkg =
17953                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17954
17955        try {
17956            // update shared libraries for the newly re-installed system package
17957            updateSharedLibrariesLPr(pkg, null);
17958        } catch (PackageManagerException e) {
17959            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17960        }
17961
17962        prepareAppDataAfterInstallLIF(pkg);
17963
17964        // writer
17965        synchronized (mPackages) {
17966            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17967
17968            // Propagate the permissions state as we do not want to drop on the floor
17969            // runtime permissions. The update permissions method below will take
17970            // care of removing obsolete permissions and grant install permissions.
17971            if (origPermissionState != null) {
17972                ps.getPermissionsState().copyFrom(origPermissionState);
17973            }
17974            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17975                    mPermissionCallback);
17976
17977            final boolean applyUserRestrictions
17978                    = (allUserHandles != null) && (origUserHandles != null);
17979            if (applyUserRestrictions) {
17980                boolean installedStateChanged = false;
17981                if (DEBUG_REMOVE) {
17982                    Slog.d(TAG, "Propagating install state across reinstall");
17983                }
17984                for (int userId : allUserHandles) {
17985                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17986                    if (DEBUG_REMOVE) {
17987                        Slog.d(TAG, "    user " + userId + " => " + installed);
17988                    }
17989                    if (installed != ps.getInstalled(userId)) {
17990                        installedStateChanged = true;
17991                    }
17992                    ps.setInstalled(installed, userId);
17993
17994                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17995                }
17996                // Regardless of writeSettings we need to ensure that this restriction
17997                // state propagation is persisted
17998                mSettings.writeAllUsersPackageRestrictionsLPr();
17999                if (installedStateChanged) {
18000                    mSettings.writeKernelMappingLPr(ps);
18001                }
18002            }
18003            // can downgrade to reader here
18004            if (writeSettings) {
18005                mSettings.writeLPr();
18006            }
18007        }
18008        return pkg;
18009    }
18010
18011    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18012            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18013            PackageRemovedInfo outInfo, boolean writeSettings,
18014            PackageParser.Package replacingPackage) {
18015        synchronized (mPackages) {
18016            if (outInfo != null) {
18017                outInfo.uid = ps.appId;
18018            }
18019
18020            if (outInfo != null && outInfo.removedChildPackages != null) {
18021                final int childCount = (ps.childPackageNames != null)
18022                        ? ps.childPackageNames.size() : 0;
18023                for (int i = 0; i < childCount; i++) {
18024                    String childPackageName = ps.childPackageNames.get(i);
18025                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18026                    if (childPs == null) {
18027                        return false;
18028                    }
18029                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18030                            childPackageName);
18031                    if (childInfo != null) {
18032                        childInfo.uid = childPs.appId;
18033                    }
18034                }
18035            }
18036        }
18037
18038        // Delete package data from internal structures and also remove data if flag is set
18039        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18040
18041        // Delete the child packages data
18042        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18043        for (int i = 0; i < childCount; i++) {
18044            PackageSetting childPs;
18045            synchronized (mPackages) {
18046                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18047            }
18048            if (childPs != null) {
18049                PackageRemovedInfo childOutInfo = (outInfo != null
18050                        && outInfo.removedChildPackages != null)
18051                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18052                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18053                        && (replacingPackage != null
18054                        && !replacingPackage.hasChildPackage(childPs.name))
18055                        ? flags & ~DELETE_KEEP_DATA : flags;
18056                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18057                        deleteFlags, writeSettings);
18058            }
18059        }
18060
18061        // Delete application code and resources only for parent packages
18062        if (ps.parentPackageName == null) {
18063            if (deleteCodeAndResources && (outInfo != null)) {
18064                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18065                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18066                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18067            }
18068        }
18069
18070        return true;
18071    }
18072
18073    @Override
18074    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18075            int userId) {
18076        mContext.enforceCallingOrSelfPermission(
18077                android.Manifest.permission.DELETE_PACKAGES, null);
18078        synchronized (mPackages) {
18079            // Cannot block uninstall of static shared libs as they are
18080            // considered a part of the using app (emulating static linking).
18081            // Also static libs are installed always on internal storage.
18082            PackageParser.Package pkg = mPackages.get(packageName);
18083            if (pkg != null && pkg.staticSharedLibName != null) {
18084                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18085                        + " providing static shared library: " + pkg.staticSharedLibName);
18086                return false;
18087            }
18088            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18089            mSettings.writePackageRestrictionsLPr(userId);
18090        }
18091        return true;
18092    }
18093
18094    @Override
18095    public boolean getBlockUninstallForUser(String packageName, int userId) {
18096        synchronized (mPackages) {
18097            final PackageSetting ps = mSettings.mPackages.get(packageName);
18098            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18099                return false;
18100            }
18101            return mSettings.getBlockUninstallLPr(userId, packageName);
18102        }
18103    }
18104
18105    @Override
18106    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18107        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18108        synchronized (mPackages) {
18109            PackageSetting ps = mSettings.mPackages.get(packageName);
18110            if (ps == null) {
18111                Log.w(TAG, "Package doesn't exist: " + packageName);
18112                return false;
18113            }
18114            if (systemUserApp) {
18115                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18116            } else {
18117                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18118            }
18119            mSettings.writeLPr();
18120        }
18121        return true;
18122    }
18123
18124    /*
18125     * This method handles package deletion in general
18126     */
18127    private boolean deletePackageLIF(String packageName, UserHandle user,
18128            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18129            PackageRemovedInfo outInfo, boolean writeSettings,
18130            PackageParser.Package replacingPackage) {
18131        if (packageName == null) {
18132            Slog.w(TAG, "Attempt to delete null packageName.");
18133            return false;
18134        }
18135
18136        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18137
18138        PackageSetting ps;
18139        synchronized (mPackages) {
18140            ps = mSettings.mPackages.get(packageName);
18141            if (ps == null) {
18142                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18143                return false;
18144            }
18145
18146            if (ps.parentPackageName != null && (!isSystemApp(ps)
18147                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18148                if (DEBUG_REMOVE) {
18149                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18150                            + ((user == null) ? UserHandle.USER_ALL : user));
18151                }
18152                final int removedUserId = (user != null) ? user.getIdentifier()
18153                        : UserHandle.USER_ALL;
18154                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18155                    return false;
18156                }
18157                markPackageUninstalledForUserLPw(ps, user);
18158                scheduleWritePackageRestrictionsLocked(user);
18159                return true;
18160            }
18161        }
18162
18163        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18164                && user.getIdentifier() != UserHandle.USER_ALL)) {
18165            // The caller is asking that the package only be deleted for a single
18166            // user.  To do this, we just mark its uninstalled state and delete
18167            // its data. If this is a system app, we only allow this to happen if
18168            // they have set the special DELETE_SYSTEM_APP which requests different
18169            // semantics than normal for uninstalling system apps.
18170            markPackageUninstalledForUserLPw(ps, user);
18171
18172            if (!isSystemApp(ps)) {
18173                // Do not uninstall the APK if an app should be cached
18174                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18175                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18176                    // Other user still have this package installed, so all
18177                    // we need to do is clear this user's data and save that
18178                    // it is uninstalled.
18179                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18180                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18181                        return false;
18182                    }
18183                    scheduleWritePackageRestrictionsLocked(user);
18184                    return true;
18185                } else {
18186                    // We need to set it back to 'installed' so the uninstall
18187                    // broadcasts will be sent correctly.
18188                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18189                    ps.setInstalled(true, user.getIdentifier());
18190                    mSettings.writeKernelMappingLPr(ps);
18191                }
18192            } else {
18193                // This is a system app, so we assume that the
18194                // other users still have this package installed, so all
18195                // we need to do is clear this user's data and save that
18196                // it is uninstalled.
18197                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18198                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18199                    return false;
18200                }
18201                scheduleWritePackageRestrictionsLocked(user);
18202                return true;
18203            }
18204        }
18205
18206        // If we are deleting a composite package for all users, keep track
18207        // of result for each child.
18208        if (ps.childPackageNames != null && outInfo != null) {
18209            synchronized (mPackages) {
18210                final int childCount = ps.childPackageNames.size();
18211                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18212                for (int i = 0; i < childCount; i++) {
18213                    String childPackageName = ps.childPackageNames.get(i);
18214                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18215                    childInfo.removedPackage = childPackageName;
18216                    childInfo.installerPackageName = ps.installerPackageName;
18217                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18218                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18219                    if (childPs != null) {
18220                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18221                    }
18222                }
18223            }
18224        }
18225
18226        boolean ret = false;
18227        if (isSystemApp(ps)) {
18228            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18229            // When an updated system application is deleted we delete the existing resources
18230            // as well and fall back to existing code in system partition
18231            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18232        } else {
18233            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18234            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18235                    outInfo, writeSettings, replacingPackage);
18236        }
18237
18238        // Take a note whether we deleted the package for all users
18239        if (outInfo != null) {
18240            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18241            if (outInfo.removedChildPackages != null) {
18242                synchronized (mPackages) {
18243                    final int childCount = outInfo.removedChildPackages.size();
18244                    for (int i = 0; i < childCount; i++) {
18245                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18246                        if (childInfo != null) {
18247                            childInfo.removedForAllUsers = mPackages.get(
18248                                    childInfo.removedPackage) == null;
18249                        }
18250                    }
18251                }
18252            }
18253            // If we uninstalled an update to a system app there may be some
18254            // child packages that appeared as they are declared in the system
18255            // app but were not declared in the update.
18256            if (isSystemApp(ps)) {
18257                synchronized (mPackages) {
18258                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18259                    final int childCount = (updatedPs.childPackageNames != null)
18260                            ? updatedPs.childPackageNames.size() : 0;
18261                    for (int i = 0; i < childCount; i++) {
18262                        String childPackageName = updatedPs.childPackageNames.get(i);
18263                        if (outInfo.removedChildPackages == null
18264                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18265                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18266                            if (childPs == null) {
18267                                continue;
18268                            }
18269                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18270                            installRes.name = childPackageName;
18271                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18272                            installRes.pkg = mPackages.get(childPackageName);
18273                            installRes.uid = childPs.pkg.applicationInfo.uid;
18274                            if (outInfo.appearedChildPackages == null) {
18275                                outInfo.appearedChildPackages = new ArrayMap<>();
18276                            }
18277                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18278                        }
18279                    }
18280                }
18281            }
18282        }
18283
18284        return ret;
18285    }
18286
18287    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18288        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18289                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18290        for (int nextUserId : userIds) {
18291            if (DEBUG_REMOVE) {
18292                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18293            }
18294            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18295                    false /*installed*/,
18296                    true /*stopped*/,
18297                    true /*notLaunched*/,
18298                    false /*hidden*/,
18299                    false /*suspended*/,
18300                    false /*instantApp*/,
18301                    false /*virtualPreload*/,
18302                    null /*lastDisableAppCaller*/,
18303                    null /*enabledComponents*/,
18304                    null /*disabledComponents*/,
18305                    ps.readUserState(nextUserId).domainVerificationStatus,
18306                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18307        }
18308        mSettings.writeKernelMappingLPr(ps);
18309    }
18310
18311    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18312            PackageRemovedInfo outInfo) {
18313        final PackageParser.Package pkg;
18314        synchronized (mPackages) {
18315            pkg = mPackages.get(ps.name);
18316        }
18317
18318        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18319                : new int[] {userId};
18320        for (int nextUserId : userIds) {
18321            if (DEBUG_REMOVE) {
18322                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18323                        + nextUserId);
18324            }
18325
18326            destroyAppDataLIF(pkg, userId,
18327                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18328            destroyAppProfilesLIF(pkg, userId);
18329            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18330            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18331            schedulePackageCleaning(ps.name, nextUserId, false);
18332            synchronized (mPackages) {
18333                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18334                    scheduleWritePackageRestrictionsLocked(nextUserId);
18335                }
18336                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18337            }
18338        }
18339
18340        if (outInfo != null) {
18341            outInfo.removedPackage = ps.name;
18342            outInfo.installerPackageName = ps.installerPackageName;
18343            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18344            outInfo.removedAppId = ps.appId;
18345            outInfo.removedUsers = userIds;
18346            outInfo.broadcastUsers = userIds;
18347        }
18348
18349        return true;
18350    }
18351
18352    private final class ClearStorageConnection implements ServiceConnection {
18353        IMediaContainerService mContainerService;
18354
18355        @Override
18356        public void onServiceConnected(ComponentName name, IBinder service) {
18357            synchronized (this) {
18358                mContainerService = IMediaContainerService.Stub
18359                        .asInterface(Binder.allowBlocking(service));
18360                notifyAll();
18361            }
18362        }
18363
18364        @Override
18365        public void onServiceDisconnected(ComponentName name) {
18366        }
18367    }
18368
18369    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18370        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18371
18372        final boolean mounted;
18373        if (Environment.isExternalStorageEmulated()) {
18374            mounted = true;
18375        } else {
18376            final String status = Environment.getExternalStorageState();
18377
18378            mounted = status.equals(Environment.MEDIA_MOUNTED)
18379                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18380        }
18381
18382        if (!mounted) {
18383            return;
18384        }
18385
18386        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18387        int[] users;
18388        if (userId == UserHandle.USER_ALL) {
18389            users = sUserManager.getUserIds();
18390        } else {
18391            users = new int[] { userId };
18392        }
18393        final ClearStorageConnection conn = new ClearStorageConnection();
18394        if (mContext.bindServiceAsUser(
18395                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18396            try {
18397                for (int curUser : users) {
18398                    long timeout = SystemClock.uptimeMillis() + 5000;
18399                    synchronized (conn) {
18400                        long now;
18401                        while (conn.mContainerService == null &&
18402                                (now = SystemClock.uptimeMillis()) < timeout) {
18403                            try {
18404                                conn.wait(timeout - now);
18405                            } catch (InterruptedException e) {
18406                            }
18407                        }
18408                    }
18409                    if (conn.mContainerService == null) {
18410                        return;
18411                    }
18412
18413                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18414                    clearDirectory(conn.mContainerService,
18415                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18416                    if (allData) {
18417                        clearDirectory(conn.mContainerService,
18418                                userEnv.buildExternalStorageAppDataDirs(packageName));
18419                        clearDirectory(conn.mContainerService,
18420                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18421                    }
18422                }
18423            } finally {
18424                mContext.unbindService(conn);
18425            }
18426        }
18427    }
18428
18429    @Override
18430    public void clearApplicationProfileData(String packageName) {
18431        enforceSystemOrRoot("Only the system can clear all profile data");
18432
18433        final PackageParser.Package pkg;
18434        synchronized (mPackages) {
18435            pkg = mPackages.get(packageName);
18436        }
18437
18438        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18439            synchronized (mInstallLock) {
18440                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18441            }
18442        }
18443    }
18444
18445    @Override
18446    public void clearApplicationUserData(final String packageName,
18447            final IPackageDataObserver observer, final int userId) {
18448        mContext.enforceCallingOrSelfPermission(
18449                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18450
18451        final int callingUid = Binder.getCallingUid();
18452        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18453                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18454
18455        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18456        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18457        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18458            throw new SecurityException("Cannot clear data for a protected package: "
18459                    + packageName);
18460        }
18461        // Queue up an async operation since the package deletion may take a little while.
18462        mHandler.post(new Runnable() {
18463            public void run() {
18464                mHandler.removeCallbacks(this);
18465                final boolean succeeded;
18466                if (!filterApp) {
18467                    try (PackageFreezer freezer = freezePackage(packageName,
18468                            "clearApplicationUserData")) {
18469                        synchronized (mInstallLock) {
18470                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18471                        }
18472                        clearExternalStorageDataSync(packageName, userId, true);
18473                        synchronized (mPackages) {
18474                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18475                                    packageName, userId);
18476                        }
18477                    }
18478                    if (succeeded) {
18479                        // invoke DeviceStorageMonitor's update method to clear any notifications
18480                        DeviceStorageMonitorInternal dsm = LocalServices
18481                                .getService(DeviceStorageMonitorInternal.class);
18482                        if (dsm != null) {
18483                            dsm.checkMemory();
18484                        }
18485                    }
18486                } else {
18487                    succeeded = false;
18488                }
18489                if (observer != null) {
18490                    try {
18491                        observer.onRemoveCompleted(packageName, succeeded);
18492                    } catch (RemoteException e) {
18493                        Log.i(TAG, "Observer no longer exists.");
18494                    }
18495                } //end if observer
18496            } //end run
18497        });
18498    }
18499
18500    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18501        if (packageName == null) {
18502            Slog.w(TAG, "Attempt to delete null packageName.");
18503            return false;
18504        }
18505
18506        // Try finding details about the requested package
18507        PackageParser.Package pkg;
18508        synchronized (mPackages) {
18509            pkg = mPackages.get(packageName);
18510            if (pkg == null) {
18511                final PackageSetting ps = mSettings.mPackages.get(packageName);
18512                if (ps != null) {
18513                    pkg = ps.pkg;
18514                }
18515            }
18516
18517            if (pkg == null) {
18518                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18519                return false;
18520            }
18521
18522            PackageSetting ps = (PackageSetting) pkg.mExtras;
18523            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18524        }
18525
18526        clearAppDataLIF(pkg, userId,
18527                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18528
18529        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18530        removeKeystoreDataIfNeeded(userId, appId);
18531
18532        UserManagerInternal umInternal = getUserManagerInternal();
18533        final int flags;
18534        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18535            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18536        } else if (umInternal.isUserRunning(userId)) {
18537            flags = StorageManager.FLAG_STORAGE_DE;
18538        } else {
18539            flags = 0;
18540        }
18541        prepareAppDataContentsLIF(pkg, userId, flags);
18542
18543        return true;
18544    }
18545
18546    /**
18547     * Reverts user permission state changes (permissions and flags) in
18548     * all packages for a given user.
18549     *
18550     * @param userId The device user for which to do a reset.
18551     */
18552    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18553        final int packageCount = mPackages.size();
18554        for (int i = 0; i < packageCount; i++) {
18555            PackageParser.Package pkg = mPackages.valueAt(i);
18556            PackageSetting ps = (PackageSetting) pkg.mExtras;
18557            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18558        }
18559    }
18560
18561    private void resetNetworkPolicies(int userId) {
18562        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18563    }
18564
18565    /**
18566     * Reverts user permission state changes (permissions and flags).
18567     *
18568     * @param ps The package for which to reset.
18569     * @param userId The device user for which to do a reset.
18570     */
18571    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18572            final PackageSetting ps, final int userId) {
18573        if (ps.pkg == null) {
18574            return;
18575        }
18576
18577        // These are flags that can change base on user actions.
18578        final int userSettableMask = FLAG_PERMISSION_USER_SET
18579                | FLAG_PERMISSION_USER_FIXED
18580                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18581                | FLAG_PERMISSION_REVIEW_REQUIRED;
18582
18583        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18584                | FLAG_PERMISSION_POLICY_FIXED;
18585
18586        boolean writeInstallPermissions = false;
18587        boolean writeRuntimePermissions = false;
18588
18589        final int permissionCount = ps.pkg.requestedPermissions.size();
18590        for (int i = 0; i < permissionCount; i++) {
18591            final String permName = ps.pkg.requestedPermissions.get(i);
18592            final BasePermission bp =
18593                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18594            if (bp == null) {
18595                continue;
18596            }
18597
18598            // If shared user we just reset the state to which only this app contributed.
18599            if (ps.sharedUser != null) {
18600                boolean used = false;
18601                final int packageCount = ps.sharedUser.packages.size();
18602                for (int j = 0; j < packageCount; j++) {
18603                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18604                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18605                            && pkg.pkg.requestedPermissions.contains(permName)) {
18606                        used = true;
18607                        break;
18608                    }
18609                }
18610                if (used) {
18611                    continue;
18612                }
18613            }
18614
18615            final PermissionsState permissionsState = ps.getPermissionsState();
18616
18617            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18618
18619            // Always clear the user settable flags.
18620            final boolean hasInstallState =
18621                    permissionsState.getInstallPermissionState(permName) != null;
18622            // If permission review is enabled and this is a legacy app, mark the
18623            // permission as requiring a review as this is the initial state.
18624            int flags = 0;
18625            if (mSettings.mPermissions.mPermissionReviewRequired
18626                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18627                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18628            }
18629            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18630                if (hasInstallState) {
18631                    writeInstallPermissions = true;
18632                } else {
18633                    writeRuntimePermissions = true;
18634                }
18635            }
18636
18637            // Below is only runtime permission handling.
18638            if (!bp.isRuntime()) {
18639                continue;
18640            }
18641
18642            // Never clobber system or policy.
18643            if ((oldFlags & policyOrSystemFlags) != 0) {
18644                continue;
18645            }
18646
18647            // If this permission was granted by default, make sure it is.
18648            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18649                if (permissionsState.grantRuntimePermission(bp, userId)
18650                        != PERMISSION_OPERATION_FAILURE) {
18651                    writeRuntimePermissions = true;
18652                }
18653            // If permission review is enabled the permissions for a legacy apps
18654            // are represented as constantly granted runtime ones, so don't revoke.
18655            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18656                // Otherwise, reset the permission.
18657                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18658                switch (revokeResult) {
18659                    case PERMISSION_OPERATION_SUCCESS:
18660                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18661                        writeRuntimePermissions = true;
18662                        final int appId = ps.appId;
18663                        mHandler.post(new Runnable() {
18664                            @Override
18665                            public void run() {
18666                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18667                            }
18668                        });
18669                    } break;
18670                }
18671            }
18672        }
18673
18674        // Synchronously write as we are taking permissions away.
18675        if (writeRuntimePermissions) {
18676            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18677        }
18678
18679        // Synchronously write as we are taking permissions away.
18680        if (writeInstallPermissions) {
18681            mSettings.writeLPr();
18682        }
18683    }
18684
18685    /**
18686     * Remove entries from the keystore daemon. Will only remove it if the
18687     * {@code appId} is valid.
18688     */
18689    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18690        if (appId < 0) {
18691            return;
18692        }
18693
18694        final KeyStore keyStore = KeyStore.getInstance();
18695        if (keyStore != null) {
18696            if (userId == UserHandle.USER_ALL) {
18697                for (final int individual : sUserManager.getUserIds()) {
18698                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18699                }
18700            } else {
18701                keyStore.clearUid(UserHandle.getUid(userId, appId));
18702            }
18703        } else {
18704            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18705        }
18706    }
18707
18708    @Override
18709    public void deleteApplicationCacheFiles(final String packageName,
18710            final IPackageDataObserver observer) {
18711        final int userId = UserHandle.getCallingUserId();
18712        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18713    }
18714
18715    @Override
18716    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18717            final IPackageDataObserver observer) {
18718        final int callingUid = Binder.getCallingUid();
18719        mContext.enforceCallingOrSelfPermission(
18720                android.Manifest.permission.DELETE_CACHE_FILES, null);
18721        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18722                /* requireFullPermission= */ true, /* checkShell= */ false,
18723                "delete application cache files");
18724        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18725                android.Manifest.permission.ACCESS_INSTANT_APPS);
18726
18727        final PackageParser.Package pkg;
18728        synchronized (mPackages) {
18729            pkg = mPackages.get(packageName);
18730        }
18731
18732        // Queue up an async operation since the package deletion may take a little while.
18733        mHandler.post(new Runnable() {
18734            public void run() {
18735                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18736                boolean doClearData = true;
18737                if (ps != null) {
18738                    final boolean targetIsInstantApp =
18739                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18740                    doClearData = !targetIsInstantApp
18741                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18742                }
18743                if (doClearData) {
18744                    synchronized (mInstallLock) {
18745                        final int flags = StorageManager.FLAG_STORAGE_DE
18746                                | StorageManager.FLAG_STORAGE_CE;
18747                        // We're only clearing cache files, so we don't care if the
18748                        // app is unfrozen and still able to run
18749                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18750                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18751                    }
18752                    clearExternalStorageDataSync(packageName, userId, false);
18753                }
18754                if (observer != null) {
18755                    try {
18756                        observer.onRemoveCompleted(packageName, true);
18757                    } catch (RemoteException e) {
18758                        Log.i(TAG, "Observer no longer exists.");
18759                    }
18760                }
18761            }
18762        });
18763    }
18764
18765    @Override
18766    public void getPackageSizeInfo(final String packageName, int userHandle,
18767            final IPackageStatsObserver observer) {
18768        throw new UnsupportedOperationException(
18769                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18770    }
18771
18772    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18773        final PackageSetting ps;
18774        synchronized (mPackages) {
18775            ps = mSettings.mPackages.get(packageName);
18776            if (ps == null) {
18777                Slog.w(TAG, "Failed to find settings for " + packageName);
18778                return false;
18779            }
18780        }
18781
18782        final String[] packageNames = { packageName };
18783        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18784        final String[] codePaths = { ps.codePathString };
18785
18786        try {
18787            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18788                    ps.appId, ceDataInodes, codePaths, stats);
18789
18790            // For now, ignore code size of packages on system partition
18791            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18792                stats.codeSize = 0;
18793            }
18794
18795            // External clients expect these to be tracked separately
18796            stats.dataSize -= stats.cacheSize;
18797
18798        } catch (InstallerException e) {
18799            Slog.w(TAG, String.valueOf(e));
18800            return false;
18801        }
18802
18803        return true;
18804    }
18805
18806    private int getUidTargetSdkVersionLockedLPr(int uid) {
18807        Object obj = mSettings.getUserIdLPr(uid);
18808        if (obj instanceof SharedUserSetting) {
18809            final SharedUserSetting sus = (SharedUserSetting) obj;
18810            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18811            final Iterator<PackageSetting> it = sus.packages.iterator();
18812            while (it.hasNext()) {
18813                final PackageSetting ps = it.next();
18814                if (ps.pkg != null) {
18815                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18816                    if (v < vers) vers = v;
18817                }
18818            }
18819            return vers;
18820        } else if (obj instanceof PackageSetting) {
18821            final PackageSetting ps = (PackageSetting) obj;
18822            if (ps.pkg != null) {
18823                return ps.pkg.applicationInfo.targetSdkVersion;
18824            }
18825        }
18826        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18827    }
18828
18829    @Override
18830    public void addPreferredActivity(IntentFilter filter, int match,
18831            ComponentName[] set, ComponentName activity, int userId) {
18832        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18833                "Adding preferred");
18834    }
18835
18836    private void addPreferredActivityInternal(IntentFilter filter, int match,
18837            ComponentName[] set, ComponentName activity, boolean always, int userId,
18838            String opname) {
18839        // writer
18840        int callingUid = Binder.getCallingUid();
18841        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18842                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18843        if (filter.countActions() == 0) {
18844            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18845            return;
18846        }
18847        synchronized (mPackages) {
18848            if (mContext.checkCallingOrSelfPermission(
18849                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18850                    != PackageManager.PERMISSION_GRANTED) {
18851                if (getUidTargetSdkVersionLockedLPr(callingUid)
18852                        < Build.VERSION_CODES.FROYO) {
18853                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18854                            + callingUid);
18855                    return;
18856                }
18857                mContext.enforceCallingOrSelfPermission(
18858                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18859            }
18860
18861            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18862            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18863                    + userId + ":");
18864            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18865            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18866            scheduleWritePackageRestrictionsLocked(userId);
18867            postPreferredActivityChangedBroadcast(userId);
18868        }
18869    }
18870
18871    private void postPreferredActivityChangedBroadcast(int userId) {
18872        mHandler.post(() -> {
18873            final IActivityManager am = ActivityManager.getService();
18874            if (am == null) {
18875                return;
18876            }
18877
18878            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18879            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18880            try {
18881                am.broadcastIntent(null, intent, null, null,
18882                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18883                        null, false, false, userId);
18884            } catch (RemoteException e) {
18885            }
18886        });
18887    }
18888
18889    @Override
18890    public void replacePreferredActivity(IntentFilter filter, int match,
18891            ComponentName[] set, ComponentName activity, int userId) {
18892        if (filter.countActions() != 1) {
18893            throw new IllegalArgumentException(
18894                    "replacePreferredActivity expects filter to have only 1 action.");
18895        }
18896        if (filter.countDataAuthorities() != 0
18897                || filter.countDataPaths() != 0
18898                || filter.countDataSchemes() > 1
18899                || filter.countDataTypes() != 0) {
18900            throw new IllegalArgumentException(
18901                    "replacePreferredActivity expects filter to have no data authorities, " +
18902                    "paths, or types; and at most one scheme.");
18903        }
18904
18905        final int callingUid = Binder.getCallingUid();
18906        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18907                true /* requireFullPermission */, false /* checkShell */,
18908                "replace preferred activity");
18909        synchronized (mPackages) {
18910            if (mContext.checkCallingOrSelfPermission(
18911                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18912                    != PackageManager.PERMISSION_GRANTED) {
18913                if (getUidTargetSdkVersionLockedLPr(callingUid)
18914                        < Build.VERSION_CODES.FROYO) {
18915                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18916                            + Binder.getCallingUid());
18917                    return;
18918                }
18919                mContext.enforceCallingOrSelfPermission(
18920                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18921            }
18922
18923            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18924            if (pir != null) {
18925                // Get all of the existing entries that exactly match this filter.
18926                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18927                if (existing != null && existing.size() == 1) {
18928                    PreferredActivity cur = existing.get(0);
18929                    if (DEBUG_PREFERRED) {
18930                        Slog.i(TAG, "Checking replace of preferred:");
18931                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18932                        if (!cur.mPref.mAlways) {
18933                            Slog.i(TAG, "  -- CUR; not mAlways!");
18934                        } else {
18935                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18936                            Slog.i(TAG, "  -- CUR: mSet="
18937                                    + Arrays.toString(cur.mPref.mSetComponents));
18938                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18939                            Slog.i(TAG, "  -- NEW: mMatch="
18940                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18941                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18942                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18943                        }
18944                    }
18945                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18946                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18947                            && cur.mPref.sameSet(set)) {
18948                        // Setting the preferred activity to what it happens to be already
18949                        if (DEBUG_PREFERRED) {
18950                            Slog.i(TAG, "Replacing with same preferred activity "
18951                                    + cur.mPref.mShortComponent + " for user "
18952                                    + userId + ":");
18953                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18954                        }
18955                        return;
18956                    }
18957                }
18958
18959                if (existing != null) {
18960                    if (DEBUG_PREFERRED) {
18961                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18962                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18963                    }
18964                    for (int i = 0; i < existing.size(); i++) {
18965                        PreferredActivity pa = existing.get(i);
18966                        if (DEBUG_PREFERRED) {
18967                            Slog.i(TAG, "Removing existing preferred activity "
18968                                    + pa.mPref.mComponent + ":");
18969                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18970                        }
18971                        pir.removeFilter(pa);
18972                    }
18973                }
18974            }
18975            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18976                    "Replacing preferred");
18977        }
18978    }
18979
18980    @Override
18981    public void clearPackagePreferredActivities(String packageName) {
18982        final int callingUid = Binder.getCallingUid();
18983        if (getInstantAppPackageName(callingUid) != null) {
18984            return;
18985        }
18986        // writer
18987        synchronized (mPackages) {
18988            PackageParser.Package pkg = mPackages.get(packageName);
18989            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18990                if (mContext.checkCallingOrSelfPermission(
18991                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18992                        != PackageManager.PERMISSION_GRANTED) {
18993                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18994                            < Build.VERSION_CODES.FROYO) {
18995                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18996                                + callingUid);
18997                        return;
18998                    }
18999                    mContext.enforceCallingOrSelfPermission(
19000                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19001                }
19002            }
19003            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19004            if (ps != null
19005                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19006                return;
19007            }
19008            int user = UserHandle.getCallingUserId();
19009            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19010                scheduleWritePackageRestrictionsLocked(user);
19011            }
19012        }
19013    }
19014
19015    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19016    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19017        ArrayList<PreferredActivity> removed = null;
19018        boolean changed = false;
19019        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19020            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19021            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19022            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19023                continue;
19024            }
19025            Iterator<PreferredActivity> it = pir.filterIterator();
19026            while (it.hasNext()) {
19027                PreferredActivity pa = it.next();
19028                // Mark entry for removal only if it matches the package name
19029                // and the entry is of type "always".
19030                if (packageName == null ||
19031                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19032                                && pa.mPref.mAlways)) {
19033                    if (removed == null) {
19034                        removed = new ArrayList<PreferredActivity>();
19035                    }
19036                    removed.add(pa);
19037                }
19038            }
19039            if (removed != null) {
19040                for (int j=0; j<removed.size(); j++) {
19041                    PreferredActivity pa = removed.get(j);
19042                    pir.removeFilter(pa);
19043                }
19044                changed = true;
19045            }
19046        }
19047        if (changed) {
19048            postPreferredActivityChangedBroadcast(userId);
19049        }
19050        return changed;
19051    }
19052
19053    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19054    private void clearIntentFilterVerificationsLPw(int userId) {
19055        final int packageCount = mPackages.size();
19056        for (int i = 0; i < packageCount; i++) {
19057            PackageParser.Package pkg = mPackages.valueAt(i);
19058            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19059        }
19060    }
19061
19062    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19063    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19064        if (userId == UserHandle.USER_ALL) {
19065            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19066                    sUserManager.getUserIds())) {
19067                for (int oneUserId : sUserManager.getUserIds()) {
19068                    scheduleWritePackageRestrictionsLocked(oneUserId);
19069                }
19070            }
19071        } else {
19072            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19073                scheduleWritePackageRestrictionsLocked(userId);
19074            }
19075        }
19076    }
19077
19078    /** Clears state for all users, and touches intent filter verification policy */
19079    void clearDefaultBrowserIfNeeded(String packageName) {
19080        for (int oneUserId : sUserManager.getUserIds()) {
19081            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19082        }
19083    }
19084
19085    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19086        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19087        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19088            if (packageName.equals(defaultBrowserPackageName)) {
19089                setDefaultBrowserPackageName(null, userId);
19090            }
19091        }
19092    }
19093
19094    @Override
19095    public void resetApplicationPreferences(int userId) {
19096        mContext.enforceCallingOrSelfPermission(
19097                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19098        final long identity = Binder.clearCallingIdentity();
19099        // writer
19100        try {
19101            synchronized (mPackages) {
19102                clearPackagePreferredActivitiesLPw(null, userId);
19103                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19104                // TODO: We have to reset the default SMS and Phone. This requires
19105                // significant refactoring to keep all default apps in the package
19106                // manager (cleaner but more work) or have the services provide
19107                // callbacks to the package manager to request a default app reset.
19108                applyFactoryDefaultBrowserLPw(userId);
19109                clearIntentFilterVerificationsLPw(userId);
19110                primeDomainVerificationsLPw(userId);
19111                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19112                scheduleWritePackageRestrictionsLocked(userId);
19113            }
19114            resetNetworkPolicies(userId);
19115        } finally {
19116            Binder.restoreCallingIdentity(identity);
19117        }
19118    }
19119
19120    @Override
19121    public int getPreferredActivities(List<IntentFilter> outFilters,
19122            List<ComponentName> outActivities, String packageName) {
19123        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19124            return 0;
19125        }
19126        int num = 0;
19127        final int userId = UserHandle.getCallingUserId();
19128        // reader
19129        synchronized (mPackages) {
19130            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19131            if (pir != null) {
19132                final Iterator<PreferredActivity> it = pir.filterIterator();
19133                while (it.hasNext()) {
19134                    final PreferredActivity pa = it.next();
19135                    if (packageName == null
19136                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19137                                    && pa.mPref.mAlways)) {
19138                        if (outFilters != null) {
19139                            outFilters.add(new IntentFilter(pa));
19140                        }
19141                        if (outActivities != null) {
19142                            outActivities.add(pa.mPref.mComponent);
19143                        }
19144                    }
19145                }
19146            }
19147        }
19148
19149        return num;
19150    }
19151
19152    @Override
19153    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19154            int userId) {
19155        int callingUid = Binder.getCallingUid();
19156        if (callingUid != Process.SYSTEM_UID) {
19157            throw new SecurityException(
19158                    "addPersistentPreferredActivity can only be run by the system");
19159        }
19160        if (filter.countActions() == 0) {
19161            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19162            return;
19163        }
19164        synchronized (mPackages) {
19165            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19166                    ":");
19167            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19168            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19169                    new PersistentPreferredActivity(filter, activity));
19170            scheduleWritePackageRestrictionsLocked(userId);
19171            postPreferredActivityChangedBroadcast(userId);
19172        }
19173    }
19174
19175    @Override
19176    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19177        int callingUid = Binder.getCallingUid();
19178        if (callingUid != Process.SYSTEM_UID) {
19179            throw new SecurityException(
19180                    "clearPackagePersistentPreferredActivities can only be run by the system");
19181        }
19182        ArrayList<PersistentPreferredActivity> removed = null;
19183        boolean changed = false;
19184        synchronized (mPackages) {
19185            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19186                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19187                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19188                        .valueAt(i);
19189                if (userId != thisUserId) {
19190                    continue;
19191                }
19192                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19193                while (it.hasNext()) {
19194                    PersistentPreferredActivity ppa = it.next();
19195                    // Mark entry for removal only if it matches the package name.
19196                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19197                        if (removed == null) {
19198                            removed = new ArrayList<PersistentPreferredActivity>();
19199                        }
19200                        removed.add(ppa);
19201                    }
19202                }
19203                if (removed != null) {
19204                    for (int j=0; j<removed.size(); j++) {
19205                        PersistentPreferredActivity ppa = removed.get(j);
19206                        ppir.removeFilter(ppa);
19207                    }
19208                    changed = true;
19209                }
19210            }
19211
19212            if (changed) {
19213                scheduleWritePackageRestrictionsLocked(userId);
19214                postPreferredActivityChangedBroadcast(userId);
19215            }
19216        }
19217    }
19218
19219    /**
19220     * Common machinery for picking apart a restored XML blob and passing
19221     * it to a caller-supplied functor to be applied to the running system.
19222     */
19223    private void restoreFromXml(XmlPullParser parser, int userId,
19224            String expectedStartTag, BlobXmlRestorer functor)
19225            throws IOException, XmlPullParserException {
19226        int type;
19227        while ((type = parser.next()) != XmlPullParser.START_TAG
19228                && type != XmlPullParser.END_DOCUMENT) {
19229        }
19230        if (type != XmlPullParser.START_TAG) {
19231            // oops didn't find a start tag?!
19232            if (DEBUG_BACKUP) {
19233                Slog.e(TAG, "Didn't find start tag during restore");
19234            }
19235            return;
19236        }
19237Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19238        // this is supposed to be TAG_PREFERRED_BACKUP
19239        if (!expectedStartTag.equals(parser.getName())) {
19240            if (DEBUG_BACKUP) {
19241                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19242            }
19243            return;
19244        }
19245
19246        // skip interfering stuff, then we're aligned with the backing implementation
19247        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19248Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19249        functor.apply(parser, userId);
19250    }
19251
19252    private interface BlobXmlRestorer {
19253        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19254    }
19255
19256    /**
19257     * Non-Binder method, support for the backup/restore mechanism: write the
19258     * full set of preferred activities in its canonical XML format.  Returns the
19259     * XML output as a byte array, or null if there is none.
19260     */
19261    @Override
19262    public byte[] getPreferredActivityBackup(int userId) {
19263        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19264            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19265        }
19266
19267        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19268        try {
19269            final XmlSerializer serializer = new FastXmlSerializer();
19270            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19271            serializer.startDocument(null, true);
19272            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19273
19274            synchronized (mPackages) {
19275                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19276            }
19277
19278            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19279            serializer.endDocument();
19280            serializer.flush();
19281        } catch (Exception e) {
19282            if (DEBUG_BACKUP) {
19283                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19284            }
19285            return null;
19286        }
19287
19288        return dataStream.toByteArray();
19289    }
19290
19291    @Override
19292    public void restorePreferredActivities(byte[] backup, int userId) {
19293        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19294            throw new SecurityException("Only the system may call restorePreferredActivities()");
19295        }
19296
19297        try {
19298            final XmlPullParser parser = Xml.newPullParser();
19299            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19300            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19301                    new BlobXmlRestorer() {
19302                        @Override
19303                        public void apply(XmlPullParser parser, int userId)
19304                                throws XmlPullParserException, IOException {
19305                            synchronized (mPackages) {
19306                                mSettings.readPreferredActivitiesLPw(parser, userId);
19307                            }
19308                        }
19309                    } );
19310        } catch (Exception e) {
19311            if (DEBUG_BACKUP) {
19312                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19313            }
19314        }
19315    }
19316
19317    /**
19318     * Non-Binder method, support for the backup/restore mechanism: write the
19319     * default browser (etc) settings in its canonical XML format.  Returns the default
19320     * browser XML representation as a byte array, or null if there is none.
19321     */
19322    @Override
19323    public byte[] getDefaultAppsBackup(int userId) {
19324        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19325            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19326        }
19327
19328        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19329        try {
19330            final XmlSerializer serializer = new FastXmlSerializer();
19331            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19332            serializer.startDocument(null, true);
19333            serializer.startTag(null, TAG_DEFAULT_APPS);
19334
19335            synchronized (mPackages) {
19336                mSettings.writeDefaultAppsLPr(serializer, userId);
19337            }
19338
19339            serializer.endTag(null, TAG_DEFAULT_APPS);
19340            serializer.endDocument();
19341            serializer.flush();
19342        } catch (Exception e) {
19343            if (DEBUG_BACKUP) {
19344                Slog.e(TAG, "Unable to write default apps for backup", e);
19345            }
19346            return null;
19347        }
19348
19349        return dataStream.toByteArray();
19350    }
19351
19352    @Override
19353    public void restoreDefaultApps(byte[] backup, int userId) {
19354        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19355            throw new SecurityException("Only the system may call restoreDefaultApps()");
19356        }
19357
19358        try {
19359            final XmlPullParser parser = Xml.newPullParser();
19360            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19361            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19362                    new BlobXmlRestorer() {
19363                        @Override
19364                        public void apply(XmlPullParser parser, int userId)
19365                                throws XmlPullParserException, IOException {
19366                            synchronized (mPackages) {
19367                                mSettings.readDefaultAppsLPw(parser, userId);
19368                            }
19369                        }
19370                    } );
19371        } catch (Exception e) {
19372            if (DEBUG_BACKUP) {
19373                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19374            }
19375        }
19376    }
19377
19378    @Override
19379    public byte[] getIntentFilterVerificationBackup(int userId) {
19380        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19381            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19382        }
19383
19384        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19385        try {
19386            final XmlSerializer serializer = new FastXmlSerializer();
19387            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19388            serializer.startDocument(null, true);
19389            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19390
19391            synchronized (mPackages) {
19392                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19393            }
19394
19395            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19396            serializer.endDocument();
19397            serializer.flush();
19398        } catch (Exception e) {
19399            if (DEBUG_BACKUP) {
19400                Slog.e(TAG, "Unable to write default apps for backup", e);
19401            }
19402            return null;
19403        }
19404
19405        return dataStream.toByteArray();
19406    }
19407
19408    @Override
19409    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19410        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19411            throw new SecurityException("Only the system may call restorePreferredActivities()");
19412        }
19413
19414        try {
19415            final XmlPullParser parser = Xml.newPullParser();
19416            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19417            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19418                    new BlobXmlRestorer() {
19419                        @Override
19420                        public void apply(XmlPullParser parser, int userId)
19421                                throws XmlPullParserException, IOException {
19422                            synchronized (mPackages) {
19423                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19424                                mSettings.writeLPr();
19425                            }
19426                        }
19427                    } );
19428        } catch (Exception e) {
19429            if (DEBUG_BACKUP) {
19430                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19431            }
19432        }
19433    }
19434
19435    @Override
19436    public byte[] getPermissionGrantBackup(int userId) {
19437        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19438            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19439        }
19440
19441        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19442        try {
19443            final XmlSerializer serializer = new FastXmlSerializer();
19444            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19445            serializer.startDocument(null, true);
19446            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19447
19448            synchronized (mPackages) {
19449                serializeRuntimePermissionGrantsLPr(serializer, userId);
19450            }
19451
19452            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19453            serializer.endDocument();
19454            serializer.flush();
19455        } catch (Exception e) {
19456            if (DEBUG_BACKUP) {
19457                Slog.e(TAG, "Unable to write default apps for backup", e);
19458            }
19459            return null;
19460        }
19461
19462        return dataStream.toByteArray();
19463    }
19464
19465    @Override
19466    public void restorePermissionGrants(byte[] backup, int userId) {
19467        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19468            throw new SecurityException("Only the system may call restorePermissionGrants()");
19469        }
19470
19471        try {
19472            final XmlPullParser parser = Xml.newPullParser();
19473            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19474            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19475                    new BlobXmlRestorer() {
19476                        @Override
19477                        public void apply(XmlPullParser parser, int userId)
19478                                throws XmlPullParserException, IOException {
19479                            synchronized (mPackages) {
19480                                processRestoredPermissionGrantsLPr(parser, userId);
19481                            }
19482                        }
19483                    } );
19484        } catch (Exception e) {
19485            if (DEBUG_BACKUP) {
19486                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19487            }
19488        }
19489    }
19490
19491    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19492            throws IOException {
19493        serializer.startTag(null, TAG_ALL_GRANTS);
19494
19495        final int N = mSettings.mPackages.size();
19496        for (int i = 0; i < N; i++) {
19497            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19498            boolean pkgGrantsKnown = false;
19499
19500            PermissionsState packagePerms = ps.getPermissionsState();
19501
19502            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19503                final int grantFlags = state.getFlags();
19504                // only look at grants that are not system/policy fixed
19505                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19506                    final boolean isGranted = state.isGranted();
19507                    // And only back up the user-twiddled state bits
19508                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19509                        final String packageName = mSettings.mPackages.keyAt(i);
19510                        if (!pkgGrantsKnown) {
19511                            serializer.startTag(null, TAG_GRANT);
19512                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19513                            pkgGrantsKnown = true;
19514                        }
19515
19516                        final boolean userSet =
19517                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19518                        final boolean userFixed =
19519                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19520                        final boolean revoke =
19521                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19522
19523                        serializer.startTag(null, TAG_PERMISSION);
19524                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19525                        if (isGranted) {
19526                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19527                        }
19528                        if (userSet) {
19529                            serializer.attribute(null, ATTR_USER_SET, "true");
19530                        }
19531                        if (userFixed) {
19532                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19533                        }
19534                        if (revoke) {
19535                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19536                        }
19537                        serializer.endTag(null, TAG_PERMISSION);
19538                    }
19539                }
19540            }
19541
19542            if (pkgGrantsKnown) {
19543                serializer.endTag(null, TAG_GRANT);
19544            }
19545        }
19546
19547        serializer.endTag(null, TAG_ALL_GRANTS);
19548    }
19549
19550    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19551            throws XmlPullParserException, IOException {
19552        String pkgName = null;
19553        int outerDepth = parser.getDepth();
19554        int type;
19555        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19556                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19557            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19558                continue;
19559            }
19560
19561            final String tagName = parser.getName();
19562            if (tagName.equals(TAG_GRANT)) {
19563                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19564                if (DEBUG_BACKUP) {
19565                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19566                }
19567            } else if (tagName.equals(TAG_PERMISSION)) {
19568
19569                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19570                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19571
19572                int newFlagSet = 0;
19573                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19574                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19575                }
19576                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19577                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19578                }
19579                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19580                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19581                }
19582                if (DEBUG_BACKUP) {
19583                    Slog.v(TAG, "  + Restoring grant:"
19584                            + " pkg=" + pkgName
19585                            + " perm=" + permName
19586                            + " granted=" + isGranted
19587                            + " bits=0x" + Integer.toHexString(newFlagSet));
19588                }
19589                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19590                if (ps != null) {
19591                    // Already installed so we apply the grant immediately
19592                    if (DEBUG_BACKUP) {
19593                        Slog.v(TAG, "        + already installed; applying");
19594                    }
19595                    PermissionsState perms = ps.getPermissionsState();
19596                    BasePermission bp =
19597                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19598                    if (bp != null) {
19599                        if (isGranted) {
19600                            perms.grantRuntimePermission(bp, userId);
19601                        }
19602                        if (newFlagSet != 0) {
19603                            perms.updatePermissionFlags(
19604                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19605                        }
19606                    }
19607                } else {
19608                    // Need to wait for post-restore install to apply the grant
19609                    if (DEBUG_BACKUP) {
19610                        Slog.v(TAG, "        - not yet installed; saving for later");
19611                    }
19612                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19613                            isGranted, newFlagSet, userId);
19614                }
19615            } else {
19616                PackageManagerService.reportSettingsProblem(Log.WARN,
19617                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19618                XmlUtils.skipCurrentTag(parser);
19619            }
19620        }
19621
19622        scheduleWriteSettingsLocked();
19623        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19624    }
19625
19626    @Override
19627    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19628            int sourceUserId, int targetUserId, int flags) {
19629        mContext.enforceCallingOrSelfPermission(
19630                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19631        int callingUid = Binder.getCallingUid();
19632        enforceOwnerRights(ownerPackage, callingUid);
19633        PackageManagerServiceUtils.enforceShellRestriction(
19634                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19635        if (intentFilter.countActions() == 0) {
19636            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19637            return;
19638        }
19639        synchronized (mPackages) {
19640            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19641                    ownerPackage, targetUserId, flags);
19642            CrossProfileIntentResolver resolver =
19643                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19644            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19645            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19646            if (existing != null) {
19647                int size = existing.size();
19648                for (int i = 0; i < size; i++) {
19649                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19650                        return;
19651                    }
19652                }
19653            }
19654            resolver.addFilter(newFilter);
19655            scheduleWritePackageRestrictionsLocked(sourceUserId);
19656        }
19657    }
19658
19659    @Override
19660    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19661        mContext.enforceCallingOrSelfPermission(
19662                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19663        final int callingUid = Binder.getCallingUid();
19664        enforceOwnerRights(ownerPackage, callingUid);
19665        PackageManagerServiceUtils.enforceShellRestriction(
19666                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19667        synchronized (mPackages) {
19668            CrossProfileIntentResolver resolver =
19669                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19670            ArraySet<CrossProfileIntentFilter> set =
19671                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19672            for (CrossProfileIntentFilter filter : set) {
19673                if (filter.getOwnerPackage().equals(ownerPackage)) {
19674                    resolver.removeFilter(filter);
19675                }
19676            }
19677            scheduleWritePackageRestrictionsLocked(sourceUserId);
19678        }
19679    }
19680
19681    // Enforcing that callingUid is owning pkg on userId
19682    private void enforceOwnerRights(String pkg, int callingUid) {
19683        // The system owns everything.
19684        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19685            return;
19686        }
19687        final int callingUserId = UserHandle.getUserId(callingUid);
19688        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19689        if (pi == null) {
19690            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19691                    + callingUserId);
19692        }
19693        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19694            throw new SecurityException("Calling uid " + callingUid
19695                    + " does not own package " + pkg);
19696        }
19697    }
19698
19699    @Override
19700    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19701        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19702            return null;
19703        }
19704        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19705    }
19706
19707    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19708        UserManagerService ums = UserManagerService.getInstance();
19709        if (ums != null) {
19710            final UserInfo parent = ums.getProfileParent(userId);
19711            final int launcherUid = (parent != null) ? parent.id : userId;
19712            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19713            if (launcherComponent != null) {
19714                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19715                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19716                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19717                        .setPackage(launcherComponent.getPackageName());
19718                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19719            }
19720        }
19721    }
19722
19723    /**
19724     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19725     * then reports the most likely home activity or null if there are more than one.
19726     */
19727    private ComponentName getDefaultHomeActivity(int userId) {
19728        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19729        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19730        if (cn != null) {
19731            return cn;
19732        }
19733
19734        // Find the launcher with the highest priority and return that component if there are no
19735        // other home activity with the same priority.
19736        int lastPriority = Integer.MIN_VALUE;
19737        ComponentName lastComponent = null;
19738        final int size = allHomeCandidates.size();
19739        for (int i = 0; i < size; i++) {
19740            final ResolveInfo ri = allHomeCandidates.get(i);
19741            if (ri.priority > lastPriority) {
19742                lastComponent = ri.activityInfo.getComponentName();
19743                lastPriority = ri.priority;
19744            } else if (ri.priority == lastPriority) {
19745                // Two components found with same priority.
19746                lastComponent = null;
19747            }
19748        }
19749        return lastComponent;
19750    }
19751
19752    private Intent getHomeIntent() {
19753        Intent intent = new Intent(Intent.ACTION_MAIN);
19754        intent.addCategory(Intent.CATEGORY_HOME);
19755        intent.addCategory(Intent.CATEGORY_DEFAULT);
19756        return intent;
19757    }
19758
19759    private IntentFilter getHomeFilter() {
19760        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19761        filter.addCategory(Intent.CATEGORY_HOME);
19762        filter.addCategory(Intent.CATEGORY_DEFAULT);
19763        return filter;
19764    }
19765
19766    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19767            int userId) {
19768        Intent intent  = getHomeIntent();
19769        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19770                PackageManager.GET_META_DATA, userId);
19771        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19772                true, false, false, userId);
19773
19774        allHomeCandidates.clear();
19775        if (list != null) {
19776            for (ResolveInfo ri : list) {
19777                allHomeCandidates.add(ri);
19778            }
19779        }
19780        return (preferred == null || preferred.activityInfo == null)
19781                ? null
19782                : new ComponentName(preferred.activityInfo.packageName,
19783                        preferred.activityInfo.name);
19784    }
19785
19786    @Override
19787    public void setHomeActivity(ComponentName comp, int userId) {
19788        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19789            return;
19790        }
19791        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19792        getHomeActivitiesAsUser(homeActivities, userId);
19793
19794        boolean found = false;
19795
19796        final int size = homeActivities.size();
19797        final ComponentName[] set = new ComponentName[size];
19798        for (int i = 0; i < size; i++) {
19799            final ResolveInfo candidate = homeActivities.get(i);
19800            final ActivityInfo info = candidate.activityInfo;
19801            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19802            set[i] = activityName;
19803            if (!found && activityName.equals(comp)) {
19804                found = true;
19805            }
19806        }
19807        if (!found) {
19808            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19809                    + userId);
19810        }
19811        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19812                set, comp, userId);
19813    }
19814
19815    private @Nullable String getSetupWizardPackageName() {
19816        final Intent intent = new Intent(Intent.ACTION_MAIN);
19817        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19818
19819        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19820                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19821                        | MATCH_DISABLED_COMPONENTS,
19822                UserHandle.myUserId());
19823        if (matches.size() == 1) {
19824            return matches.get(0).getComponentInfo().packageName;
19825        } else {
19826            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19827                    + ": matches=" + matches);
19828            return null;
19829        }
19830    }
19831
19832    private @Nullable String getStorageManagerPackageName() {
19833        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19834
19835        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19836                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19837                        | MATCH_DISABLED_COMPONENTS,
19838                UserHandle.myUserId());
19839        if (matches.size() == 1) {
19840            return matches.get(0).getComponentInfo().packageName;
19841        } else {
19842            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19843                    + matches.size() + ": matches=" + matches);
19844            return null;
19845        }
19846    }
19847
19848    @Override
19849    public void setApplicationEnabledSetting(String appPackageName,
19850            int newState, int flags, int userId, String callingPackage) {
19851        if (!sUserManager.exists(userId)) return;
19852        if (callingPackage == null) {
19853            callingPackage = Integer.toString(Binder.getCallingUid());
19854        }
19855        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19856    }
19857
19858    @Override
19859    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19860        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19861        synchronized (mPackages) {
19862            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19863            if (pkgSetting != null) {
19864                pkgSetting.setUpdateAvailable(updateAvailable);
19865            }
19866        }
19867    }
19868
19869    @Override
19870    public void setComponentEnabledSetting(ComponentName componentName,
19871            int newState, int flags, int userId) {
19872        if (!sUserManager.exists(userId)) return;
19873        setEnabledSetting(componentName.getPackageName(),
19874                componentName.getClassName(), newState, flags, userId, null);
19875    }
19876
19877    private void setEnabledSetting(final String packageName, String className, int newState,
19878            final int flags, int userId, String callingPackage) {
19879        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19880              || newState == COMPONENT_ENABLED_STATE_ENABLED
19881              || newState == COMPONENT_ENABLED_STATE_DISABLED
19882              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19883              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19884            throw new IllegalArgumentException("Invalid new component state: "
19885                    + newState);
19886        }
19887        PackageSetting pkgSetting;
19888        final int callingUid = Binder.getCallingUid();
19889        final int permission;
19890        if (callingUid == Process.SYSTEM_UID) {
19891            permission = PackageManager.PERMISSION_GRANTED;
19892        } else {
19893            permission = mContext.checkCallingOrSelfPermission(
19894                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19895        }
19896        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19897                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19898        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19899        boolean sendNow = false;
19900        boolean isApp = (className == null);
19901        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19902        String componentName = isApp ? packageName : className;
19903        int packageUid = -1;
19904        ArrayList<String> components;
19905
19906        // reader
19907        synchronized (mPackages) {
19908            pkgSetting = mSettings.mPackages.get(packageName);
19909            if (pkgSetting == null) {
19910                if (!isCallerInstantApp) {
19911                    if (className == null) {
19912                        throw new IllegalArgumentException("Unknown package: " + packageName);
19913                    }
19914                    throw new IllegalArgumentException(
19915                            "Unknown component: " + packageName + "/" + className);
19916                } else {
19917                    // throw SecurityException to prevent leaking package information
19918                    throw new SecurityException(
19919                            "Attempt to change component state; "
19920                            + "pid=" + Binder.getCallingPid()
19921                            + ", uid=" + callingUid
19922                            + (className == null
19923                                    ? ", package=" + packageName
19924                                    : ", component=" + packageName + "/" + className));
19925                }
19926            }
19927        }
19928
19929        // Limit who can change which apps
19930        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19931            // Don't allow apps that don't have permission to modify other apps
19932            if (!allowedByPermission
19933                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19934                throw new SecurityException(
19935                        "Attempt to change component state; "
19936                        + "pid=" + Binder.getCallingPid()
19937                        + ", uid=" + callingUid
19938                        + (className == null
19939                                ? ", package=" + packageName
19940                                : ", component=" + packageName + "/" + className));
19941            }
19942            // Don't allow changing protected packages.
19943            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19944                throw new SecurityException("Cannot disable a protected package: " + packageName);
19945            }
19946        }
19947
19948        synchronized (mPackages) {
19949            if (callingUid == Process.SHELL_UID
19950                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19951                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19952                // unless it is a test package.
19953                int oldState = pkgSetting.getEnabled(userId);
19954                if (className == null
19955                        &&
19956                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19957                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19958                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19959                        &&
19960                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19961                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19962                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19963                    // ok
19964                } else {
19965                    throw new SecurityException(
19966                            "Shell cannot change component state for " + packageName + "/"
19967                                    + className + " to " + newState);
19968                }
19969            }
19970        }
19971        if (className == null) {
19972            // We're dealing with an application/package level state change
19973            synchronized (mPackages) {
19974                if (pkgSetting.getEnabled(userId) == newState) {
19975                    // Nothing to do
19976                    return;
19977                }
19978            }
19979            // If we're enabling a system stub, there's a little more work to do.
19980            // Prior to enabling the package, we need to decompress the APK(s) to the
19981            // data partition and then replace the version on the system partition.
19982            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19983            final boolean isSystemStub = deletedPkg.isStub
19984                    && deletedPkg.isSystem();
19985            if (isSystemStub
19986                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19987                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19988                final File codePath = decompressPackage(deletedPkg);
19989                if (codePath == null) {
19990                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19991                    return;
19992                }
19993                // TODO remove direct parsing of the package object during internal cleanup
19994                // of scan package
19995                // We need to call parse directly here for no other reason than we need
19996                // the new package in order to disable the old one [we use the information
19997                // for some internal optimization to optionally create a new package setting
19998                // object on replace]. However, we can't get the package from the scan
19999                // because the scan modifies live structures and we need to remove the
20000                // old [system] package from the system before a scan can be attempted.
20001                // Once scan is indempotent we can remove this parse and use the package
20002                // object we scanned, prior to adding it to package settings.
20003                final PackageParser pp = new PackageParser();
20004                pp.setSeparateProcesses(mSeparateProcesses);
20005                pp.setDisplayMetrics(mMetrics);
20006                pp.setCallback(mPackageParserCallback);
20007                final PackageParser.Package tmpPkg;
20008                try {
20009                    final @ParseFlags int parseFlags = mDefParseFlags
20010                            | PackageParser.PARSE_MUST_BE_APK
20011                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20012                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20013                } catch (PackageParserException e) {
20014                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20015                    return;
20016                }
20017                synchronized (mInstallLock) {
20018                    // Disable the stub and remove any package entries
20019                    removePackageLI(deletedPkg, true);
20020                    synchronized (mPackages) {
20021                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20022                    }
20023                    final PackageParser.Package pkg;
20024                    try (PackageFreezer freezer =
20025                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20026                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20027                                | PackageParser.PARSE_ENFORCE_CODE;
20028                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20029                                0 /*currentTime*/, null /*user*/);
20030                        prepareAppDataAfterInstallLIF(pkg);
20031                        synchronized (mPackages) {
20032                            try {
20033                                updateSharedLibrariesLPr(pkg, null);
20034                            } catch (PackageManagerException e) {
20035                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20036                            }
20037                            mPermissionManager.updatePermissions(
20038                                    pkg.packageName, pkg, true, mPackages.values(),
20039                                    mPermissionCallback);
20040                            mSettings.writeLPr();
20041                        }
20042                    } catch (PackageManagerException e) {
20043                        // Whoops! Something went wrong; try to roll back to the stub
20044                        Slog.w(TAG, "Failed to install compressed system package:"
20045                                + pkgSetting.name, e);
20046                        // Remove the failed install
20047                        removeCodePathLI(codePath);
20048
20049                        // Install the system package
20050                        try (PackageFreezer freezer =
20051                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20052                            synchronized (mPackages) {
20053                                // NOTE: The system package always needs to be enabled; even
20054                                // if it's for a compressed stub. If we don't, installing the
20055                                // system package fails during scan [scanning checks the disabled
20056                                // packages]. We will reverse this later, after we've "installed"
20057                                // the stub.
20058                                // This leaves us in a fragile state; the stub should never be
20059                                // enabled, so, cross your fingers and hope nothing goes wrong
20060                                // until we can disable the package later.
20061                                enableSystemPackageLPw(deletedPkg);
20062                            }
20063                            installPackageFromSystemLIF(deletedPkg.codePath,
20064                                    false /*isPrivileged*/, null /*allUserHandles*/,
20065                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20066                                    true /*writeSettings*/);
20067                        } catch (PackageManagerException pme) {
20068                            Slog.w(TAG, "Failed to restore system package:"
20069                                    + deletedPkg.packageName, pme);
20070                        } finally {
20071                            synchronized (mPackages) {
20072                                mSettings.disableSystemPackageLPw(
20073                                        deletedPkg.packageName, true /*replaced*/);
20074                                mSettings.writeLPr();
20075                            }
20076                        }
20077                        return;
20078                    }
20079                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20080                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20081                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20082                    mDexManager.notifyPackageUpdated(pkg.packageName,
20083                            pkg.baseCodePath, pkg.splitCodePaths);
20084                }
20085            }
20086            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20087                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20088                // Don't care about who enables an app.
20089                callingPackage = null;
20090            }
20091            synchronized (mPackages) {
20092                pkgSetting.setEnabled(newState, userId, callingPackage);
20093            }
20094        } else {
20095            synchronized (mPackages) {
20096                // We're dealing with a component level state change
20097                // First, verify that this is a valid class name.
20098                PackageParser.Package pkg = pkgSetting.pkg;
20099                if (pkg == null || !pkg.hasComponentClassName(className)) {
20100                    if (pkg != null &&
20101                            pkg.applicationInfo.targetSdkVersion >=
20102                                    Build.VERSION_CODES.JELLY_BEAN) {
20103                        throw new IllegalArgumentException("Component class " + className
20104                                + " does not exist in " + packageName);
20105                    } else {
20106                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20107                                + className + " does not exist in " + packageName);
20108                    }
20109                }
20110                switch (newState) {
20111                    case COMPONENT_ENABLED_STATE_ENABLED:
20112                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20113                            return;
20114                        }
20115                        break;
20116                    case COMPONENT_ENABLED_STATE_DISABLED:
20117                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20118                            return;
20119                        }
20120                        break;
20121                    case COMPONENT_ENABLED_STATE_DEFAULT:
20122                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20123                            return;
20124                        }
20125                        break;
20126                    default:
20127                        Slog.e(TAG, "Invalid new component state: " + newState);
20128                        return;
20129                }
20130            }
20131        }
20132        synchronized (mPackages) {
20133            scheduleWritePackageRestrictionsLocked(userId);
20134            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20135            final long callingId = Binder.clearCallingIdentity();
20136            try {
20137                updateInstantAppInstallerLocked(packageName);
20138            } finally {
20139                Binder.restoreCallingIdentity(callingId);
20140            }
20141            components = mPendingBroadcasts.get(userId, packageName);
20142            final boolean newPackage = components == null;
20143            if (newPackage) {
20144                components = new ArrayList<String>();
20145            }
20146            if (!components.contains(componentName)) {
20147                components.add(componentName);
20148            }
20149            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20150                sendNow = true;
20151                // Purge entry from pending broadcast list if another one exists already
20152                // since we are sending one right away.
20153                mPendingBroadcasts.remove(userId, packageName);
20154            } else {
20155                if (newPackage) {
20156                    mPendingBroadcasts.put(userId, packageName, components);
20157                }
20158                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20159                    // Schedule a message
20160                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20161                }
20162            }
20163        }
20164
20165        long callingId = Binder.clearCallingIdentity();
20166        try {
20167            if (sendNow) {
20168                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20169                sendPackageChangedBroadcast(packageName,
20170                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20171            }
20172        } finally {
20173            Binder.restoreCallingIdentity(callingId);
20174        }
20175    }
20176
20177    @Override
20178    public void flushPackageRestrictionsAsUser(int userId) {
20179        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20180            return;
20181        }
20182        if (!sUserManager.exists(userId)) {
20183            return;
20184        }
20185        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20186                false /* checkShell */, "flushPackageRestrictions");
20187        synchronized (mPackages) {
20188            mSettings.writePackageRestrictionsLPr(userId);
20189            mDirtyUsers.remove(userId);
20190            if (mDirtyUsers.isEmpty()) {
20191                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20192            }
20193        }
20194    }
20195
20196    private void sendPackageChangedBroadcast(String packageName,
20197            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20198        if (DEBUG_INSTALL)
20199            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20200                    + componentNames);
20201        Bundle extras = new Bundle(4);
20202        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20203        String nameList[] = new String[componentNames.size()];
20204        componentNames.toArray(nameList);
20205        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20206        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20207        extras.putInt(Intent.EXTRA_UID, packageUid);
20208        // If this is not reporting a change of the overall package, then only send it
20209        // to registered receivers.  We don't want to launch a swath of apps for every
20210        // little component state change.
20211        final int flags = !componentNames.contains(packageName)
20212                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20213        final int userId = UserHandle.getUserId(packageUid);
20214        final boolean isInstantApp = isInstantApp(packageName, userId);
20215        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20216        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20217        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20218                userIds, instantUserIds);
20219    }
20220
20221    @Override
20222    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20223        if (!sUserManager.exists(userId)) return;
20224        final int callingUid = Binder.getCallingUid();
20225        if (getInstantAppPackageName(callingUid) != null) {
20226            return;
20227        }
20228        final int permission = mContext.checkCallingOrSelfPermission(
20229                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20230        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20231        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20232                true /* requireFullPermission */, true /* checkShell */, "stop package");
20233        // writer
20234        synchronized (mPackages) {
20235            final PackageSetting ps = mSettings.mPackages.get(packageName);
20236            if (!filterAppAccessLPr(ps, callingUid, userId)
20237                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20238                            allowedByPermission, callingUid, userId)) {
20239                scheduleWritePackageRestrictionsLocked(userId);
20240            }
20241        }
20242    }
20243
20244    @Override
20245    public String getInstallerPackageName(String packageName) {
20246        final int callingUid = Binder.getCallingUid();
20247        if (getInstantAppPackageName(callingUid) != null) {
20248            return null;
20249        }
20250        // reader
20251        synchronized (mPackages) {
20252            final PackageSetting ps = mSettings.mPackages.get(packageName);
20253            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20254                return null;
20255            }
20256            return mSettings.getInstallerPackageNameLPr(packageName);
20257        }
20258    }
20259
20260    public boolean isOrphaned(String packageName) {
20261        // reader
20262        synchronized (mPackages) {
20263            return mSettings.isOrphaned(packageName);
20264        }
20265    }
20266
20267    @Override
20268    public int getApplicationEnabledSetting(String packageName, int userId) {
20269        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20270        int callingUid = Binder.getCallingUid();
20271        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20272                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20273        // reader
20274        synchronized (mPackages) {
20275            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20276                return COMPONENT_ENABLED_STATE_DISABLED;
20277            }
20278            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20279        }
20280    }
20281
20282    @Override
20283    public int getComponentEnabledSetting(ComponentName component, int userId) {
20284        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20285        int callingUid = Binder.getCallingUid();
20286        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20287                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20288        synchronized (mPackages) {
20289            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20290                    component, TYPE_UNKNOWN, userId)) {
20291                return COMPONENT_ENABLED_STATE_DISABLED;
20292            }
20293            return mSettings.getComponentEnabledSettingLPr(component, userId);
20294        }
20295    }
20296
20297    @Override
20298    public void enterSafeMode() {
20299        enforceSystemOrRoot("Only the system can request entering safe mode");
20300
20301        if (!mSystemReady) {
20302            mSafeMode = true;
20303        }
20304    }
20305
20306    @Override
20307    public void systemReady() {
20308        enforceSystemOrRoot("Only the system can claim the system is ready");
20309
20310        mSystemReady = true;
20311        final ContentResolver resolver = mContext.getContentResolver();
20312        ContentObserver co = new ContentObserver(mHandler) {
20313            @Override
20314            public void onChange(boolean selfChange) {
20315                mEphemeralAppsDisabled =
20316                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20317                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20318            }
20319        };
20320        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20321                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20322                false, co, UserHandle.USER_SYSTEM);
20323        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20324                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20325        co.onChange(true);
20326
20327        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20328        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20329        // it is done.
20330        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20331            @Override
20332            public void onChange(boolean selfChange) {
20333                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20334                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20335                        oobEnabled == 1 ? "true" : "false");
20336            }
20337        };
20338        mContext.getContentResolver().registerContentObserver(
20339                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20340                UserHandle.USER_SYSTEM);
20341        // At boot, restore the value from the setting, which persists across reboot.
20342        privAppOobObserver.onChange(true);
20343
20344        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20345        // disabled after already being started.
20346        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20347                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20348
20349        // Read the compatibilty setting when the system is ready.
20350        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20351                mContext.getContentResolver(),
20352                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20353        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20354        if (DEBUG_SETTINGS) {
20355            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20356        }
20357
20358        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20359
20360        synchronized (mPackages) {
20361            // Verify that all of the preferred activity components actually
20362            // exist.  It is possible for applications to be updated and at
20363            // that point remove a previously declared activity component that
20364            // had been set as a preferred activity.  We try to clean this up
20365            // the next time we encounter that preferred activity, but it is
20366            // possible for the user flow to never be able to return to that
20367            // situation so here we do a sanity check to make sure we haven't
20368            // left any junk around.
20369            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20370            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20371                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20372                removed.clear();
20373                for (PreferredActivity pa : pir.filterSet()) {
20374                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20375                        removed.add(pa);
20376                    }
20377                }
20378                if (removed.size() > 0) {
20379                    for (int r=0; r<removed.size(); r++) {
20380                        PreferredActivity pa = removed.get(r);
20381                        Slog.w(TAG, "Removing dangling preferred activity: "
20382                                + pa.mPref.mComponent);
20383                        pir.removeFilter(pa);
20384                    }
20385                    mSettings.writePackageRestrictionsLPr(
20386                            mSettings.mPreferredActivities.keyAt(i));
20387                }
20388            }
20389
20390            for (int userId : UserManagerService.getInstance().getUserIds()) {
20391                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20392                    grantPermissionsUserIds = ArrayUtils.appendInt(
20393                            grantPermissionsUserIds, userId);
20394                }
20395            }
20396        }
20397        sUserManager.systemReady();
20398
20399        // If we upgraded grant all default permissions before kicking off.
20400        for (int userId : grantPermissionsUserIds) {
20401            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20402        }
20403
20404        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20405            // If we did not grant default permissions, we preload from this the
20406            // default permission exceptions lazily to ensure we don't hit the
20407            // disk on a new user creation.
20408            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20409        }
20410
20411        // Now that we've scanned all packages, and granted any default
20412        // permissions, ensure permissions are updated. Beware of dragons if you
20413        // try optimizing this.
20414        synchronized (mPackages) {
20415            mPermissionManager.updateAllPermissions(
20416                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20417                    mPermissionCallback);
20418        }
20419
20420        // Kick off any messages waiting for system ready
20421        if (mPostSystemReadyMessages != null) {
20422            for (Message msg : mPostSystemReadyMessages) {
20423                msg.sendToTarget();
20424            }
20425            mPostSystemReadyMessages = null;
20426        }
20427
20428        // Watch for external volumes that come and go over time
20429        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20430        storage.registerListener(mStorageListener);
20431
20432        mInstallerService.systemReady();
20433        mPackageDexOptimizer.systemReady();
20434
20435        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20436                StorageManagerInternal.class);
20437        StorageManagerInternal.addExternalStoragePolicy(
20438                new StorageManagerInternal.ExternalStorageMountPolicy() {
20439            @Override
20440            public int getMountMode(int uid, String packageName) {
20441                if (Process.isIsolated(uid)) {
20442                    return Zygote.MOUNT_EXTERNAL_NONE;
20443                }
20444                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20445                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20446                }
20447                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20448                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20449                }
20450                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20451                    return Zygote.MOUNT_EXTERNAL_READ;
20452                }
20453                return Zygote.MOUNT_EXTERNAL_WRITE;
20454            }
20455
20456            @Override
20457            public boolean hasExternalStorage(int uid, String packageName) {
20458                return true;
20459            }
20460        });
20461
20462        // Now that we're mostly running, clean up stale users and apps
20463        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20464        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20465
20466        mPermissionManager.systemReady();
20467    }
20468
20469    public void waitForAppDataPrepared() {
20470        if (mPrepareAppDataFuture == null) {
20471            return;
20472        }
20473        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20474        mPrepareAppDataFuture = null;
20475    }
20476
20477    @Override
20478    public boolean isSafeMode() {
20479        // allow instant applications
20480        return mSafeMode;
20481    }
20482
20483    @Override
20484    public boolean hasSystemUidErrors() {
20485        // allow instant applications
20486        return mHasSystemUidErrors;
20487    }
20488
20489    static String arrayToString(int[] array) {
20490        StringBuffer buf = new StringBuffer(128);
20491        buf.append('[');
20492        if (array != null) {
20493            for (int i=0; i<array.length; i++) {
20494                if (i > 0) buf.append(", ");
20495                buf.append(array[i]);
20496            }
20497        }
20498        buf.append(']');
20499        return buf.toString();
20500    }
20501
20502    @Override
20503    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20504            FileDescriptor err, String[] args, ShellCallback callback,
20505            ResultReceiver resultReceiver) {
20506        (new PackageManagerShellCommand(this)).exec(
20507                this, in, out, err, args, callback, resultReceiver);
20508    }
20509
20510    @Override
20511    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20512        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20513
20514        DumpState dumpState = new DumpState();
20515        boolean fullPreferred = false;
20516        boolean checkin = false;
20517
20518        String packageName = null;
20519        ArraySet<String> permissionNames = null;
20520
20521        int opti = 0;
20522        while (opti < args.length) {
20523            String opt = args[opti];
20524            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20525                break;
20526            }
20527            opti++;
20528
20529            if ("-a".equals(opt)) {
20530                // Right now we only know how to print all.
20531            } else if ("-h".equals(opt)) {
20532                pw.println("Package manager dump options:");
20533                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20534                pw.println("    --checkin: dump for a checkin");
20535                pw.println("    -f: print details of intent filters");
20536                pw.println("    -h: print this help");
20537                pw.println("  cmd may be one of:");
20538                pw.println("    l[ibraries]: list known shared libraries");
20539                pw.println("    f[eatures]: list device features");
20540                pw.println("    k[eysets]: print known keysets");
20541                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20542                pw.println("    perm[issions]: dump permissions");
20543                pw.println("    permission [name ...]: dump declaration and use of given permission");
20544                pw.println("    pref[erred]: print preferred package settings");
20545                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20546                pw.println("    prov[iders]: dump content providers");
20547                pw.println("    p[ackages]: dump installed packages");
20548                pw.println("    s[hared-users]: dump shared user IDs");
20549                pw.println("    m[essages]: print collected runtime messages");
20550                pw.println("    v[erifiers]: print package verifier info");
20551                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20552                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20553                pw.println("    version: print database version info");
20554                pw.println("    write: write current settings now");
20555                pw.println("    installs: details about install sessions");
20556                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20557                pw.println("    dexopt: dump dexopt state");
20558                pw.println("    compiler-stats: dump compiler statistics");
20559                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20560                pw.println("    service-permissions: dump permissions required by services");
20561                pw.println("    <package.name>: info about given package");
20562                return;
20563            } else if ("--checkin".equals(opt)) {
20564                checkin = true;
20565            } else if ("-f".equals(opt)) {
20566                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20567            } else if ("--proto".equals(opt)) {
20568                dumpProto(fd);
20569                return;
20570            } else {
20571                pw.println("Unknown argument: " + opt + "; use -h for help");
20572            }
20573        }
20574
20575        // Is the caller requesting to dump a particular piece of data?
20576        if (opti < args.length) {
20577            String cmd = args[opti];
20578            opti++;
20579            // Is this a package name?
20580            if ("android".equals(cmd) || cmd.contains(".")) {
20581                packageName = cmd;
20582                // When dumping a single package, we always dump all of its
20583                // filter information since the amount of data will be reasonable.
20584                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20585            } else if ("check-permission".equals(cmd)) {
20586                if (opti >= args.length) {
20587                    pw.println("Error: check-permission missing permission argument");
20588                    return;
20589                }
20590                String perm = args[opti];
20591                opti++;
20592                if (opti >= args.length) {
20593                    pw.println("Error: check-permission missing package argument");
20594                    return;
20595                }
20596
20597                String pkg = args[opti];
20598                opti++;
20599                int user = UserHandle.getUserId(Binder.getCallingUid());
20600                if (opti < args.length) {
20601                    try {
20602                        user = Integer.parseInt(args[opti]);
20603                    } catch (NumberFormatException e) {
20604                        pw.println("Error: check-permission user argument is not a number: "
20605                                + args[opti]);
20606                        return;
20607                    }
20608                }
20609
20610                // Normalize package name to handle renamed packages and static libs
20611                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20612
20613                pw.println(checkPermission(perm, pkg, user));
20614                return;
20615            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20616                dumpState.setDump(DumpState.DUMP_LIBS);
20617            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20618                dumpState.setDump(DumpState.DUMP_FEATURES);
20619            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20620                if (opti >= args.length) {
20621                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20622                            | DumpState.DUMP_SERVICE_RESOLVERS
20623                            | DumpState.DUMP_RECEIVER_RESOLVERS
20624                            | DumpState.DUMP_CONTENT_RESOLVERS);
20625                } else {
20626                    while (opti < args.length) {
20627                        String name = args[opti];
20628                        if ("a".equals(name) || "activity".equals(name)) {
20629                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20630                        } else if ("s".equals(name) || "service".equals(name)) {
20631                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20632                        } else if ("r".equals(name) || "receiver".equals(name)) {
20633                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20634                        } else if ("c".equals(name) || "content".equals(name)) {
20635                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20636                        } else {
20637                            pw.println("Error: unknown resolver table type: " + name);
20638                            return;
20639                        }
20640                        opti++;
20641                    }
20642                }
20643            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20644                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20645            } else if ("permission".equals(cmd)) {
20646                if (opti >= args.length) {
20647                    pw.println("Error: permission requires permission name");
20648                    return;
20649                }
20650                permissionNames = new ArraySet<>();
20651                while (opti < args.length) {
20652                    permissionNames.add(args[opti]);
20653                    opti++;
20654                }
20655                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20656                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20657            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20658                dumpState.setDump(DumpState.DUMP_PREFERRED);
20659            } else if ("preferred-xml".equals(cmd)) {
20660                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20661                if (opti < args.length && "--full".equals(args[opti])) {
20662                    fullPreferred = true;
20663                    opti++;
20664                }
20665            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20666                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20667            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20668                dumpState.setDump(DumpState.DUMP_PACKAGES);
20669            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20670                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20671            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20672                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20673            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20674                dumpState.setDump(DumpState.DUMP_MESSAGES);
20675            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20676                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20677            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20678                    || "intent-filter-verifiers".equals(cmd)) {
20679                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20680            } else if ("version".equals(cmd)) {
20681                dumpState.setDump(DumpState.DUMP_VERSION);
20682            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20683                dumpState.setDump(DumpState.DUMP_KEYSETS);
20684            } else if ("installs".equals(cmd)) {
20685                dumpState.setDump(DumpState.DUMP_INSTALLS);
20686            } else if ("frozen".equals(cmd)) {
20687                dumpState.setDump(DumpState.DUMP_FROZEN);
20688            } else if ("volumes".equals(cmd)) {
20689                dumpState.setDump(DumpState.DUMP_VOLUMES);
20690            } else if ("dexopt".equals(cmd)) {
20691                dumpState.setDump(DumpState.DUMP_DEXOPT);
20692            } else if ("compiler-stats".equals(cmd)) {
20693                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20694            } else if ("changes".equals(cmd)) {
20695                dumpState.setDump(DumpState.DUMP_CHANGES);
20696            } else if ("service-permissions".equals(cmd)) {
20697                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
20698            } else if ("write".equals(cmd)) {
20699                synchronized (mPackages) {
20700                    mSettings.writeLPr();
20701                    pw.println("Settings written.");
20702                    return;
20703                }
20704            }
20705        }
20706
20707        if (checkin) {
20708            pw.println("vers,1");
20709        }
20710
20711        // reader
20712        synchronized (mPackages) {
20713            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20714                if (!checkin) {
20715                    if (dumpState.onTitlePrinted())
20716                        pw.println();
20717                    pw.println("Database versions:");
20718                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20719                }
20720            }
20721
20722            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20723                if (!checkin) {
20724                    if (dumpState.onTitlePrinted())
20725                        pw.println();
20726                    pw.println("Verifiers:");
20727                    pw.print("  Required: ");
20728                    pw.print(mRequiredVerifierPackage);
20729                    pw.print(" (uid=");
20730                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20731                            UserHandle.USER_SYSTEM));
20732                    pw.println(")");
20733                } else if (mRequiredVerifierPackage != null) {
20734                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20735                    pw.print(",");
20736                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20737                            UserHandle.USER_SYSTEM));
20738                }
20739            }
20740
20741            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20742                    packageName == null) {
20743                if (mIntentFilterVerifierComponent != null) {
20744                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20745                    if (!checkin) {
20746                        if (dumpState.onTitlePrinted())
20747                            pw.println();
20748                        pw.println("Intent Filter Verifier:");
20749                        pw.print("  Using: ");
20750                        pw.print(verifierPackageName);
20751                        pw.print(" (uid=");
20752                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20753                                UserHandle.USER_SYSTEM));
20754                        pw.println(")");
20755                    } else if (verifierPackageName != null) {
20756                        pw.print("ifv,"); pw.print(verifierPackageName);
20757                        pw.print(",");
20758                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20759                                UserHandle.USER_SYSTEM));
20760                    }
20761                } else {
20762                    pw.println();
20763                    pw.println("No Intent Filter Verifier available!");
20764                }
20765            }
20766
20767            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20768                boolean printedHeader = false;
20769                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20770                while (it.hasNext()) {
20771                    String libName = it.next();
20772                    LongSparseArray<SharedLibraryEntry> versionedLib
20773                            = mSharedLibraries.get(libName);
20774                    if (versionedLib == null) {
20775                        continue;
20776                    }
20777                    final int versionCount = versionedLib.size();
20778                    for (int i = 0; i < versionCount; i++) {
20779                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20780                        if (!checkin) {
20781                            if (!printedHeader) {
20782                                if (dumpState.onTitlePrinted())
20783                                    pw.println();
20784                                pw.println("Libraries:");
20785                                printedHeader = true;
20786                            }
20787                            pw.print("  ");
20788                        } else {
20789                            pw.print("lib,");
20790                        }
20791                        pw.print(libEntry.info.getName());
20792                        if (libEntry.info.isStatic()) {
20793                            pw.print(" version=" + libEntry.info.getLongVersion());
20794                        }
20795                        if (!checkin) {
20796                            pw.print(" -> ");
20797                        }
20798                        if (libEntry.path != null) {
20799                            pw.print(" (jar) ");
20800                            pw.print(libEntry.path);
20801                        } else {
20802                            pw.print(" (apk) ");
20803                            pw.print(libEntry.apk);
20804                        }
20805                        pw.println();
20806                    }
20807                }
20808            }
20809
20810            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20811                if (dumpState.onTitlePrinted())
20812                    pw.println();
20813                if (!checkin) {
20814                    pw.println("Features:");
20815                }
20816
20817                synchronized (mAvailableFeatures) {
20818                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20819                        if (checkin) {
20820                            pw.print("feat,");
20821                            pw.print(feat.name);
20822                            pw.print(",");
20823                            pw.println(feat.version);
20824                        } else {
20825                            pw.print("  ");
20826                            pw.print(feat.name);
20827                            if (feat.version > 0) {
20828                                pw.print(" version=");
20829                                pw.print(feat.version);
20830                            }
20831                            pw.println();
20832                        }
20833                    }
20834                }
20835            }
20836
20837            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20838                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20839                        : "Activity Resolver Table:", "  ", packageName,
20840                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20841                    dumpState.setTitlePrinted(true);
20842                }
20843            }
20844            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20845                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20846                        : "Receiver Resolver Table:", "  ", packageName,
20847                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20848                    dumpState.setTitlePrinted(true);
20849                }
20850            }
20851            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20852                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20853                        : "Service Resolver Table:", "  ", packageName,
20854                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20855                    dumpState.setTitlePrinted(true);
20856                }
20857            }
20858            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20859                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20860                        : "Provider Resolver Table:", "  ", packageName,
20861                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20862                    dumpState.setTitlePrinted(true);
20863                }
20864            }
20865
20866            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20867                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20868                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20869                    int user = mSettings.mPreferredActivities.keyAt(i);
20870                    if (pir.dump(pw,
20871                            dumpState.getTitlePrinted()
20872                                ? "\nPreferred Activities User " + user + ":"
20873                                : "Preferred Activities User " + user + ":", "  ",
20874                            packageName, true, false)) {
20875                        dumpState.setTitlePrinted(true);
20876                    }
20877                }
20878            }
20879
20880            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20881                pw.flush();
20882                FileOutputStream fout = new FileOutputStream(fd);
20883                BufferedOutputStream str = new BufferedOutputStream(fout);
20884                XmlSerializer serializer = new FastXmlSerializer();
20885                try {
20886                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20887                    serializer.startDocument(null, true);
20888                    serializer.setFeature(
20889                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20890                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20891                    serializer.endDocument();
20892                    serializer.flush();
20893                } catch (IllegalArgumentException e) {
20894                    pw.println("Failed writing: " + e);
20895                } catch (IllegalStateException e) {
20896                    pw.println("Failed writing: " + e);
20897                } catch (IOException e) {
20898                    pw.println("Failed writing: " + e);
20899                }
20900            }
20901
20902            if (!checkin
20903                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20904                    && packageName == null) {
20905                pw.println();
20906                int count = mSettings.mPackages.size();
20907                if (count == 0) {
20908                    pw.println("No applications!");
20909                    pw.println();
20910                } else {
20911                    final String prefix = "  ";
20912                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20913                    if (allPackageSettings.size() == 0) {
20914                        pw.println("No domain preferred apps!");
20915                        pw.println();
20916                    } else {
20917                        pw.println("App verification status:");
20918                        pw.println();
20919                        count = 0;
20920                        for (PackageSetting ps : allPackageSettings) {
20921                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20922                            if (ivi == null || ivi.getPackageName() == null) continue;
20923                            pw.println(prefix + "Package: " + ivi.getPackageName());
20924                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20925                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20926                            pw.println();
20927                            count++;
20928                        }
20929                        if (count == 0) {
20930                            pw.println(prefix + "No app verification established.");
20931                            pw.println();
20932                        }
20933                        for (int userId : sUserManager.getUserIds()) {
20934                            pw.println("App linkages for user " + userId + ":");
20935                            pw.println();
20936                            count = 0;
20937                            for (PackageSetting ps : allPackageSettings) {
20938                                final long status = ps.getDomainVerificationStatusForUser(userId);
20939                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20940                                        && !DEBUG_DOMAIN_VERIFICATION) {
20941                                    continue;
20942                                }
20943                                pw.println(prefix + "Package: " + ps.name);
20944                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20945                                String statusStr = IntentFilterVerificationInfo.
20946                                        getStatusStringFromValue(status);
20947                                pw.println(prefix + "Status:  " + statusStr);
20948                                pw.println();
20949                                count++;
20950                            }
20951                            if (count == 0) {
20952                                pw.println(prefix + "No configured app linkages.");
20953                                pw.println();
20954                            }
20955                        }
20956                    }
20957                }
20958            }
20959
20960            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20961                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20962            }
20963
20964            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20965                boolean printedSomething = false;
20966                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20967                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20968                        continue;
20969                    }
20970                    if (!printedSomething) {
20971                        if (dumpState.onTitlePrinted())
20972                            pw.println();
20973                        pw.println("Registered ContentProviders:");
20974                        printedSomething = true;
20975                    }
20976                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20977                    pw.print("    "); pw.println(p.toString());
20978                }
20979                printedSomething = false;
20980                for (Map.Entry<String, PackageParser.Provider> entry :
20981                        mProvidersByAuthority.entrySet()) {
20982                    PackageParser.Provider p = entry.getValue();
20983                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20984                        continue;
20985                    }
20986                    if (!printedSomething) {
20987                        if (dumpState.onTitlePrinted())
20988                            pw.println();
20989                        pw.println("ContentProvider Authorities:");
20990                        printedSomething = true;
20991                    }
20992                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20993                    pw.print("    "); pw.println(p.toString());
20994                    if (p.info != null && p.info.applicationInfo != null) {
20995                        final String appInfo = p.info.applicationInfo.toString();
20996                        pw.print("      applicationInfo="); pw.println(appInfo);
20997                    }
20998                }
20999            }
21000
21001            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21002                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21003            }
21004
21005            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21006                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21007            }
21008
21009            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21010                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21011            }
21012
21013            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21014                if (dumpState.onTitlePrinted()) pw.println();
21015                pw.println("Package Changes:");
21016                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21017                final int K = mChangedPackages.size();
21018                for (int i = 0; i < K; i++) {
21019                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21020                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21021                    final int N = changes.size();
21022                    if (N == 0) {
21023                        pw.print("    "); pw.println("No packages changed");
21024                    } else {
21025                        for (int j = 0; j < N; j++) {
21026                            final String pkgName = changes.valueAt(j);
21027                            final int sequenceNumber = changes.keyAt(j);
21028                            pw.print("    ");
21029                            pw.print("seq=");
21030                            pw.print(sequenceNumber);
21031                            pw.print(", package=");
21032                            pw.println(pkgName);
21033                        }
21034                    }
21035                }
21036            }
21037
21038            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21039                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21040            }
21041
21042            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21043                // XXX should handle packageName != null by dumping only install data that
21044                // the given package is involved with.
21045                if (dumpState.onTitlePrinted()) pw.println();
21046
21047                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21048                ipw.println();
21049                ipw.println("Frozen packages:");
21050                ipw.increaseIndent();
21051                if (mFrozenPackages.size() == 0) {
21052                    ipw.println("(none)");
21053                } else {
21054                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21055                        ipw.println(mFrozenPackages.valueAt(i));
21056                    }
21057                }
21058                ipw.decreaseIndent();
21059            }
21060
21061            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21062                if (dumpState.onTitlePrinted()) pw.println();
21063
21064                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21065                ipw.println();
21066                ipw.println("Loaded volumes:");
21067                ipw.increaseIndent();
21068                if (mLoadedVolumes.size() == 0) {
21069                    ipw.println("(none)");
21070                } else {
21071                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21072                        ipw.println(mLoadedVolumes.valueAt(i));
21073                    }
21074                }
21075                ipw.decreaseIndent();
21076            }
21077
21078            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21079                    && packageName == null) {
21080                if (dumpState.onTitlePrinted()) pw.println();
21081                pw.println("Service permissions:");
21082
21083                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21084                while (filterIterator.hasNext()) {
21085                    final ServiceIntentInfo info = filterIterator.next();
21086                    final ServiceInfo serviceInfo = info.service.info;
21087                    final String permission = serviceInfo.permission;
21088                    if (permission != null) {
21089                        pw.print("    ");
21090                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21091                        pw.print(": ");
21092                        pw.println(permission);
21093                    }
21094                }
21095            }
21096
21097            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21098                if (dumpState.onTitlePrinted()) pw.println();
21099                dumpDexoptStateLPr(pw, packageName);
21100            }
21101
21102            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21103                if (dumpState.onTitlePrinted()) pw.println();
21104                dumpCompilerStatsLPr(pw, packageName);
21105            }
21106
21107            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21108                if (dumpState.onTitlePrinted()) pw.println();
21109                mSettings.dumpReadMessagesLPr(pw, dumpState);
21110
21111                pw.println();
21112                pw.println("Package warning messages:");
21113                dumpCriticalInfo(pw, null);
21114            }
21115
21116            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21117                dumpCriticalInfo(pw, "msg,");
21118            }
21119        }
21120
21121        // PackageInstaller should be called outside of mPackages lock
21122        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21123            // XXX should handle packageName != null by dumping only install data that
21124            // the given package is involved with.
21125            if (dumpState.onTitlePrinted()) pw.println();
21126            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21127        }
21128    }
21129
21130    private void dumpProto(FileDescriptor fd) {
21131        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21132
21133        synchronized (mPackages) {
21134            final long requiredVerifierPackageToken =
21135                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21136            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21137            proto.write(
21138                    PackageServiceDumpProto.PackageShortProto.UID,
21139                    getPackageUid(
21140                            mRequiredVerifierPackage,
21141                            MATCH_DEBUG_TRIAGED_MISSING,
21142                            UserHandle.USER_SYSTEM));
21143            proto.end(requiredVerifierPackageToken);
21144
21145            if (mIntentFilterVerifierComponent != null) {
21146                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21147                final long verifierPackageToken =
21148                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21149                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21150                proto.write(
21151                        PackageServiceDumpProto.PackageShortProto.UID,
21152                        getPackageUid(
21153                                verifierPackageName,
21154                                MATCH_DEBUG_TRIAGED_MISSING,
21155                                UserHandle.USER_SYSTEM));
21156                proto.end(verifierPackageToken);
21157            }
21158
21159            dumpSharedLibrariesProto(proto);
21160            dumpFeaturesProto(proto);
21161            mSettings.dumpPackagesProto(proto);
21162            mSettings.dumpSharedUsersProto(proto);
21163            dumpCriticalInfo(proto);
21164        }
21165        proto.flush();
21166    }
21167
21168    private void dumpFeaturesProto(ProtoOutputStream proto) {
21169        synchronized (mAvailableFeatures) {
21170            final int count = mAvailableFeatures.size();
21171            for (int i = 0; i < count; i++) {
21172                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21173            }
21174        }
21175    }
21176
21177    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21178        final int count = mSharedLibraries.size();
21179        for (int i = 0; i < count; i++) {
21180            final String libName = mSharedLibraries.keyAt(i);
21181            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21182            if (versionedLib == null) {
21183                continue;
21184            }
21185            final int versionCount = versionedLib.size();
21186            for (int j = 0; j < versionCount; j++) {
21187                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21188                final long sharedLibraryToken =
21189                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21190                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21191                final boolean isJar = (libEntry.path != null);
21192                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21193                if (isJar) {
21194                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21195                } else {
21196                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21197                }
21198                proto.end(sharedLibraryToken);
21199            }
21200        }
21201    }
21202
21203    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21204        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21205        ipw.println();
21206        ipw.println("Dexopt state:");
21207        ipw.increaseIndent();
21208        Collection<PackageParser.Package> packages = null;
21209        if (packageName != null) {
21210            PackageParser.Package targetPackage = mPackages.get(packageName);
21211            if (targetPackage != null) {
21212                packages = Collections.singletonList(targetPackage);
21213            } else {
21214                ipw.println("Unable to find package: " + packageName);
21215                return;
21216            }
21217        } else {
21218            packages = mPackages.values();
21219        }
21220
21221        for (PackageParser.Package pkg : packages) {
21222            ipw.println("[" + pkg.packageName + "]");
21223            ipw.increaseIndent();
21224            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21225                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21226            ipw.decreaseIndent();
21227        }
21228    }
21229
21230    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21231        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21232        ipw.println();
21233        ipw.println("Compiler stats:");
21234        ipw.increaseIndent();
21235        Collection<PackageParser.Package> packages = null;
21236        if (packageName != null) {
21237            PackageParser.Package targetPackage = mPackages.get(packageName);
21238            if (targetPackage != null) {
21239                packages = Collections.singletonList(targetPackage);
21240            } else {
21241                ipw.println("Unable to find package: " + packageName);
21242                return;
21243            }
21244        } else {
21245            packages = mPackages.values();
21246        }
21247
21248        for (PackageParser.Package pkg : packages) {
21249            ipw.println("[" + pkg.packageName + "]");
21250            ipw.increaseIndent();
21251
21252            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21253            if (stats == null) {
21254                ipw.println("(No recorded stats)");
21255            } else {
21256                stats.dump(ipw);
21257            }
21258            ipw.decreaseIndent();
21259        }
21260    }
21261
21262    private String dumpDomainString(String packageName) {
21263        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21264                .getList();
21265        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21266
21267        ArraySet<String> result = new ArraySet<>();
21268        if (iviList.size() > 0) {
21269            for (IntentFilterVerificationInfo ivi : iviList) {
21270                for (String host : ivi.getDomains()) {
21271                    result.add(host);
21272                }
21273            }
21274        }
21275        if (filters != null && filters.size() > 0) {
21276            for (IntentFilter filter : filters) {
21277                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21278                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21279                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21280                    result.addAll(filter.getHostsList());
21281                }
21282            }
21283        }
21284
21285        StringBuilder sb = new StringBuilder(result.size() * 16);
21286        for (String domain : result) {
21287            if (sb.length() > 0) sb.append(" ");
21288            sb.append(domain);
21289        }
21290        return sb.toString();
21291    }
21292
21293    // ------- apps on sdcard specific code -------
21294    static final boolean DEBUG_SD_INSTALL = false;
21295
21296    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21297
21298    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21299
21300    private boolean mMediaMounted = false;
21301
21302    static String getEncryptKey() {
21303        try {
21304            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21305                    SD_ENCRYPTION_KEYSTORE_NAME);
21306            if (sdEncKey == null) {
21307                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21308                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21309                if (sdEncKey == null) {
21310                    Slog.e(TAG, "Failed to create encryption keys");
21311                    return null;
21312                }
21313            }
21314            return sdEncKey;
21315        } catch (NoSuchAlgorithmException nsae) {
21316            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21317            return null;
21318        } catch (IOException ioe) {
21319            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21320            return null;
21321        }
21322    }
21323
21324    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21325            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21326        final int size = infos.size();
21327        final String[] packageNames = new String[size];
21328        final int[] packageUids = new int[size];
21329        for (int i = 0; i < size; i++) {
21330            final ApplicationInfo info = infos.get(i);
21331            packageNames[i] = info.packageName;
21332            packageUids[i] = info.uid;
21333        }
21334        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21335                finishedReceiver);
21336    }
21337
21338    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21339            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21340        sendResourcesChangedBroadcast(mediaStatus, replacing,
21341                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21342    }
21343
21344    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21345            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21346        int size = pkgList.length;
21347        if (size > 0) {
21348            // Send broadcasts here
21349            Bundle extras = new Bundle();
21350            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21351            if (uidArr != null) {
21352                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21353            }
21354            if (replacing) {
21355                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21356            }
21357            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21358                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21359            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21360        }
21361    }
21362
21363    private void loadPrivatePackages(final VolumeInfo vol) {
21364        mHandler.post(new Runnable() {
21365            @Override
21366            public void run() {
21367                loadPrivatePackagesInner(vol);
21368            }
21369        });
21370    }
21371
21372    private void loadPrivatePackagesInner(VolumeInfo vol) {
21373        final String volumeUuid = vol.fsUuid;
21374        if (TextUtils.isEmpty(volumeUuid)) {
21375            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21376            return;
21377        }
21378
21379        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21380        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21381        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21382
21383        final VersionInfo ver;
21384        final List<PackageSetting> packages;
21385        synchronized (mPackages) {
21386            ver = mSettings.findOrCreateVersion(volumeUuid);
21387            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21388        }
21389
21390        for (PackageSetting ps : packages) {
21391            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21392            synchronized (mInstallLock) {
21393                final PackageParser.Package pkg;
21394                try {
21395                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21396                    loaded.add(pkg.applicationInfo);
21397
21398                } catch (PackageManagerException e) {
21399                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21400                }
21401
21402                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21403                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21404                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21405                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21406                }
21407            }
21408        }
21409
21410        // Reconcile app data for all started/unlocked users
21411        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21412        final UserManager um = mContext.getSystemService(UserManager.class);
21413        UserManagerInternal umInternal = getUserManagerInternal();
21414        for (UserInfo user : um.getUsers()) {
21415            final int flags;
21416            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21417                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21418            } else if (umInternal.isUserRunning(user.id)) {
21419                flags = StorageManager.FLAG_STORAGE_DE;
21420            } else {
21421                continue;
21422            }
21423
21424            try {
21425                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21426                synchronized (mInstallLock) {
21427                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21428                }
21429            } catch (IllegalStateException e) {
21430                // Device was probably ejected, and we'll process that event momentarily
21431                Slog.w(TAG, "Failed to prepare storage: " + e);
21432            }
21433        }
21434
21435        synchronized (mPackages) {
21436            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21437            if (sdkUpdated) {
21438                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21439                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21440            }
21441            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21442                    mPermissionCallback);
21443
21444            // Yay, everything is now upgraded
21445            ver.forceCurrent();
21446
21447            mSettings.writeLPr();
21448        }
21449
21450        for (PackageFreezer freezer : freezers) {
21451            freezer.close();
21452        }
21453
21454        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21455        sendResourcesChangedBroadcast(true, false, loaded, null);
21456        mLoadedVolumes.add(vol.getId());
21457    }
21458
21459    private void unloadPrivatePackages(final VolumeInfo vol) {
21460        mHandler.post(new Runnable() {
21461            @Override
21462            public void run() {
21463                unloadPrivatePackagesInner(vol);
21464            }
21465        });
21466    }
21467
21468    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21469        final String volumeUuid = vol.fsUuid;
21470        if (TextUtils.isEmpty(volumeUuid)) {
21471            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21472            return;
21473        }
21474
21475        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21476        synchronized (mInstallLock) {
21477        synchronized (mPackages) {
21478            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21479            for (PackageSetting ps : packages) {
21480                if (ps.pkg == null) continue;
21481
21482                final ApplicationInfo info = ps.pkg.applicationInfo;
21483                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21484                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21485
21486                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21487                        "unloadPrivatePackagesInner")) {
21488                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21489                            false, null)) {
21490                        unloaded.add(info);
21491                    } else {
21492                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21493                    }
21494                }
21495
21496                // Try very hard to release any references to this package
21497                // so we don't risk the system server being killed due to
21498                // open FDs
21499                AttributeCache.instance().removePackage(ps.name);
21500            }
21501
21502            mSettings.writeLPr();
21503        }
21504        }
21505
21506        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21507        sendResourcesChangedBroadcast(false, false, unloaded, null);
21508        mLoadedVolumes.remove(vol.getId());
21509
21510        // Try very hard to release any references to this path so we don't risk
21511        // the system server being killed due to open FDs
21512        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21513
21514        for (int i = 0; i < 3; i++) {
21515            System.gc();
21516            System.runFinalization();
21517        }
21518    }
21519
21520    private void assertPackageKnown(String volumeUuid, String packageName)
21521            throws PackageManagerException {
21522        synchronized (mPackages) {
21523            // Normalize package name to handle renamed packages
21524            packageName = normalizePackageNameLPr(packageName);
21525
21526            final PackageSetting ps = mSettings.mPackages.get(packageName);
21527            if (ps == null) {
21528                throw new PackageManagerException("Package " + packageName + " is unknown");
21529            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21530                throw new PackageManagerException(
21531                        "Package " + packageName + " found on unknown volume " + volumeUuid
21532                                + "; expected volume " + ps.volumeUuid);
21533            }
21534        }
21535    }
21536
21537    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21538            throws PackageManagerException {
21539        synchronized (mPackages) {
21540            // Normalize package name to handle renamed packages
21541            packageName = normalizePackageNameLPr(packageName);
21542
21543            final PackageSetting ps = mSettings.mPackages.get(packageName);
21544            if (ps == null) {
21545                throw new PackageManagerException("Package " + packageName + " is unknown");
21546            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21547                throw new PackageManagerException(
21548                        "Package " + packageName + " found on unknown volume " + volumeUuid
21549                                + "; expected volume " + ps.volumeUuid);
21550            } else if (!ps.getInstalled(userId)) {
21551                throw new PackageManagerException(
21552                        "Package " + packageName + " not installed for user " + userId);
21553            }
21554        }
21555    }
21556
21557    private List<String> collectAbsoluteCodePaths() {
21558        synchronized (mPackages) {
21559            List<String> codePaths = new ArrayList<>();
21560            final int packageCount = mSettings.mPackages.size();
21561            for (int i = 0; i < packageCount; i++) {
21562                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21563                codePaths.add(ps.codePath.getAbsolutePath());
21564            }
21565            return codePaths;
21566        }
21567    }
21568
21569    /**
21570     * Examine all apps present on given mounted volume, and destroy apps that
21571     * aren't expected, either due to uninstallation or reinstallation on
21572     * another volume.
21573     */
21574    private void reconcileApps(String volumeUuid) {
21575        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21576        List<File> filesToDelete = null;
21577
21578        final File[] files = FileUtils.listFilesOrEmpty(
21579                Environment.getDataAppDirectory(volumeUuid));
21580        for (File file : files) {
21581            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21582                    && !PackageInstallerService.isStageName(file.getName());
21583            if (!isPackage) {
21584                // Ignore entries which are not packages
21585                continue;
21586            }
21587
21588            String absolutePath = file.getAbsolutePath();
21589
21590            boolean pathValid = false;
21591            final int absoluteCodePathCount = absoluteCodePaths.size();
21592            for (int i = 0; i < absoluteCodePathCount; i++) {
21593                String absoluteCodePath = absoluteCodePaths.get(i);
21594                if (absolutePath.startsWith(absoluteCodePath)) {
21595                    pathValid = true;
21596                    break;
21597                }
21598            }
21599
21600            if (!pathValid) {
21601                if (filesToDelete == null) {
21602                    filesToDelete = new ArrayList<>();
21603                }
21604                filesToDelete.add(file);
21605            }
21606        }
21607
21608        if (filesToDelete != null) {
21609            final int fileToDeleteCount = filesToDelete.size();
21610            for (int i = 0; i < fileToDeleteCount; i++) {
21611                File fileToDelete = filesToDelete.get(i);
21612                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21613                synchronized (mInstallLock) {
21614                    removeCodePathLI(fileToDelete);
21615                }
21616            }
21617        }
21618    }
21619
21620    /**
21621     * Reconcile all app data for the given user.
21622     * <p>
21623     * Verifies that directories exist and that ownership and labeling is
21624     * correct for all installed apps on all mounted volumes.
21625     */
21626    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21627        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21628        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21629            final String volumeUuid = vol.getFsUuid();
21630            synchronized (mInstallLock) {
21631                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21632            }
21633        }
21634    }
21635
21636    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21637            boolean migrateAppData) {
21638        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21639    }
21640
21641    /**
21642     * Reconcile all app data on given mounted volume.
21643     * <p>
21644     * Destroys app data that isn't expected, either due to uninstallation or
21645     * reinstallation on another volume.
21646     * <p>
21647     * Verifies that directories exist and that ownership and labeling is
21648     * correct for all installed apps.
21649     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21650     */
21651    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21652            boolean migrateAppData, boolean onlyCoreApps) {
21653        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21654                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21655        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21656
21657        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21658        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21659
21660        // First look for stale data that doesn't belong, and check if things
21661        // have changed since we did our last restorecon
21662        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21663            if (StorageManager.isFileEncryptedNativeOrEmulated()
21664                    && !StorageManager.isUserKeyUnlocked(userId)) {
21665                throw new RuntimeException(
21666                        "Yikes, someone asked us to reconcile CE storage while " + userId
21667                                + " was still locked; this would have caused massive data loss!");
21668            }
21669
21670            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21671            for (File file : files) {
21672                final String packageName = file.getName();
21673                try {
21674                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21675                } catch (PackageManagerException e) {
21676                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21677                    try {
21678                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21679                                StorageManager.FLAG_STORAGE_CE, 0);
21680                    } catch (InstallerException e2) {
21681                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21682                    }
21683                }
21684            }
21685        }
21686        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21687            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21688            for (File file : files) {
21689                final String packageName = file.getName();
21690                try {
21691                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21692                } catch (PackageManagerException e) {
21693                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21694                    try {
21695                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21696                                StorageManager.FLAG_STORAGE_DE, 0);
21697                    } catch (InstallerException e2) {
21698                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21699                    }
21700                }
21701            }
21702        }
21703
21704        // Ensure that data directories are ready to roll for all packages
21705        // installed for this volume and user
21706        final List<PackageSetting> packages;
21707        synchronized (mPackages) {
21708            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21709        }
21710        int preparedCount = 0;
21711        for (PackageSetting ps : packages) {
21712            final String packageName = ps.name;
21713            if (ps.pkg == null) {
21714                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21715                // TODO: might be due to legacy ASEC apps; we should circle back
21716                // and reconcile again once they're scanned
21717                continue;
21718            }
21719            // Skip non-core apps if requested
21720            if (onlyCoreApps && !ps.pkg.coreApp) {
21721                result.add(packageName);
21722                continue;
21723            }
21724
21725            if (ps.getInstalled(userId)) {
21726                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21727                preparedCount++;
21728            }
21729        }
21730
21731        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21732        return result;
21733    }
21734
21735    /**
21736     * Prepare app data for the given app just after it was installed or
21737     * upgraded. This method carefully only touches users that it's installed
21738     * for, and it forces a restorecon to handle any seinfo changes.
21739     * <p>
21740     * Verifies that directories exist and that ownership and labeling is
21741     * correct for all installed apps. If there is an ownership mismatch, it
21742     * will try recovering system apps by wiping data; third-party app data is
21743     * left intact.
21744     * <p>
21745     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21746     */
21747    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21748        final PackageSetting ps;
21749        synchronized (mPackages) {
21750            ps = mSettings.mPackages.get(pkg.packageName);
21751            mSettings.writeKernelMappingLPr(ps);
21752        }
21753
21754        final UserManager um = mContext.getSystemService(UserManager.class);
21755        UserManagerInternal umInternal = getUserManagerInternal();
21756        for (UserInfo user : um.getUsers()) {
21757            final int flags;
21758            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21759                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21760            } else if (umInternal.isUserRunning(user.id)) {
21761                flags = StorageManager.FLAG_STORAGE_DE;
21762            } else {
21763                continue;
21764            }
21765
21766            if (ps.getInstalled(user.id)) {
21767                // TODO: when user data is locked, mark that we're still dirty
21768                prepareAppDataLIF(pkg, user.id, flags);
21769            }
21770        }
21771    }
21772
21773    /**
21774     * Prepare app data for the given app.
21775     * <p>
21776     * Verifies that directories exist and that ownership and labeling is
21777     * correct for all installed apps. If there is an ownership mismatch, this
21778     * will try recovering system apps by wiping data; third-party app data is
21779     * left intact.
21780     */
21781    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21782        if (pkg == null) {
21783            Slog.wtf(TAG, "Package was null!", new Throwable());
21784            return;
21785        }
21786        prepareAppDataLeafLIF(pkg, userId, flags);
21787        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21788        for (int i = 0; i < childCount; i++) {
21789            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21790        }
21791    }
21792
21793    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21794            boolean maybeMigrateAppData) {
21795        prepareAppDataLIF(pkg, userId, flags);
21796
21797        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21798            // We may have just shuffled around app data directories, so
21799            // prepare them one more time
21800            prepareAppDataLIF(pkg, userId, flags);
21801        }
21802    }
21803
21804    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21805        if (DEBUG_APP_DATA) {
21806            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21807                    + Integer.toHexString(flags));
21808        }
21809
21810        final String volumeUuid = pkg.volumeUuid;
21811        final String packageName = pkg.packageName;
21812        final ApplicationInfo app = pkg.applicationInfo;
21813        final int appId = UserHandle.getAppId(app.uid);
21814
21815        Preconditions.checkNotNull(app.seInfo);
21816
21817        long ceDataInode = -1;
21818        try {
21819            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21820                    appId, app.seInfo, app.targetSdkVersion);
21821        } catch (InstallerException e) {
21822            if (app.isSystemApp()) {
21823                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21824                        + ", but trying to recover: " + e);
21825                destroyAppDataLeafLIF(pkg, userId, flags);
21826                try {
21827                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21828                            appId, app.seInfo, app.targetSdkVersion);
21829                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21830                } catch (InstallerException e2) {
21831                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21832                }
21833            } else {
21834                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21835            }
21836        }
21837
21838        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21839            // TODO: mark this structure as dirty so we persist it!
21840            synchronized (mPackages) {
21841                final PackageSetting ps = mSettings.mPackages.get(packageName);
21842                if (ps != null) {
21843                    ps.setCeDataInode(ceDataInode, userId);
21844                }
21845            }
21846        }
21847
21848        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21849    }
21850
21851    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21852        if (pkg == null) {
21853            Slog.wtf(TAG, "Package was null!", new Throwable());
21854            return;
21855        }
21856        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21857        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21858        for (int i = 0; i < childCount; i++) {
21859            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21860        }
21861    }
21862
21863    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21864        final String volumeUuid = pkg.volumeUuid;
21865        final String packageName = pkg.packageName;
21866        final ApplicationInfo app = pkg.applicationInfo;
21867
21868        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21869            // Create a native library symlink only if we have native libraries
21870            // and if the native libraries are 32 bit libraries. We do not provide
21871            // this symlink for 64 bit libraries.
21872            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21873                final String nativeLibPath = app.nativeLibraryDir;
21874                try {
21875                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21876                            nativeLibPath, userId);
21877                } catch (InstallerException e) {
21878                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21879                }
21880            }
21881        }
21882    }
21883
21884    /**
21885     * For system apps on non-FBE devices, this method migrates any existing
21886     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21887     * requested by the app.
21888     */
21889    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21890        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21891                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21892            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21893                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21894            try {
21895                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21896                        storageTarget);
21897            } catch (InstallerException e) {
21898                logCriticalInfo(Log.WARN,
21899                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21900            }
21901            return true;
21902        } else {
21903            return false;
21904        }
21905    }
21906
21907    public PackageFreezer freezePackage(String packageName, String killReason) {
21908        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21909    }
21910
21911    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21912        return new PackageFreezer(packageName, userId, killReason);
21913    }
21914
21915    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21916            String killReason) {
21917        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21918    }
21919
21920    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21921            String killReason) {
21922        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21923            return new PackageFreezer();
21924        } else {
21925            return freezePackage(packageName, userId, killReason);
21926        }
21927    }
21928
21929    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21930            String killReason) {
21931        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21932    }
21933
21934    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21935            String killReason) {
21936        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21937            return new PackageFreezer();
21938        } else {
21939            return freezePackage(packageName, userId, killReason);
21940        }
21941    }
21942
21943    /**
21944     * Class that freezes and kills the given package upon creation, and
21945     * unfreezes it upon closing. This is typically used when doing surgery on
21946     * app code/data to prevent the app from running while you're working.
21947     */
21948    private class PackageFreezer implements AutoCloseable {
21949        private final String mPackageName;
21950        private final PackageFreezer[] mChildren;
21951
21952        private final boolean mWeFroze;
21953
21954        private final AtomicBoolean mClosed = new AtomicBoolean();
21955        private final CloseGuard mCloseGuard = CloseGuard.get();
21956
21957        /**
21958         * Create and return a stub freezer that doesn't actually do anything,
21959         * typically used when someone requested
21960         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21961         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21962         */
21963        public PackageFreezer() {
21964            mPackageName = null;
21965            mChildren = null;
21966            mWeFroze = false;
21967            mCloseGuard.open("close");
21968        }
21969
21970        public PackageFreezer(String packageName, int userId, String killReason) {
21971            synchronized (mPackages) {
21972                mPackageName = packageName;
21973                mWeFroze = mFrozenPackages.add(mPackageName);
21974
21975                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21976                if (ps != null) {
21977                    killApplication(ps.name, ps.appId, userId, killReason);
21978                }
21979
21980                final PackageParser.Package p = mPackages.get(packageName);
21981                if (p != null && p.childPackages != null) {
21982                    final int N = p.childPackages.size();
21983                    mChildren = new PackageFreezer[N];
21984                    for (int i = 0; i < N; i++) {
21985                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21986                                userId, killReason);
21987                    }
21988                } else {
21989                    mChildren = null;
21990                }
21991            }
21992            mCloseGuard.open("close");
21993        }
21994
21995        @Override
21996        protected void finalize() throws Throwable {
21997            try {
21998                if (mCloseGuard != null) {
21999                    mCloseGuard.warnIfOpen();
22000                }
22001
22002                close();
22003            } finally {
22004                super.finalize();
22005            }
22006        }
22007
22008        @Override
22009        public void close() {
22010            mCloseGuard.close();
22011            if (mClosed.compareAndSet(false, true)) {
22012                synchronized (mPackages) {
22013                    if (mWeFroze) {
22014                        mFrozenPackages.remove(mPackageName);
22015                    }
22016
22017                    if (mChildren != null) {
22018                        for (PackageFreezer freezer : mChildren) {
22019                            freezer.close();
22020                        }
22021                    }
22022                }
22023            }
22024        }
22025    }
22026
22027    /**
22028     * Verify that given package is currently frozen.
22029     */
22030    private void checkPackageFrozen(String packageName) {
22031        synchronized (mPackages) {
22032            if (!mFrozenPackages.contains(packageName)) {
22033                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22034            }
22035        }
22036    }
22037
22038    @Override
22039    public int movePackage(final String packageName, final String volumeUuid) {
22040        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22041
22042        final int callingUid = Binder.getCallingUid();
22043        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22044        final int moveId = mNextMoveId.getAndIncrement();
22045        mHandler.post(new Runnable() {
22046            @Override
22047            public void run() {
22048                try {
22049                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22050                } catch (PackageManagerException e) {
22051                    Slog.w(TAG, "Failed to move " + packageName, e);
22052                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22053                }
22054            }
22055        });
22056        return moveId;
22057    }
22058
22059    private void movePackageInternal(final String packageName, final String volumeUuid,
22060            final int moveId, final int callingUid, UserHandle user)
22061                    throws PackageManagerException {
22062        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22063        final PackageManager pm = mContext.getPackageManager();
22064
22065        final boolean currentAsec;
22066        final String currentVolumeUuid;
22067        final File codeFile;
22068        final String installerPackageName;
22069        final String packageAbiOverride;
22070        final int appId;
22071        final String seinfo;
22072        final String label;
22073        final int targetSdkVersion;
22074        final PackageFreezer freezer;
22075        final int[] installedUserIds;
22076
22077        // reader
22078        synchronized (mPackages) {
22079            final PackageParser.Package pkg = mPackages.get(packageName);
22080            final PackageSetting ps = mSettings.mPackages.get(packageName);
22081            if (pkg == null
22082                    || ps == null
22083                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22084                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22085            }
22086            if (pkg.applicationInfo.isSystemApp()) {
22087                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22088                        "Cannot move system application");
22089            }
22090
22091            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22092            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22093                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22094            if (isInternalStorage && !allow3rdPartyOnInternal) {
22095                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22096                        "3rd party apps are not allowed on internal storage");
22097            }
22098
22099            if (pkg.applicationInfo.isExternalAsec()) {
22100                currentAsec = true;
22101                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22102            } else if (pkg.applicationInfo.isForwardLocked()) {
22103                currentAsec = true;
22104                currentVolumeUuid = "forward_locked";
22105            } else {
22106                currentAsec = false;
22107                currentVolumeUuid = ps.volumeUuid;
22108
22109                final File probe = new File(pkg.codePath);
22110                final File probeOat = new File(probe, "oat");
22111                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22112                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22113                            "Move only supported for modern cluster style installs");
22114                }
22115            }
22116
22117            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22118                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22119                        "Package already moved to " + volumeUuid);
22120            }
22121            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22122                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22123                        "Device admin cannot be moved");
22124            }
22125
22126            if (mFrozenPackages.contains(packageName)) {
22127                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22128                        "Failed to move already frozen package");
22129            }
22130
22131            codeFile = new File(pkg.codePath);
22132            installerPackageName = ps.installerPackageName;
22133            packageAbiOverride = ps.cpuAbiOverrideString;
22134            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22135            seinfo = pkg.applicationInfo.seInfo;
22136            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22137            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22138            freezer = freezePackage(packageName, "movePackageInternal");
22139            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22140        }
22141
22142        final Bundle extras = new Bundle();
22143        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22144        extras.putString(Intent.EXTRA_TITLE, label);
22145        mMoveCallbacks.notifyCreated(moveId, extras);
22146
22147        int installFlags;
22148        final boolean moveCompleteApp;
22149        final File measurePath;
22150
22151        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22152            installFlags = INSTALL_INTERNAL;
22153            moveCompleteApp = !currentAsec;
22154            measurePath = Environment.getDataAppDirectory(volumeUuid);
22155        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22156            installFlags = INSTALL_EXTERNAL;
22157            moveCompleteApp = false;
22158            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22159        } else {
22160            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22161            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22162                    || !volume.isMountedWritable()) {
22163                freezer.close();
22164                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22165                        "Move location not mounted private volume");
22166            }
22167
22168            Preconditions.checkState(!currentAsec);
22169
22170            installFlags = INSTALL_INTERNAL;
22171            moveCompleteApp = true;
22172            measurePath = Environment.getDataAppDirectory(volumeUuid);
22173        }
22174
22175        // If we're moving app data around, we need all the users unlocked
22176        if (moveCompleteApp) {
22177            for (int userId : installedUserIds) {
22178                if (StorageManager.isFileEncryptedNativeOrEmulated()
22179                        && !StorageManager.isUserKeyUnlocked(userId)) {
22180                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22181                            "User " + userId + " must be unlocked");
22182                }
22183            }
22184        }
22185
22186        final PackageStats stats = new PackageStats(null, -1);
22187        synchronized (mInstaller) {
22188            for (int userId : installedUserIds) {
22189                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22190                    freezer.close();
22191                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22192                            "Failed to measure package size");
22193                }
22194            }
22195        }
22196
22197        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22198                + stats.dataSize);
22199
22200        final long startFreeBytes = measurePath.getUsableSpace();
22201        final long sizeBytes;
22202        if (moveCompleteApp) {
22203            sizeBytes = stats.codeSize + stats.dataSize;
22204        } else {
22205            sizeBytes = stats.codeSize;
22206        }
22207
22208        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22209            freezer.close();
22210            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22211                    "Not enough free space to move");
22212        }
22213
22214        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22215
22216        final CountDownLatch installedLatch = new CountDownLatch(1);
22217        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22218            @Override
22219            public void onUserActionRequired(Intent intent) throws RemoteException {
22220                throw new IllegalStateException();
22221            }
22222
22223            @Override
22224            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22225                    Bundle extras) throws RemoteException {
22226                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22227                        + PackageManager.installStatusToString(returnCode, msg));
22228
22229                installedLatch.countDown();
22230                freezer.close();
22231
22232                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22233                switch (status) {
22234                    case PackageInstaller.STATUS_SUCCESS:
22235                        mMoveCallbacks.notifyStatusChanged(moveId,
22236                                PackageManager.MOVE_SUCCEEDED);
22237                        break;
22238                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22239                        mMoveCallbacks.notifyStatusChanged(moveId,
22240                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22241                        break;
22242                    default:
22243                        mMoveCallbacks.notifyStatusChanged(moveId,
22244                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22245                        break;
22246                }
22247            }
22248        };
22249
22250        final MoveInfo move;
22251        if (moveCompleteApp) {
22252            // Kick off a thread to report progress estimates
22253            new Thread() {
22254                @Override
22255                public void run() {
22256                    while (true) {
22257                        try {
22258                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22259                                break;
22260                            }
22261                        } catch (InterruptedException ignored) {
22262                        }
22263
22264                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22265                        final int progress = 10 + (int) MathUtils.constrain(
22266                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22267                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22268                    }
22269                }
22270            }.start();
22271
22272            final String dataAppName = codeFile.getName();
22273            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22274                    dataAppName, appId, seinfo, targetSdkVersion);
22275        } else {
22276            move = null;
22277        }
22278
22279        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22280
22281        final Message msg = mHandler.obtainMessage(INIT_COPY);
22282        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22283        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22284                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22285                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22286                PackageManager.INSTALL_REASON_UNKNOWN);
22287        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22288        msg.obj = params;
22289
22290        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22291                System.identityHashCode(msg.obj));
22292        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22293                System.identityHashCode(msg.obj));
22294
22295        mHandler.sendMessage(msg);
22296    }
22297
22298    @Override
22299    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22300        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22301
22302        final int realMoveId = mNextMoveId.getAndIncrement();
22303        final Bundle extras = new Bundle();
22304        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22305        mMoveCallbacks.notifyCreated(realMoveId, extras);
22306
22307        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22308            @Override
22309            public void onCreated(int moveId, Bundle extras) {
22310                // Ignored
22311            }
22312
22313            @Override
22314            public void onStatusChanged(int moveId, int status, long estMillis) {
22315                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22316            }
22317        };
22318
22319        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22320        storage.setPrimaryStorageUuid(volumeUuid, callback);
22321        return realMoveId;
22322    }
22323
22324    @Override
22325    public int getMoveStatus(int moveId) {
22326        mContext.enforceCallingOrSelfPermission(
22327                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22328        return mMoveCallbacks.mLastStatus.get(moveId);
22329    }
22330
22331    @Override
22332    public void registerMoveCallback(IPackageMoveObserver callback) {
22333        mContext.enforceCallingOrSelfPermission(
22334                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22335        mMoveCallbacks.register(callback);
22336    }
22337
22338    @Override
22339    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22340        mContext.enforceCallingOrSelfPermission(
22341                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22342        mMoveCallbacks.unregister(callback);
22343    }
22344
22345    @Override
22346    public boolean setInstallLocation(int loc) {
22347        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22348                null);
22349        if (getInstallLocation() == loc) {
22350            return true;
22351        }
22352        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22353                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22354            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22355                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22356            return true;
22357        }
22358        return false;
22359   }
22360
22361    @Override
22362    public int getInstallLocation() {
22363        // allow instant app access
22364        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22365                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22366                PackageHelper.APP_INSTALL_AUTO);
22367    }
22368
22369    /** Called by UserManagerService */
22370    void cleanUpUser(UserManagerService userManager, int userHandle) {
22371        synchronized (mPackages) {
22372            mDirtyUsers.remove(userHandle);
22373            mUserNeedsBadging.delete(userHandle);
22374            mSettings.removeUserLPw(userHandle);
22375            mPendingBroadcasts.remove(userHandle);
22376            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22377            removeUnusedPackagesLPw(userManager, userHandle);
22378        }
22379    }
22380
22381    /**
22382     * We're removing userHandle and would like to remove any downloaded packages
22383     * that are no longer in use by any other user.
22384     * @param userHandle the user being removed
22385     */
22386    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22387        final boolean DEBUG_CLEAN_APKS = false;
22388        int [] users = userManager.getUserIds();
22389        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22390        while (psit.hasNext()) {
22391            PackageSetting ps = psit.next();
22392            if (ps.pkg == null) {
22393                continue;
22394            }
22395            final String packageName = ps.pkg.packageName;
22396            // Skip over if system app
22397            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22398                continue;
22399            }
22400            if (DEBUG_CLEAN_APKS) {
22401                Slog.i(TAG, "Checking package " + packageName);
22402            }
22403            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22404            if (keep) {
22405                if (DEBUG_CLEAN_APKS) {
22406                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22407                }
22408            } else {
22409                for (int i = 0; i < users.length; i++) {
22410                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22411                        keep = true;
22412                        if (DEBUG_CLEAN_APKS) {
22413                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22414                                    + users[i]);
22415                        }
22416                        break;
22417                    }
22418                }
22419            }
22420            if (!keep) {
22421                if (DEBUG_CLEAN_APKS) {
22422                    Slog.i(TAG, "  Removing package " + packageName);
22423                }
22424                mHandler.post(new Runnable() {
22425                    public void run() {
22426                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22427                                userHandle, 0);
22428                    } //end run
22429                });
22430            }
22431        }
22432    }
22433
22434    /** Called by UserManagerService */
22435    void createNewUser(int userId, String[] disallowedPackages) {
22436        synchronized (mInstallLock) {
22437            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22438        }
22439        synchronized (mPackages) {
22440            scheduleWritePackageRestrictionsLocked(userId);
22441            scheduleWritePackageListLocked(userId);
22442            applyFactoryDefaultBrowserLPw(userId);
22443            primeDomainVerificationsLPw(userId);
22444        }
22445    }
22446
22447    void onNewUserCreated(final int userId) {
22448        synchronized(mPackages) {
22449            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22450            // If permission review for legacy apps is required, we represent
22451            // dagerous permissions for such apps as always granted runtime
22452            // permissions to keep per user flag state whether review is needed.
22453            // Hence, if a new user is added we have to propagate dangerous
22454            // permission grants for these legacy apps.
22455            if (mSettings.mPermissions.mPermissionReviewRequired) {
22456// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22457                mPermissionManager.updateAllPermissions(
22458                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22459                        mPermissionCallback);
22460            }
22461        }
22462    }
22463
22464    @Override
22465    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22466        mContext.enforceCallingOrSelfPermission(
22467                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22468                "Only package verification agents can read the verifier device identity");
22469
22470        synchronized (mPackages) {
22471            return mSettings.getVerifierDeviceIdentityLPw();
22472        }
22473    }
22474
22475    @Override
22476    public void setPermissionEnforced(String permission, boolean enforced) {
22477        // TODO: Now that we no longer change GID for storage, this should to away.
22478        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22479                "setPermissionEnforced");
22480        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22481            synchronized (mPackages) {
22482                if (mSettings.mReadExternalStorageEnforced == null
22483                        || mSettings.mReadExternalStorageEnforced != enforced) {
22484                    mSettings.mReadExternalStorageEnforced =
22485                            enforced ? Boolean.TRUE : Boolean.FALSE;
22486                    mSettings.writeLPr();
22487                }
22488            }
22489            // kill any non-foreground processes so we restart them and
22490            // grant/revoke the GID.
22491            final IActivityManager am = ActivityManager.getService();
22492            if (am != null) {
22493                final long token = Binder.clearCallingIdentity();
22494                try {
22495                    am.killProcessesBelowForeground("setPermissionEnforcement");
22496                } catch (RemoteException e) {
22497                } finally {
22498                    Binder.restoreCallingIdentity(token);
22499                }
22500            }
22501        } else {
22502            throw new IllegalArgumentException("No selective enforcement for " + permission);
22503        }
22504    }
22505
22506    @Override
22507    @Deprecated
22508    public boolean isPermissionEnforced(String permission) {
22509        // allow instant applications
22510        return true;
22511    }
22512
22513    @Override
22514    public boolean isStorageLow() {
22515        // allow instant applications
22516        final long token = Binder.clearCallingIdentity();
22517        try {
22518            final DeviceStorageMonitorInternal
22519                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22520            if (dsm != null) {
22521                return dsm.isMemoryLow();
22522            } else {
22523                return false;
22524            }
22525        } finally {
22526            Binder.restoreCallingIdentity(token);
22527        }
22528    }
22529
22530    @Override
22531    public IPackageInstaller getPackageInstaller() {
22532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22533            return null;
22534        }
22535        return mInstallerService;
22536    }
22537
22538    @Override
22539    public IArtManager getArtManager() {
22540        return mArtManagerService;
22541    }
22542
22543    private boolean userNeedsBadging(int userId) {
22544        int index = mUserNeedsBadging.indexOfKey(userId);
22545        if (index < 0) {
22546            final UserInfo userInfo;
22547            final long token = Binder.clearCallingIdentity();
22548            try {
22549                userInfo = sUserManager.getUserInfo(userId);
22550            } finally {
22551                Binder.restoreCallingIdentity(token);
22552            }
22553            final boolean b;
22554            if (userInfo != null && userInfo.isManagedProfile()) {
22555                b = true;
22556            } else {
22557                b = false;
22558            }
22559            mUserNeedsBadging.put(userId, b);
22560            return b;
22561        }
22562        return mUserNeedsBadging.valueAt(index);
22563    }
22564
22565    @Override
22566    public KeySet getKeySetByAlias(String packageName, String alias) {
22567        if (packageName == null || alias == null) {
22568            return null;
22569        }
22570        synchronized(mPackages) {
22571            final PackageParser.Package pkg = mPackages.get(packageName);
22572            if (pkg == null) {
22573                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22574                throw new IllegalArgumentException("Unknown package: " + packageName);
22575            }
22576            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22577            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22578                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22579                throw new IllegalArgumentException("Unknown package: " + packageName);
22580            }
22581            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22582            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22583        }
22584    }
22585
22586    @Override
22587    public KeySet getSigningKeySet(String packageName) {
22588        if (packageName == null) {
22589            return null;
22590        }
22591        synchronized(mPackages) {
22592            final int callingUid = Binder.getCallingUid();
22593            final int callingUserId = UserHandle.getUserId(callingUid);
22594            final PackageParser.Package pkg = mPackages.get(packageName);
22595            if (pkg == null) {
22596                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22597                throw new IllegalArgumentException("Unknown package: " + packageName);
22598            }
22599            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22600            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22601                // filter and pretend the package doesn't exist
22602                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22603                        + ", uid:" + callingUid);
22604                throw new IllegalArgumentException("Unknown package: " + packageName);
22605            }
22606            if (pkg.applicationInfo.uid != callingUid
22607                    && Process.SYSTEM_UID != callingUid) {
22608                throw new SecurityException("May not access signing KeySet of other apps.");
22609            }
22610            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22611            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22612        }
22613    }
22614
22615    @Override
22616    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22617        final int callingUid = Binder.getCallingUid();
22618        if (getInstantAppPackageName(callingUid) != null) {
22619            return false;
22620        }
22621        if (packageName == null || ks == null) {
22622            return false;
22623        }
22624        synchronized(mPackages) {
22625            final PackageParser.Package pkg = mPackages.get(packageName);
22626            if (pkg == null
22627                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22628                            UserHandle.getUserId(callingUid))) {
22629                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22630                throw new IllegalArgumentException("Unknown package: " + packageName);
22631            }
22632            IBinder ksh = ks.getToken();
22633            if (ksh instanceof KeySetHandle) {
22634                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22635                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22636            }
22637            return false;
22638        }
22639    }
22640
22641    @Override
22642    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22643        final int callingUid = Binder.getCallingUid();
22644        if (getInstantAppPackageName(callingUid) != null) {
22645            return false;
22646        }
22647        if (packageName == null || ks == null) {
22648            return false;
22649        }
22650        synchronized(mPackages) {
22651            final PackageParser.Package pkg = mPackages.get(packageName);
22652            if (pkg == null
22653                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22654                            UserHandle.getUserId(callingUid))) {
22655                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22656                throw new IllegalArgumentException("Unknown package: " + packageName);
22657            }
22658            IBinder ksh = ks.getToken();
22659            if (ksh instanceof KeySetHandle) {
22660                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22661                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22662            }
22663            return false;
22664        }
22665    }
22666
22667    private void deletePackageIfUnusedLPr(final String packageName) {
22668        PackageSetting ps = mSettings.mPackages.get(packageName);
22669        if (ps == null) {
22670            return;
22671        }
22672        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22673            // TODO Implement atomic delete if package is unused
22674            // It is currently possible that the package will be deleted even if it is installed
22675            // after this method returns.
22676            mHandler.post(new Runnable() {
22677                public void run() {
22678                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22679                            0, PackageManager.DELETE_ALL_USERS);
22680                }
22681            });
22682        }
22683    }
22684
22685    /**
22686     * Check and throw if the given before/after packages would be considered a
22687     * downgrade.
22688     */
22689    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22690            throws PackageManagerException {
22691        if (after.getLongVersionCode() < before.getLongVersionCode()) {
22692            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22693                    "Update version code " + after.versionCode + " is older than current "
22694                    + before.getLongVersionCode());
22695        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
22696            if (after.baseRevisionCode < before.baseRevisionCode) {
22697                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22698                        "Update base revision code " + after.baseRevisionCode
22699                        + " is older than current " + before.baseRevisionCode);
22700            }
22701
22702            if (!ArrayUtils.isEmpty(after.splitNames)) {
22703                for (int i = 0; i < after.splitNames.length; i++) {
22704                    final String splitName = after.splitNames[i];
22705                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22706                    if (j != -1) {
22707                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22708                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22709                                    "Update split " + splitName + " revision code "
22710                                    + after.splitRevisionCodes[i] + " is older than current "
22711                                    + before.splitRevisionCodes[j]);
22712                        }
22713                    }
22714                }
22715            }
22716        }
22717    }
22718
22719    private static class MoveCallbacks extends Handler {
22720        private static final int MSG_CREATED = 1;
22721        private static final int MSG_STATUS_CHANGED = 2;
22722
22723        private final RemoteCallbackList<IPackageMoveObserver>
22724                mCallbacks = new RemoteCallbackList<>();
22725
22726        private final SparseIntArray mLastStatus = new SparseIntArray();
22727
22728        public MoveCallbacks(Looper looper) {
22729            super(looper);
22730        }
22731
22732        public void register(IPackageMoveObserver callback) {
22733            mCallbacks.register(callback);
22734        }
22735
22736        public void unregister(IPackageMoveObserver callback) {
22737            mCallbacks.unregister(callback);
22738        }
22739
22740        @Override
22741        public void handleMessage(Message msg) {
22742            final SomeArgs args = (SomeArgs) msg.obj;
22743            final int n = mCallbacks.beginBroadcast();
22744            for (int i = 0; i < n; i++) {
22745                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22746                try {
22747                    invokeCallback(callback, msg.what, args);
22748                } catch (RemoteException ignored) {
22749                }
22750            }
22751            mCallbacks.finishBroadcast();
22752            args.recycle();
22753        }
22754
22755        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22756                throws RemoteException {
22757            switch (what) {
22758                case MSG_CREATED: {
22759                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22760                    break;
22761                }
22762                case MSG_STATUS_CHANGED: {
22763                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22764                    break;
22765                }
22766            }
22767        }
22768
22769        private void notifyCreated(int moveId, Bundle extras) {
22770            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22771
22772            final SomeArgs args = SomeArgs.obtain();
22773            args.argi1 = moveId;
22774            args.arg2 = extras;
22775            obtainMessage(MSG_CREATED, args).sendToTarget();
22776        }
22777
22778        private void notifyStatusChanged(int moveId, int status) {
22779            notifyStatusChanged(moveId, status, -1);
22780        }
22781
22782        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22783            Slog.v(TAG, "Move " + moveId + " status " + status);
22784
22785            final SomeArgs args = SomeArgs.obtain();
22786            args.argi1 = moveId;
22787            args.argi2 = status;
22788            args.arg3 = estMillis;
22789            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22790
22791            synchronized (mLastStatus) {
22792                mLastStatus.put(moveId, status);
22793            }
22794        }
22795    }
22796
22797    private final static class OnPermissionChangeListeners extends Handler {
22798        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22799
22800        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22801                new RemoteCallbackList<>();
22802
22803        public OnPermissionChangeListeners(Looper looper) {
22804            super(looper);
22805        }
22806
22807        @Override
22808        public void handleMessage(Message msg) {
22809            switch (msg.what) {
22810                case MSG_ON_PERMISSIONS_CHANGED: {
22811                    final int uid = msg.arg1;
22812                    handleOnPermissionsChanged(uid);
22813                } break;
22814            }
22815        }
22816
22817        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22818            mPermissionListeners.register(listener);
22819
22820        }
22821
22822        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22823            mPermissionListeners.unregister(listener);
22824        }
22825
22826        public void onPermissionsChanged(int uid) {
22827            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22828                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22829            }
22830        }
22831
22832        private void handleOnPermissionsChanged(int uid) {
22833            final int count = mPermissionListeners.beginBroadcast();
22834            try {
22835                for (int i = 0; i < count; i++) {
22836                    IOnPermissionsChangeListener callback = mPermissionListeners
22837                            .getBroadcastItem(i);
22838                    try {
22839                        callback.onPermissionsChanged(uid);
22840                    } catch (RemoteException e) {
22841                        Log.e(TAG, "Permission listener is dead", e);
22842                    }
22843                }
22844            } finally {
22845                mPermissionListeners.finishBroadcast();
22846            }
22847        }
22848    }
22849
22850    private class PackageManagerNative extends IPackageManagerNative.Stub {
22851        @Override
22852        public String[] getNamesForUids(int[] uids) throws RemoteException {
22853            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22854            // massage results so they can be parsed by the native binder
22855            for (int i = results.length - 1; i >= 0; --i) {
22856                if (results[i] == null) {
22857                    results[i] = "";
22858                }
22859            }
22860            return results;
22861        }
22862
22863        // NB: this differentiates between preloads and sideloads
22864        @Override
22865        public String getInstallerForPackage(String packageName) throws RemoteException {
22866            final String installerName = getInstallerPackageName(packageName);
22867            if (!TextUtils.isEmpty(installerName)) {
22868                return installerName;
22869            }
22870            // differentiate between preload and sideload
22871            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22872            ApplicationInfo appInfo = getApplicationInfo(packageName,
22873                                    /*flags*/ 0,
22874                                    /*userId*/ callingUser);
22875            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22876                return "preload";
22877            }
22878            return "";
22879        }
22880
22881        @Override
22882        public long getVersionCodeForPackage(String packageName) throws RemoteException {
22883            try {
22884                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22885                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22886                if (pInfo != null) {
22887                    return pInfo.getLongVersionCode();
22888                }
22889            } catch (Exception e) {
22890            }
22891            return 0;
22892        }
22893    }
22894
22895    private class PackageManagerInternalImpl extends PackageManagerInternal {
22896        @Override
22897        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22898                int flagValues, int userId) {
22899            PackageManagerService.this.updatePermissionFlags(
22900                    permName, packageName, flagMask, flagValues, userId);
22901        }
22902
22903        @Override
22904        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22905            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22906        }
22907
22908        @Override
22909        public boolean isInstantApp(String packageName, int userId) {
22910            return PackageManagerService.this.isInstantApp(packageName, userId);
22911        }
22912
22913        @Override
22914        public String getInstantAppPackageName(int uid) {
22915            return PackageManagerService.this.getInstantAppPackageName(uid);
22916        }
22917
22918        @Override
22919        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22920            synchronized (mPackages) {
22921                return PackageManagerService.this.filterAppAccessLPr(
22922                        (PackageSetting) pkg.mExtras, callingUid, userId);
22923            }
22924        }
22925
22926        @Override
22927        public PackageParser.Package getPackage(String packageName) {
22928            synchronized (mPackages) {
22929                packageName = resolveInternalPackageNameLPr(
22930                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22931                return mPackages.get(packageName);
22932            }
22933        }
22934
22935        @Override
22936        public PackageParser.Package getDisabledPackage(String packageName) {
22937            synchronized (mPackages) {
22938                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22939                return (ps != null) ? ps.pkg : null;
22940            }
22941        }
22942
22943        @Override
22944        public String getKnownPackageName(int knownPackage, int userId) {
22945            switch(knownPackage) {
22946                case PackageManagerInternal.PACKAGE_BROWSER:
22947                    return getDefaultBrowserPackageName(userId);
22948                case PackageManagerInternal.PACKAGE_INSTALLER:
22949                    return mRequiredInstallerPackage;
22950                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22951                    return mSetupWizardPackage;
22952                case PackageManagerInternal.PACKAGE_SYSTEM:
22953                    return "android";
22954                case PackageManagerInternal.PACKAGE_VERIFIER:
22955                    return mRequiredVerifierPackage;
22956            }
22957            return null;
22958        }
22959
22960        @Override
22961        public boolean isResolveActivityComponent(ComponentInfo component) {
22962            return mResolveActivity.packageName.equals(component.packageName)
22963                    && mResolveActivity.name.equals(component.name);
22964        }
22965
22966        @Override
22967        public void setLocationPackagesProvider(PackagesProvider provider) {
22968            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22969        }
22970
22971        @Override
22972        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22973            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22974        }
22975
22976        @Override
22977        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22978            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22979        }
22980
22981        @Override
22982        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22983            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22984        }
22985
22986        @Override
22987        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22988            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22989        }
22990
22991        @Override
22992        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22993            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22994        }
22995
22996        @Override
22997        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22998            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22999        }
23000
23001        @Override
23002        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23003            synchronized (mPackages) {
23004                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23005            }
23006            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23007        }
23008
23009        @Override
23010        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23011            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23012                    packageName, userId);
23013        }
23014
23015        @Override
23016        public void setKeepUninstalledPackages(final List<String> packageList) {
23017            Preconditions.checkNotNull(packageList);
23018            List<String> removedFromList = null;
23019            synchronized (mPackages) {
23020                if (mKeepUninstalledPackages != null) {
23021                    final int packagesCount = mKeepUninstalledPackages.size();
23022                    for (int i = 0; i < packagesCount; i++) {
23023                        String oldPackage = mKeepUninstalledPackages.get(i);
23024                        if (packageList != null && packageList.contains(oldPackage)) {
23025                            continue;
23026                        }
23027                        if (removedFromList == null) {
23028                            removedFromList = new ArrayList<>();
23029                        }
23030                        removedFromList.add(oldPackage);
23031                    }
23032                }
23033                mKeepUninstalledPackages = new ArrayList<>(packageList);
23034                if (removedFromList != null) {
23035                    final int removedCount = removedFromList.size();
23036                    for (int i = 0; i < removedCount; i++) {
23037                        deletePackageIfUnusedLPr(removedFromList.get(i));
23038                    }
23039                }
23040            }
23041        }
23042
23043        @Override
23044        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23045            synchronized (mPackages) {
23046                return mPermissionManager.isPermissionsReviewRequired(
23047                        mPackages.get(packageName), userId);
23048            }
23049        }
23050
23051        @Override
23052        public PackageInfo getPackageInfo(
23053                String packageName, int flags, int filterCallingUid, int userId) {
23054            return PackageManagerService.this
23055                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23056                            flags, filterCallingUid, userId);
23057        }
23058
23059        @Override
23060        public int getPackageUid(String packageName, int flags, int userId) {
23061            return PackageManagerService.this
23062                    .getPackageUid(packageName, flags, userId);
23063        }
23064
23065        @Override
23066        public ApplicationInfo getApplicationInfo(
23067                String packageName, int flags, int filterCallingUid, int userId) {
23068            return PackageManagerService.this
23069                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23070        }
23071
23072        @Override
23073        public ActivityInfo getActivityInfo(
23074                ComponentName component, int flags, int filterCallingUid, int userId) {
23075            return PackageManagerService.this
23076                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23077        }
23078
23079        @Override
23080        public List<ResolveInfo> queryIntentActivities(
23081                Intent intent, int flags, int filterCallingUid, int userId) {
23082            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23083            return PackageManagerService.this
23084                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23085                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23086        }
23087
23088        @Override
23089        public List<ResolveInfo> queryIntentServices(
23090                Intent intent, int flags, int callingUid, int userId) {
23091            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23092            return PackageManagerService.this
23093                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23094                            false);
23095        }
23096
23097        @Override
23098        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23099                int userId) {
23100            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23101        }
23102
23103        @Override
23104        public void setDeviceAndProfileOwnerPackages(
23105                int deviceOwnerUserId, String deviceOwnerPackage,
23106                SparseArray<String> profileOwnerPackages) {
23107            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23108                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23109        }
23110
23111        @Override
23112        public boolean isPackageDataProtected(int userId, String packageName) {
23113            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23114        }
23115
23116        @Override
23117        public boolean isPackageEphemeral(int userId, String packageName) {
23118            synchronized (mPackages) {
23119                final PackageSetting ps = mSettings.mPackages.get(packageName);
23120                return ps != null ? ps.getInstantApp(userId) : false;
23121            }
23122        }
23123
23124        @Override
23125        public boolean wasPackageEverLaunched(String packageName, int userId) {
23126            synchronized (mPackages) {
23127                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23128            }
23129        }
23130
23131        @Override
23132        public void grantRuntimePermission(String packageName, String permName, int userId,
23133                boolean overridePolicy) {
23134            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23135                    permName, packageName, overridePolicy, getCallingUid(), userId,
23136                    mPermissionCallback);
23137        }
23138
23139        @Override
23140        public void revokeRuntimePermission(String packageName, String permName, int userId,
23141                boolean overridePolicy) {
23142            mPermissionManager.revokeRuntimePermission(
23143                    permName, packageName, overridePolicy, getCallingUid(), userId,
23144                    mPermissionCallback);
23145        }
23146
23147        @Override
23148        public String getNameForUid(int uid) {
23149            return PackageManagerService.this.getNameForUid(uid);
23150        }
23151
23152        @Override
23153        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23154                Intent origIntent, String resolvedType, String callingPackage,
23155                Bundle verificationBundle, int userId) {
23156            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23157                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23158                    userId);
23159        }
23160
23161        @Override
23162        public void grantEphemeralAccess(int userId, Intent intent,
23163                int targetAppId, int ephemeralAppId) {
23164            synchronized (mPackages) {
23165                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23166                        targetAppId, ephemeralAppId);
23167            }
23168        }
23169
23170        @Override
23171        public boolean isInstantAppInstallerComponent(ComponentName component) {
23172            synchronized (mPackages) {
23173                return mInstantAppInstallerActivity != null
23174                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23175            }
23176        }
23177
23178        @Override
23179        public void pruneInstantApps() {
23180            mInstantAppRegistry.pruneInstantApps();
23181        }
23182
23183        @Override
23184        public String getSetupWizardPackageName() {
23185            return mSetupWizardPackage;
23186        }
23187
23188        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23189            if (policy != null) {
23190                mExternalSourcesPolicy = policy;
23191            }
23192        }
23193
23194        @Override
23195        public boolean isPackagePersistent(String packageName) {
23196            synchronized (mPackages) {
23197                PackageParser.Package pkg = mPackages.get(packageName);
23198                return pkg != null
23199                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23200                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23201                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23202                        : false;
23203            }
23204        }
23205
23206        @Override
23207        public boolean isLegacySystemApp(Package pkg) {
23208            synchronized (mPackages) {
23209                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23210                return mPromoteSystemApps
23211                        && ps.isSystem()
23212                        && mExistingSystemPackages.contains(ps.name);
23213            }
23214        }
23215
23216        @Override
23217        public List<PackageInfo> getOverlayPackages(int userId) {
23218            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23219            synchronized (mPackages) {
23220                for (PackageParser.Package p : mPackages.values()) {
23221                    if (p.mOverlayTarget != null) {
23222                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23223                        if (pkg != null) {
23224                            overlayPackages.add(pkg);
23225                        }
23226                    }
23227                }
23228            }
23229            return overlayPackages;
23230        }
23231
23232        @Override
23233        public List<String> getTargetPackageNames(int userId) {
23234            List<String> targetPackages = new ArrayList<>();
23235            synchronized (mPackages) {
23236                for (PackageParser.Package p : mPackages.values()) {
23237                    if (p.mOverlayTarget == null) {
23238                        targetPackages.add(p.packageName);
23239                    }
23240                }
23241            }
23242            return targetPackages;
23243        }
23244
23245        @Override
23246        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23247                @Nullable List<String> overlayPackageNames) {
23248            synchronized (mPackages) {
23249                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23250                    Slog.e(TAG, "failed to find package " + targetPackageName);
23251                    return false;
23252                }
23253                ArrayList<String> overlayPaths = null;
23254                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23255                    final int N = overlayPackageNames.size();
23256                    overlayPaths = new ArrayList<>(N);
23257                    for (int i = 0; i < N; i++) {
23258                        final String packageName = overlayPackageNames.get(i);
23259                        final PackageParser.Package pkg = mPackages.get(packageName);
23260                        if (pkg == null) {
23261                            Slog.e(TAG, "failed to find package " + packageName);
23262                            return false;
23263                        }
23264                        overlayPaths.add(pkg.baseCodePath);
23265                    }
23266                }
23267
23268                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23269                ps.setOverlayPaths(overlayPaths, userId);
23270                return true;
23271            }
23272        }
23273
23274        @Override
23275        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23276                int flags, int userId, boolean resolveForStart) {
23277            return resolveIntentInternal(
23278                    intent, resolvedType, flags, userId, resolveForStart);
23279        }
23280
23281        @Override
23282        public ResolveInfo resolveService(Intent intent, String resolvedType,
23283                int flags, int userId, int callingUid) {
23284            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23285        }
23286
23287        @Override
23288        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23289            return PackageManagerService.this.resolveContentProviderInternal(
23290                    name, flags, userId);
23291        }
23292
23293        @Override
23294        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23295            synchronized (mPackages) {
23296                mIsolatedOwners.put(isolatedUid, ownerUid);
23297            }
23298        }
23299
23300        @Override
23301        public void removeIsolatedUid(int isolatedUid) {
23302            synchronized (mPackages) {
23303                mIsolatedOwners.delete(isolatedUid);
23304            }
23305        }
23306
23307        @Override
23308        public int getUidTargetSdkVersion(int uid) {
23309            synchronized (mPackages) {
23310                return getUidTargetSdkVersionLockedLPr(uid);
23311            }
23312        }
23313
23314        @Override
23315        public boolean canAccessInstantApps(int callingUid, int userId) {
23316            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23317        }
23318
23319        @Override
23320        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23321            synchronized (mPackages) {
23322                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23323            }
23324        }
23325
23326        @Override
23327        public void notifyPackageUse(String packageName, int reason) {
23328            synchronized (mPackages) {
23329                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23330            }
23331        }
23332    }
23333
23334    @Override
23335    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23336        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23337        synchronized (mPackages) {
23338            final long identity = Binder.clearCallingIdentity();
23339            try {
23340                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23341                        packageNames, userId);
23342            } finally {
23343                Binder.restoreCallingIdentity(identity);
23344            }
23345        }
23346    }
23347
23348    @Override
23349    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23350        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23351        synchronized (mPackages) {
23352            final long identity = Binder.clearCallingIdentity();
23353            try {
23354                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23355                        packageNames, userId);
23356            } finally {
23357                Binder.restoreCallingIdentity(identity);
23358            }
23359        }
23360    }
23361
23362    private static void enforceSystemOrPhoneCaller(String tag) {
23363        int callingUid = Binder.getCallingUid();
23364        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23365            throw new SecurityException(
23366                    "Cannot call " + tag + " from UID " + callingUid);
23367        }
23368    }
23369
23370    boolean isHistoricalPackageUsageAvailable() {
23371        return mPackageUsage.isHistoricalPackageUsageAvailable();
23372    }
23373
23374    /**
23375     * Return a <b>copy</b> of the collection of packages known to the package manager.
23376     * @return A copy of the values of mPackages.
23377     */
23378    Collection<PackageParser.Package> getPackages() {
23379        synchronized (mPackages) {
23380            return new ArrayList<>(mPackages.values());
23381        }
23382    }
23383
23384    /**
23385     * Logs process start information (including base APK hash) to the security log.
23386     * @hide
23387     */
23388    @Override
23389    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23390            String apkFile, int pid) {
23391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23392            return;
23393        }
23394        if (!SecurityLog.isLoggingEnabled()) {
23395            return;
23396        }
23397        Bundle data = new Bundle();
23398        data.putLong("startTimestamp", System.currentTimeMillis());
23399        data.putString("processName", processName);
23400        data.putInt("uid", uid);
23401        data.putString("seinfo", seinfo);
23402        data.putString("apkFile", apkFile);
23403        data.putInt("pid", pid);
23404        Message msg = mProcessLoggingHandler.obtainMessage(
23405                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23406        msg.setData(data);
23407        mProcessLoggingHandler.sendMessage(msg);
23408    }
23409
23410    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23411        return mCompilerStats.getPackageStats(pkgName);
23412    }
23413
23414    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23415        return getOrCreateCompilerPackageStats(pkg.packageName);
23416    }
23417
23418    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23419        return mCompilerStats.getOrCreatePackageStats(pkgName);
23420    }
23421
23422    public void deleteCompilerPackageStats(String pkgName) {
23423        mCompilerStats.deletePackageStats(pkgName);
23424    }
23425
23426    @Override
23427    public int getInstallReason(String packageName, int userId) {
23428        final int callingUid = Binder.getCallingUid();
23429        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23430                true /* requireFullPermission */, false /* checkShell */,
23431                "get install reason");
23432        synchronized (mPackages) {
23433            final PackageSetting ps = mSettings.mPackages.get(packageName);
23434            if (filterAppAccessLPr(ps, callingUid, userId)) {
23435                return PackageManager.INSTALL_REASON_UNKNOWN;
23436            }
23437            if (ps != null) {
23438                return ps.getInstallReason(userId);
23439            }
23440        }
23441        return PackageManager.INSTALL_REASON_UNKNOWN;
23442    }
23443
23444    @Override
23445    public boolean canRequestPackageInstalls(String packageName, int userId) {
23446        return canRequestPackageInstallsInternal(packageName, 0, userId,
23447                true /* throwIfPermNotDeclared*/);
23448    }
23449
23450    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23451            boolean throwIfPermNotDeclared) {
23452        int callingUid = Binder.getCallingUid();
23453        int uid = getPackageUid(packageName, 0, userId);
23454        if (callingUid != uid && callingUid != Process.ROOT_UID
23455                && callingUid != Process.SYSTEM_UID) {
23456            throw new SecurityException(
23457                    "Caller uid " + callingUid + " does not own package " + packageName);
23458        }
23459        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23460        if (info == null) {
23461            return false;
23462        }
23463        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23464            return false;
23465        }
23466        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23467        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23468        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23469            if (throwIfPermNotDeclared) {
23470                throw new SecurityException("Need to declare " + appOpPermission
23471                        + " to call this api");
23472            } else {
23473                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23474                return false;
23475            }
23476        }
23477        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23478            return false;
23479        }
23480        if (mExternalSourcesPolicy != null) {
23481            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23482            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23483                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23484            }
23485        }
23486        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23487    }
23488
23489    @Override
23490    public ComponentName getInstantAppResolverSettingsComponent() {
23491        return mInstantAppResolverSettingsComponent;
23492    }
23493
23494    @Override
23495    public ComponentName getInstantAppInstallerComponent() {
23496        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23497            return null;
23498        }
23499        return mInstantAppInstallerActivity == null
23500                ? null : mInstantAppInstallerActivity.getComponentName();
23501    }
23502
23503    @Override
23504    public String getInstantAppAndroidId(String packageName, int userId) {
23505        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23506                "getInstantAppAndroidId");
23507        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23508                true /* requireFullPermission */, false /* checkShell */,
23509                "getInstantAppAndroidId");
23510        // Make sure the target is an Instant App.
23511        if (!isInstantApp(packageName, userId)) {
23512            return null;
23513        }
23514        synchronized (mPackages) {
23515            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23516        }
23517    }
23518
23519    boolean canHaveOatDir(String packageName) {
23520        synchronized (mPackages) {
23521            PackageParser.Package p = mPackages.get(packageName);
23522            if (p == null) {
23523                return false;
23524            }
23525            return p.canHaveOatDir();
23526        }
23527    }
23528
23529    private String getOatDir(PackageParser.Package pkg) {
23530        if (!pkg.canHaveOatDir()) {
23531            return null;
23532        }
23533        File codePath = new File(pkg.codePath);
23534        if (codePath.isDirectory()) {
23535            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23536        }
23537        return null;
23538    }
23539
23540    void deleteOatArtifactsOfPackage(String packageName) {
23541        final String[] instructionSets;
23542        final List<String> codePaths;
23543        final String oatDir;
23544        final PackageParser.Package pkg;
23545        synchronized (mPackages) {
23546            pkg = mPackages.get(packageName);
23547        }
23548        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23549        codePaths = pkg.getAllCodePaths();
23550        oatDir = getOatDir(pkg);
23551
23552        for (String codePath : codePaths) {
23553            for (String isa : instructionSets) {
23554                try {
23555                    mInstaller.deleteOdex(codePath, isa, oatDir);
23556                } catch (InstallerException e) {
23557                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23558                }
23559            }
23560        }
23561    }
23562
23563    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23564        Set<String> unusedPackages = new HashSet<>();
23565        long currentTimeInMillis = System.currentTimeMillis();
23566        synchronized (mPackages) {
23567            for (PackageParser.Package pkg : mPackages.values()) {
23568                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23569                if (ps == null) {
23570                    continue;
23571                }
23572                PackageDexUsage.PackageUseInfo packageUseInfo =
23573                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23574                if (PackageManagerServiceUtils
23575                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23576                                downgradeTimeThresholdMillis, packageUseInfo,
23577                                pkg.getLatestPackageUseTimeInMills(),
23578                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23579                    unusedPackages.add(pkg.packageName);
23580                }
23581            }
23582        }
23583        return unusedPackages;
23584    }
23585}
23586
23587interface PackageSender {
23588    /**
23589     * @param userIds User IDs where the action occurred on a full application
23590     * @param instantUserIds User IDs where the action occurred on an instant application
23591     */
23592    void sendPackageBroadcast(final String action, final String pkg,
23593        final Bundle extras, final int flags, final String targetPkg,
23594        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
23595    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23596        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
23597}
23598