PackageManagerService.java revision a732f014c5743af0dbb7eb2e63474a7147576f9d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
87import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
103import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
104import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
105import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
106import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
107import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
108import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
109import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
114import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
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.PackageStats;
177import android.content.pm.PackageUserState;
178import android.content.pm.ParceledListSlice;
179import android.content.pm.PermissionGroupInfo;
180import android.content.pm.PermissionInfo;
181import android.content.pm.ProviderInfo;
182import android.content.pm.ResolveInfo;
183import android.content.pm.ServiceInfo;
184import android.content.pm.SharedLibraryInfo;
185import android.content.pm.Signature;
186import android.content.pm.UserInfo;
187import android.content.pm.VerifierDeviceIdentity;
188import android.content.pm.VerifierInfo;
189import android.content.pm.VersionedPackage;
190import android.content.res.Resources;
191import android.database.ContentObserver;
192import android.graphics.Bitmap;
193import android.hardware.display.DisplayManager;
194import android.net.Uri;
195import android.os.Binder;
196import android.os.Build;
197import android.os.Bundle;
198import android.os.Debug;
199import android.os.Environment;
200import android.os.Environment.UserEnvironment;
201import android.os.FileUtils;
202import android.os.Handler;
203import android.os.IBinder;
204import android.os.Looper;
205import android.os.Message;
206import android.os.Parcel;
207import android.os.ParcelFileDescriptor;
208import android.os.PatternMatcher;
209import android.os.Process;
210import android.os.RemoteCallbackList;
211import android.os.RemoteException;
212import android.os.ResultReceiver;
213import android.os.SELinux;
214import android.os.ServiceManager;
215import android.os.ShellCallback;
216import android.os.SystemClock;
217import android.os.SystemProperties;
218import android.os.Trace;
219import android.os.UserHandle;
220import android.os.UserManager;
221import android.os.UserManagerInternal;
222import android.os.storage.IStorageManager;
223import android.os.storage.StorageEventListener;
224import android.os.storage.StorageManager;
225import android.os.storage.StorageManagerInternal;
226import android.os.storage.VolumeInfo;
227import android.os.storage.VolumeRecord;
228import android.provider.Settings.Global;
229import android.provider.Settings.Secure;
230import android.security.KeyStore;
231import android.security.SystemKeyStore;
232import android.service.pm.PackageServiceDumpProto;
233import android.system.ErrnoException;
234import android.system.Os;
235import android.text.TextUtils;
236import android.text.format.DateUtils;
237import android.util.ArrayMap;
238import android.util.ArraySet;
239import android.util.Base64;
240import android.util.DisplayMetrics;
241import android.util.EventLog;
242import android.util.ExceptionUtils;
243import android.util.Log;
244import android.util.LogPrinter;
245import android.util.MathUtils;
246import android.util.PackageUtils;
247import android.util.Pair;
248import android.util.PrintStreamPrinter;
249import android.util.Slog;
250import android.util.SparseArray;
251import android.util.SparseBooleanArray;
252import android.util.SparseIntArray;
253import android.util.TimingsTraceLog;
254import android.util.Xml;
255import android.util.jar.StrictJarFile;
256import android.util.proto.ProtoOutputStream;
257import android.view.Display;
258
259import com.android.internal.R;
260import com.android.internal.annotations.GuardedBy;
261import com.android.internal.app.IMediaContainerService;
262import com.android.internal.app.ResolverActivity;
263import com.android.internal.content.NativeLibraryHelper;
264import com.android.internal.content.PackageHelper;
265import com.android.internal.logging.MetricsLogger;
266import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
267import com.android.internal.os.IParcelFileDescriptorFactory;
268import com.android.internal.os.RoSystemProperties;
269import com.android.internal.os.SomeArgs;
270import com.android.internal.os.Zygote;
271import com.android.internal.telephony.CarrierAppUtils;
272import com.android.internal.util.ArrayUtils;
273import com.android.internal.util.ConcurrentUtils;
274import com.android.internal.util.DumpUtils;
275import com.android.internal.util.FastPrintWriter;
276import com.android.internal.util.FastXmlSerializer;
277import com.android.internal.util.IndentingPrintWriter;
278import com.android.internal.util.Preconditions;
279import com.android.internal.util.XmlUtils;
280import com.android.server.AttributeCache;
281import com.android.server.DeviceIdleController;
282import com.android.server.EventLogTags;
283import com.android.server.FgThread;
284import com.android.server.IntentResolver;
285import com.android.server.LocalServices;
286import com.android.server.LockGuard;
287import com.android.server.ServiceThread;
288import com.android.server.SystemConfig;
289import com.android.server.SystemServerInitThreadPool;
290import com.android.server.Watchdog;
291import com.android.server.net.NetworkPolicyManagerInternal;
292import com.android.server.pm.Installer.InstallerException;
293import com.android.server.pm.Settings.DatabaseVersion;
294import com.android.server.pm.Settings.VersionInfo;
295import com.android.server.pm.dex.DexLogger;
296import com.android.server.pm.dex.DexManager;
297import com.android.server.pm.dex.DexoptOptions;
298import com.android.server.pm.dex.PackageDexUsage;
299import com.android.server.pm.permission.BasePermission;
300import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
301import com.android.server.pm.permission.PermissionManagerService;
302import com.android.server.pm.permission.PermissionManagerInternal;
303import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
304import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
305import com.android.server.pm.permission.PermissionsState;
306import com.android.server.pm.permission.PermissionsState.PermissionState;
307import com.android.server.storage.DeviceStorageMonitorInternal;
308
309import dalvik.system.CloseGuard;
310import dalvik.system.DexFile;
311import dalvik.system.VMRuntime;
312
313import libcore.io.IoUtils;
314import libcore.io.Streams;
315import libcore.util.EmptyArray;
316
317import org.xmlpull.v1.XmlPullParser;
318import org.xmlpull.v1.XmlPullParserException;
319import org.xmlpull.v1.XmlSerializer;
320
321import java.io.BufferedOutputStream;
322import java.io.BufferedReader;
323import java.io.ByteArrayInputStream;
324import java.io.ByteArrayOutputStream;
325import java.io.File;
326import java.io.FileDescriptor;
327import java.io.FileInputStream;
328import java.io.FileOutputStream;
329import java.io.FileReader;
330import java.io.FilenameFilter;
331import java.io.IOException;
332import java.io.InputStream;
333import java.io.OutputStream;
334import java.io.PrintWriter;
335import java.lang.annotation.Retention;
336import java.lang.annotation.RetentionPolicy;
337import java.nio.charset.StandardCharsets;
338import java.security.DigestInputStream;
339import java.security.MessageDigest;
340import java.security.NoSuchAlgorithmException;
341import java.security.PublicKey;
342import java.security.SecureRandom;
343import java.security.cert.Certificate;
344import java.security.cert.CertificateEncodingException;
345import java.security.cert.CertificateException;
346import java.text.SimpleDateFormat;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.Date;
353import java.util.HashMap;
354import java.util.HashSet;
355import java.util.Iterator;
356import java.util.LinkedHashSet;
357import java.util.List;
358import java.util.Map;
359import java.util.Objects;
360import java.util.Set;
361import java.util.concurrent.CountDownLatch;
362import java.util.concurrent.Future;
363import java.util.concurrent.TimeUnit;
364import java.util.concurrent.atomic.AtomicBoolean;
365import java.util.concurrent.atomic.AtomicInteger;
366import java.util.zip.GZIPInputStream;
367
368/**
369 * Keep track of all those APKs everywhere.
370 * <p>
371 * Internally there are two important locks:
372 * <ul>
373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
374 * and other related state. It is a fine-grained lock that should only be held
375 * momentarily, as it's one of the most contended locks in the system.
376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
377 * operations typically involve heavy lifting of application data on disk. Since
378 * {@code installd} is single-threaded, and it's operations can often be slow,
379 * this lock should never be acquired while already holding {@link #mPackages}.
380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
381 * holding {@link #mInstallLock}.
382 * </ul>
383 * Many internal methods rely on the caller to hold the appropriate locks, and
384 * this contract is expressed through method name suffixes:
385 * <ul>
386 * <li>fooLI(): the caller must hold {@link #mInstallLock}
387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
388 * being modified must be frozen
389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
391 * </ul>
392 * <p>
393 * Because this class is very central to the platform's security; please run all
394 * CTS and unit tests whenever making modifications:
395 *
396 * <pre>
397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
399 * </pre>
400 */
401public class PackageManagerService extends IPackageManager.Stub
402        implements PackageSender {
403    static final String TAG = "PackageManager";
404    public static final boolean DEBUG_SETTINGS = false;
405    static final boolean DEBUG_PREFERRED = false;
406    static final boolean DEBUG_UPGRADE = false;
407    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
408    private static final boolean DEBUG_BACKUP = false;
409    public static final boolean DEBUG_INSTALL = false;
410    public static final boolean DEBUG_REMOVE = false;
411    private static final boolean DEBUG_BROADCASTS = false;
412    private static final boolean DEBUG_SHOW_INFO = false;
413    private static final boolean DEBUG_PACKAGE_INFO = false;
414    private static final boolean DEBUG_INTENT_MATCHING = false;
415    public static final boolean DEBUG_PACKAGE_SCANNING = false;
416    private static final boolean DEBUG_VERIFY = false;
417    private static final boolean DEBUG_FILTERS = false;
418    public static final boolean DEBUG_PERMISSIONS = false;
419    private static final boolean DEBUG_SHARED_LIBRARIES = false;
420    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
421
422    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
423    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
424    // user, but by default initialize to this.
425    public static final boolean DEBUG_DEXOPT = false;
426
427    private static final boolean DEBUG_ABI_SELECTION = false;
428    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
429    private static final boolean DEBUG_TRIAGED_MISSING = false;
430    private static final boolean DEBUG_APP_DATA = false;
431
432    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
433    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
434
435    private static final boolean HIDE_EPHEMERAL_APIS = false;
436
437    private static final boolean ENABLE_FREE_CACHE_V2 =
438            SystemProperties.getBoolean("fw.free_cache_v2", true);
439
440    private static final int RADIO_UID = Process.PHONE_UID;
441    private static final int LOG_UID = Process.LOG_UID;
442    private static final int NFC_UID = Process.NFC_UID;
443    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
444    private static final int SHELL_UID = Process.SHELL_UID;
445
446    // Suffix used during package installation when copying/moving
447    // package apks to install directory.
448    private static final String INSTALL_PACKAGE_SUFFIX = "-";
449
450    static final int SCAN_NO_DEX = 1<<0;
451    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
452    static final int SCAN_NEW_INSTALL = 1<<2;
453    static final int SCAN_UPDATE_TIME = 1<<3;
454    static final int SCAN_BOOTING = 1<<4;
455    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
456    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
457    static final int SCAN_REQUIRE_KNOWN = 1<<7;
458    static final int SCAN_MOVE = 1<<8;
459    static final int SCAN_INITIAL = 1<<9;
460    static final int SCAN_CHECK_ONLY = 1<<10;
461    static final int SCAN_DONT_KILL_APP = 1<<11;
462    static final int SCAN_IGNORE_FROZEN = 1<<12;
463    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
464    static final int SCAN_AS_INSTANT_APP = 1<<14;
465    static final int SCAN_AS_FULL_APP = 1<<15;
466    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
467    static final int SCAN_AS_SYSTEM = 1<<17;
468    static final int SCAN_AS_PRIVILEGED = 1<<18;
469    static final int SCAN_AS_OEM = 1<<19;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
477            SCAN_TRUSTED_OVERLAY,
478            SCAN_DELETE_DATA_ON_FAILURES,
479            SCAN_REQUIRE_KNOWN,
480            SCAN_MOVE,
481            SCAN_INITIAL,
482            SCAN_CHECK_ONLY,
483            SCAN_DONT_KILL_APP,
484            SCAN_IGNORE_FROZEN,
485            SCAN_FIRST_BOOT_OR_UPGRADE,
486            SCAN_AS_INSTANT_APP,
487            SCAN_AS_FULL_APP,
488            SCAN_AS_VIRTUAL_PRELOAD,
489    })
490    @Retention(RetentionPolicy.SOURCE)
491    public @interface ScanFlags {}
492
493    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
494    /** Extension of the compressed packages */
495    public final static String COMPRESSED_EXTENSION = ".gz";
496    /** Suffix of stub packages on the system partition */
497    public final static String STUB_SUFFIX = "-Stub";
498
499    private static final int[] EMPTY_INT_ARRAY = new int[0];
500
501    private static final int TYPE_UNKNOWN = 0;
502    private static final int TYPE_ACTIVITY = 1;
503    private static final int TYPE_RECEIVER = 2;
504    private static final int TYPE_SERVICE = 3;
505    private static final int TYPE_PROVIDER = 4;
506    @IntDef(prefix = { "TYPE_" }, value = {
507            TYPE_UNKNOWN,
508            TYPE_ACTIVITY,
509            TYPE_RECEIVER,
510            TYPE_SERVICE,
511            TYPE_PROVIDER,
512    })
513    @Retention(RetentionPolicy.SOURCE)
514    public @interface ComponentType {}
515
516    /**
517     * Timeout (in milliseconds) after which the watchdog should declare that
518     * our handler thread is wedged.  The usual default for such things is one
519     * minute but we sometimes do very lengthy I/O operations on this thread,
520     * such as installing multi-gigabyte applications, so ours needs to be longer.
521     */
522    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
523
524    /**
525     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
526     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
527     * settings entry if available, otherwise we use the hardcoded default.  If it's been
528     * more than this long since the last fstrim, we force one during the boot sequence.
529     *
530     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
531     * one gets run at the next available charging+idle time.  This final mandatory
532     * no-fstrim check kicks in only of the other scheduling criteria is never met.
533     */
534    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
535
536    /**
537     * Whether verification is enabled by default.
538     */
539    private static final boolean DEFAULT_VERIFY_ENABLE = true;
540
541    /**
542     * The default maximum time to wait for the verification agent to return in
543     * milliseconds.
544     */
545    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
546
547    /**
548     * The default response for package verification timeout.
549     *
550     * This can be either PackageManager.VERIFICATION_ALLOW or
551     * PackageManager.VERIFICATION_REJECT.
552     */
553    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
554
555    public static final String PLATFORM_PACKAGE_NAME = "android";
556
557    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
558
559    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
560            DEFAULT_CONTAINER_PACKAGE,
561            "com.android.defcontainer.DefaultContainerService");
562
563    private static final String KILL_APP_REASON_GIDS_CHANGED =
564            "permission grant or revoke changed gids";
565
566    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
567            "permissions revoked";
568
569    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
570
571    private static final String PACKAGE_SCHEME = "package";
572
573    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
574
575    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
576
577    /** Canonical intent used to identify what counts as a "web browser" app */
578    private static final Intent sBrowserIntent;
579    static {
580        sBrowserIntent = new Intent();
581        sBrowserIntent.setAction(Intent.ACTION_VIEW);
582        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
583        sBrowserIntent.setData(Uri.parse("http:"));
584    }
585
586    /**
587     * The set of all protected actions [i.e. those actions for which a high priority
588     * intent filter is disallowed].
589     */
590    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
591    static {
592        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
593        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
595        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
596    }
597
598    // Compilation reasons.
599    public static final int REASON_FIRST_BOOT = 0;
600    public static final int REASON_BOOT = 1;
601    public static final int REASON_INSTALL = 2;
602    public static final int REASON_BACKGROUND_DEXOPT = 3;
603    public static final int REASON_AB_OTA = 4;
604    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
605    public static final int REASON_SHARED = 6;
606
607    public static final int REASON_LAST = REASON_SHARED;
608
609    /**
610     * Version number for the package parser cache. Increment this whenever the format or
611     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
612     */
613    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
614
615    /**
616     * Whether the package parser cache is enabled.
617     */
618    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
619
620    final ServiceThread mHandlerThread;
621
622    final PackageHandler mHandler;
623
624    private final ProcessLoggingHandler mProcessLoggingHandler;
625
626    /**
627     * Messages for {@link #mHandler} that need to wait for system ready before
628     * being dispatched.
629     */
630    private ArrayList<Message> mPostSystemReadyMessages;
631
632    final int mSdkVersion = Build.VERSION.SDK_INT;
633
634    final Context mContext;
635    final boolean mFactoryTest;
636    final boolean mOnlyCore;
637    final DisplayMetrics mMetrics;
638    final int mDefParseFlags;
639    final String[] mSeparateProcesses;
640    final boolean mIsUpgrade;
641    final boolean mIsPreNUpgrade;
642    final boolean mIsPreNMR1Upgrade;
643
644    // Have we told the Activity Manager to whitelist the default container service by uid yet?
645    @GuardedBy("mPackages")
646    boolean mDefaultContainerWhitelisted = false;
647
648    @GuardedBy("mPackages")
649    private boolean mDexOptDialogShown;
650
651    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
652    // LOCK HELD.  Can be called with mInstallLock held.
653    @GuardedBy("mInstallLock")
654    final Installer mInstaller;
655
656    /** Directory where installed third-party apps stored */
657    final File mAppInstallDir;
658
659    /**
660     * Directory to which applications installed internally have their
661     * 32 bit native libraries copied.
662     */
663    private File mAppLib32InstallDir;
664
665    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
666    // apps.
667    final File mDrmAppPrivateInstallDir;
668
669    // ----------------------------------------------------------------
670
671    // Lock for state used when installing and doing other long running
672    // operations.  Methods that must be called with this lock held have
673    // the suffix "LI".
674    final Object mInstallLock = new Object();
675
676    // ----------------------------------------------------------------
677
678    // Keys are String (package name), values are Package.  This also serves
679    // as the lock for the global state.  Methods that must be called with
680    // this lock held have the prefix "LP".
681    @GuardedBy("mPackages")
682    final ArrayMap<String, PackageParser.Package> mPackages =
683            new ArrayMap<String, PackageParser.Package>();
684
685    final ArrayMap<String, Set<String>> mKnownCodebase =
686            new ArrayMap<String, Set<String>>();
687
688    // Keys are isolated uids and values are the uid of the application
689    // that created the isolated proccess.
690    @GuardedBy("mPackages")
691    final SparseIntArray mIsolatedOwners = new SparseIntArray();
692
693    /**
694     * Tracks new system packages [received in an OTA] that we expect to
695     * find updated user-installed versions. Keys are package name, values
696     * are package location.
697     */
698    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
699    /**
700     * Tracks high priority intent filters for protected actions. During boot, certain
701     * filter actions are protected and should never be allowed to have a high priority
702     * intent filter for them. However, there is one, and only one exception -- the
703     * setup wizard. It must be able to define a high priority intent filter for these
704     * actions to ensure there are no escapes from the wizard. We need to delay processing
705     * of these during boot as we need to look at all of the system packages in order
706     * to know which component is the setup wizard.
707     */
708    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
709    /**
710     * Whether or not processing protected filters should be deferred.
711     */
712    private boolean mDeferProtectedFilters = true;
713
714    /**
715     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
716     */
717    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
718    /**
719     * Whether or not system app permissions should be promoted from install to runtime.
720     */
721    boolean mPromoteSystemApps;
722
723    @GuardedBy("mPackages")
724    final Settings mSettings;
725
726    /**
727     * Set of package names that are currently "frozen", which means active
728     * surgery is being done on the code/data for that package. The platform
729     * will refuse to launch frozen packages to avoid race conditions.
730     *
731     * @see PackageFreezer
732     */
733    @GuardedBy("mPackages")
734    final ArraySet<String> mFrozenPackages = new ArraySet<>();
735
736    final ProtectedPackages mProtectedPackages;
737
738    @GuardedBy("mLoadedVolumes")
739    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
740
741    boolean mFirstBoot;
742
743    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
744
745    @GuardedBy("mAvailableFeatures")
746    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
747
748    // If mac_permissions.xml was found for seinfo labeling.
749    boolean mFoundPolicyFile;
750
751    private final InstantAppRegistry mInstantAppRegistry;
752
753    @GuardedBy("mPackages")
754    int mChangedPackagesSequenceNumber;
755    /**
756     * List of changed [installed, removed or updated] packages.
757     * mapping from user id -> sequence number -> package name
758     */
759    @GuardedBy("mPackages")
760    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
761    /**
762     * The sequence number of the last change to a package.
763     * mapping from user id -> package name -> sequence number
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
767
768    class PackageParserCallback implements PackageParser.Callback {
769        @Override public final boolean hasFeature(String feature) {
770            return PackageManagerService.this.hasSystemFeature(feature, 0);
771        }
772
773        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
774                Collection<PackageParser.Package> allPackages, String targetPackageName) {
775            List<PackageParser.Package> overlayPackages = null;
776            for (PackageParser.Package p : allPackages) {
777                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
778                    if (overlayPackages == null) {
779                        overlayPackages = new ArrayList<PackageParser.Package>();
780                    }
781                    overlayPackages.add(p);
782                }
783            }
784            if (overlayPackages != null) {
785                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
786                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
787                        return p1.mOverlayPriority - p2.mOverlayPriority;
788                    }
789                };
790                Collections.sort(overlayPackages, cmp);
791            }
792            return overlayPackages;
793        }
794
795        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
796                String targetPackageName, String targetPath) {
797            if ("android".equals(targetPackageName)) {
798                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
799                // native AssetManager.
800                return null;
801            }
802            List<PackageParser.Package> overlayPackages =
803                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
804            if (overlayPackages == null || overlayPackages.isEmpty()) {
805                return null;
806            }
807            List<String> overlayPathList = null;
808            for (PackageParser.Package overlayPackage : overlayPackages) {
809                if (targetPath == null) {
810                    if (overlayPathList == null) {
811                        overlayPathList = new ArrayList<String>();
812                    }
813                    overlayPathList.add(overlayPackage.baseCodePath);
814                    continue;
815                }
816
817                try {
818                    // Creates idmaps for system to parse correctly the Android manifest of the
819                    // target package.
820                    //
821                    // OverlayManagerService will update each of them with a correct gid from its
822                    // target package app id.
823                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
824                            UserHandle.getSharedAppGid(
825                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
826                    if (overlayPathList == null) {
827                        overlayPathList = new ArrayList<String>();
828                    }
829                    overlayPathList.add(overlayPackage.baseCodePath);
830                } catch (InstallerException e) {
831                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
832                            overlayPackage.baseCodePath);
833                }
834            }
835            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
836        }
837
838        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
839            synchronized (mPackages) {
840                return getStaticOverlayPathsLocked(
841                        mPackages.values(), targetPackageName, targetPath);
842            }
843        }
844
845        @Override public final String[] getOverlayApks(String targetPackageName) {
846            return getStaticOverlayPaths(targetPackageName, null);
847        }
848
849        @Override public final String[] getOverlayPaths(String targetPackageName,
850                String targetPath) {
851            return getStaticOverlayPaths(targetPackageName, targetPath);
852        }
853    }
854
855    class ParallelPackageParserCallback extends PackageParserCallback {
856        List<PackageParser.Package> mOverlayPackages = null;
857
858        void findStaticOverlayPackages() {
859            synchronized (mPackages) {
860                for (PackageParser.Package p : mPackages.values()) {
861                    if (p.mIsStaticOverlay) {
862                        if (mOverlayPackages == null) {
863                            mOverlayPackages = new ArrayList<PackageParser.Package>();
864                        }
865                        mOverlayPackages.add(p);
866                    }
867                }
868            }
869        }
870
871        @Override
872        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
873            // We can trust mOverlayPackages without holding mPackages because package uninstall
874            // can't happen while running parallel parsing.
875            // Moreover holding mPackages on each parsing thread causes dead-lock.
876            return mOverlayPackages == null ? null :
877                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
878        }
879    }
880
881    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
882    final ParallelPackageParserCallback mParallelPackageParserCallback =
883            new ParallelPackageParserCallback();
884
885    public static final class SharedLibraryEntry {
886        public final @Nullable String path;
887        public final @Nullable String apk;
888        public final @NonNull SharedLibraryInfo info;
889
890        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
891                String declaringPackageName, int declaringPackageVersionCode) {
892            path = _path;
893            apk = _apk;
894            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
895                    declaringPackageName, declaringPackageVersionCode), null);
896        }
897    }
898
899    // Currently known shared libraries.
900    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
901    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
902            new ArrayMap<>();
903
904    // All available activities, for your resolving pleasure.
905    final ActivityIntentResolver mActivities =
906            new ActivityIntentResolver();
907
908    // All available receivers, for your resolving pleasure.
909    final ActivityIntentResolver mReceivers =
910            new ActivityIntentResolver();
911
912    // All available services, for your resolving pleasure.
913    final ServiceIntentResolver mServices = new ServiceIntentResolver();
914
915    // All available providers, for your resolving pleasure.
916    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
917
918    // Mapping from provider base names (first directory in content URI codePath)
919    // to the provider information.
920    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
921            new ArrayMap<String, PackageParser.Provider>();
922
923    // Mapping from instrumentation class names to info about them.
924    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
925            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
926
927    // Packages whose data we have transfered into another package, thus
928    // should no longer exist.
929    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
930
931    // Broadcast actions that are only available to the system.
932    @GuardedBy("mProtectedBroadcasts")
933    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
934
935    /** List of packages waiting for verification. */
936    final SparseArray<PackageVerificationState> mPendingVerification
937            = new SparseArray<PackageVerificationState>();
938
939    final PackageInstallerService mInstallerService;
940
941    private final PackageDexOptimizer mPackageDexOptimizer;
942    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
943    // is used by other apps).
944    private final DexManager mDexManager;
945
946    private AtomicInteger mNextMoveId = new AtomicInteger();
947    private final MoveCallbacks mMoveCallbacks;
948
949    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
950
951    // Cache of users who need badging.
952    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
953
954    /** Token for keys in mPendingVerification. */
955    private int mPendingVerificationToken = 0;
956
957    volatile boolean mSystemReady;
958    volatile boolean mSafeMode;
959    volatile boolean mHasSystemUidErrors;
960    private volatile boolean mEphemeralAppsDisabled;
961
962    ApplicationInfo mAndroidApplication;
963    final ActivityInfo mResolveActivity = new ActivityInfo();
964    final ResolveInfo mResolveInfo = new ResolveInfo();
965    ComponentName mResolveComponentName;
966    PackageParser.Package mPlatformPackage;
967    ComponentName mCustomResolverComponentName;
968
969    boolean mResolverReplaced = false;
970
971    private final @Nullable ComponentName mIntentFilterVerifierComponent;
972    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
973
974    private int mIntentFilterVerificationToken = 0;
975
976    /** The service connection to the ephemeral resolver */
977    final EphemeralResolverConnection mInstantAppResolverConnection;
978    /** Component used to show resolver settings for Instant Apps */
979    final ComponentName mInstantAppResolverSettingsComponent;
980
981    /** Activity used to install instant applications */
982    ActivityInfo mInstantAppInstallerActivity;
983    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
984
985    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
986            = new SparseArray<IntentFilterVerificationState>();
987
988    // TODO remove this and go through mPermissonManager directly
989    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
990    private final PermissionManagerInternal mPermissionManager;
991
992    // List of packages names to keep cached, even if they are uninstalled for all users
993    private List<String> mKeepUninstalledPackages;
994
995    private UserManagerInternal mUserManagerInternal;
996
997    private DeviceIdleController.LocalService mDeviceIdleController;
998
999    private File mCacheDir;
1000
1001    private Future<?> mPrepareAppDataFuture;
1002
1003    private static class IFVerificationParams {
1004        PackageParser.Package pkg;
1005        boolean replacing;
1006        int userId;
1007        int verifierUid;
1008
1009        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1010                int _userId, int _verifierUid) {
1011            pkg = _pkg;
1012            replacing = _replacing;
1013            userId = _userId;
1014            replacing = _replacing;
1015            verifierUid = _verifierUid;
1016        }
1017    }
1018
1019    private interface IntentFilterVerifier<T extends IntentFilter> {
1020        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1021                                               T filter, String packageName);
1022        void startVerifications(int userId);
1023        void receiveVerificationResponse(int verificationId);
1024    }
1025
1026    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1027        private Context mContext;
1028        private ComponentName mIntentFilterVerifierComponent;
1029        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1030
1031        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1032            mContext = context;
1033            mIntentFilterVerifierComponent = verifierComponent;
1034        }
1035
1036        private String getDefaultScheme() {
1037            return IntentFilter.SCHEME_HTTPS;
1038        }
1039
1040        @Override
1041        public void startVerifications(int userId) {
1042            // Launch verifications requests
1043            int count = mCurrentIntentFilterVerifications.size();
1044            for (int n=0; n<count; n++) {
1045                int verificationId = mCurrentIntentFilterVerifications.get(n);
1046                final IntentFilterVerificationState ivs =
1047                        mIntentFilterVerificationStates.get(verificationId);
1048
1049                String packageName = ivs.getPackageName();
1050
1051                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1052                final int filterCount = filters.size();
1053                ArraySet<String> domainsSet = new ArraySet<>();
1054                for (int m=0; m<filterCount; m++) {
1055                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1056                    domainsSet.addAll(filter.getHostsList());
1057                }
1058                synchronized (mPackages) {
1059                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1060                            packageName, domainsSet) != null) {
1061                        scheduleWriteSettingsLocked();
1062                    }
1063                }
1064                sendVerificationRequest(verificationId, ivs);
1065            }
1066            mCurrentIntentFilterVerifications.clear();
1067        }
1068
1069        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1070            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1073                    verificationId);
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1076                    getDefaultScheme());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1079                    ivs.getHostsString());
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1082                    ivs.getPackageName());
1083            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1084            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1085
1086            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1087            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1088                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1089                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1090
1091            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1092            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1093                    "Sending IntentFilter verification broadcast");
1094        }
1095
1096        public void receiveVerificationResponse(int verificationId) {
1097            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1098
1099            final boolean verified = ivs.isVerified();
1100
1101            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1102            final int count = filters.size();
1103            if (DEBUG_DOMAIN_VERIFICATION) {
1104                Slog.i(TAG, "Received verification response " + verificationId
1105                        + " for " + count + " filters, verified=" + verified);
1106            }
1107            for (int n=0; n<count; n++) {
1108                PackageParser.ActivityIntentInfo filter = filters.get(n);
1109                filter.setVerified(verified);
1110
1111                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1112                        + " verified with result:" + verified + " and hosts:"
1113                        + ivs.getHostsString());
1114            }
1115
1116            mIntentFilterVerificationStates.remove(verificationId);
1117
1118            final String packageName = ivs.getPackageName();
1119            IntentFilterVerificationInfo ivi = null;
1120
1121            synchronized (mPackages) {
1122                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1123            }
1124            if (ivi == null) {
1125                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1126                        + verificationId + " packageName:" + packageName);
1127                return;
1128            }
1129            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1130                    "Updating IntentFilterVerificationInfo for package " + packageName
1131                            +" verificationId:" + verificationId);
1132
1133            synchronized (mPackages) {
1134                if (verified) {
1135                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1136                } else {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1138                }
1139                scheduleWriteSettingsLocked();
1140
1141                final int userId = ivs.getUserId();
1142                if (userId != UserHandle.USER_ALL) {
1143                    final int userStatus =
1144                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1145
1146                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1147                    boolean needUpdate = false;
1148
1149                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1150                    // already been set by the User thru the Disambiguation dialog
1151                    switch (userStatus) {
1152                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1153                            if (verified) {
1154                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1155                            } else {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1157                            }
1158                            needUpdate = true;
1159                            break;
1160
1161                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1162                            if (verified) {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1164                                needUpdate = true;
1165                            }
1166                            break;
1167
1168                        default:
1169                            // Nothing to do
1170                    }
1171
1172                    if (needUpdate) {
1173                        mSettings.updateIntentFilterVerificationStatusLPw(
1174                                packageName, updatedStatus, userId);
1175                        scheduleWritePackageRestrictionsLocked(userId);
1176                    }
1177                }
1178            }
1179        }
1180
1181        @Override
1182        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1183                    ActivityIntentInfo filter, String packageName) {
1184            if (!hasValidDomains(filter)) {
1185                return false;
1186            }
1187            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1188            if (ivs == null) {
1189                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1190                        packageName);
1191            }
1192            if (DEBUG_DOMAIN_VERIFICATION) {
1193                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1194            }
1195            ivs.addFilter(filter);
1196            return true;
1197        }
1198
1199        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1200                int userId, int verificationId, String packageName) {
1201            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1202                    verifierUid, userId, packageName);
1203            ivs.setPendingState();
1204            synchronized (mPackages) {
1205                mIntentFilterVerificationStates.append(verificationId, ivs);
1206                mCurrentIntentFilterVerifications.add(verificationId);
1207            }
1208            return ivs;
1209        }
1210    }
1211
1212    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1213        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1214                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1215                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1216    }
1217
1218    // Set of pending broadcasts for aggregating enable/disable of components.
1219    static class PendingPackageBroadcasts {
1220        // for each user id, a map of <package name -> components within that package>
1221        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1222
1223        public PendingPackageBroadcasts() {
1224            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1225        }
1226
1227        public ArrayList<String> get(int userId, String packageName) {
1228            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1229            return packages.get(packageName);
1230        }
1231
1232        public void put(int userId, String packageName, ArrayList<String> components) {
1233            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1234            packages.put(packageName, components);
1235        }
1236
1237        public void remove(int userId, String packageName) {
1238            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1239            if (packages != null) {
1240                packages.remove(packageName);
1241            }
1242        }
1243
1244        public void remove(int userId) {
1245            mUidMap.remove(userId);
1246        }
1247
1248        public int userIdCount() {
1249            return mUidMap.size();
1250        }
1251
1252        public int userIdAt(int n) {
1253            return mUidMap.keyAt(n);
1254        }
1255
1256        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1257            return mUidMap.get(userId);
1258        }
1259
1260        public int size() {
1261            // total number of pending broadcast entries across all userIds
1262            int num = 0;
1263            for (int i = 0; i< mUidMap.size(); i++) {
1264                num += mUidMap.valueAt(i).size();
1265            }
1266            return num;
1267        }
1268
1269        public void clear() {
1270            mUidMap.clear();
1271        }
1272
1273        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1274            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1275            if (map == null) {
1276                map = new ArrayMap<String, ArrayList<String>>();
1277                mUidMap.put(userId, map);
1278            }
1279            return map;
1280        }
1281    }
1282    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1283
1284    // Service Connection to remote media container service to copy
1285    // package uri's from external media onto secure containers
1286    // or internal storage.
1287    private IMediaContainerService mContainerService = null;
1288
1289    static final int SEND_PENDING_BROADCAST = 1;
1290    static final int MCS_BOUND = 3;
1291    static final int END_COPY = 4;
1292    static final int INIT_COPY = 5;
1293    static final int MCS_UNBIND = 6;
1294    static final int START_CLEANING_PACKAGE = 7;
1295    static final int FIND_INSTALL_LOC = 8;
1296    static final int POST_INSTALL = 9;
1297    static final int MCS_RECONNECT = 10;
1298    static final int MCS_GIVE_UP = 11;
1299    static final int WRITE_SETTINGS = 13;
1300    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1301    static final int PACKAGE_VERIFIED = 15;
1302    static final int CHECK_PENDING_VERIFICATION = 16;
1303    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1304    static final int INTENT_FILTER_VERIFIED = 18;
1305    static final int WRITE_PACKAGE_LIST = 19;
1306    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1307
1308    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1309
1310    // Delay time in millisecs
1311    static final int BROADCAST_DELAY = 10 * 1000;
1312
1313    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1314            2 * 60 * 60 * 1000L; /* two hours */
1315
1316    static UserManagerService sUserManager;
1317
1318    // Stores a list of users whose package restrictions file needs to be updated
1319    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1320
1321    final private DefaultContainerConnection mDefContainerConn =
1322            new DefaultContainerConnection();
1323    class DefaultContainerConnection implements ServiceConnection {
1324        public void onServiceConnected(ComponentName name, IBinder service) {
1325            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1326            final IMediaContainerService imcs = IMediaContainerService.Stub
1327                    .asInterface(Binder.allowBlocking(service));
1328            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1329        }
1330
1331        public void onServiceDisconnected(ComponentName name) {
1332            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1333        }
1334    }
1335
1336    // Recordkeeping of restore-after-install operations that are currently in flight
1337    // between the Package Manager and the Backup Manager
1338    static class PostInstallData {
1339        public InstallArgs args;
1340        public PackageInstalledInfo res;
1341
1342        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1343            args = _a;
1344            res = _r;
1345        }
1346    }
1347
1348    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1349    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1350
1351    // XML tags for backup/restore of various bits of state
1352    private static final String TAG_PREFERRED_BACKUP = "pa";
1353    private static final String TAG_DEFAULT_APPS = "da";
1354    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1355
1356    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1357    private static final String TAG_ALL_GRANTS = "rt-grants";
1358    private static final String TAG_GRANT = "grant";
1359    private static final String ATTR_PACKAGE_NAME = "pkg";
1360
1361    private static final String TAG_PERMISSION = "perm";
1362    private static final String ATTR_PERMISSION_NAME = "name";
1363    private static final String ATTR_IS_GRANTED = "g";
1364    private static final String ATTR_USER_SET = "set";
1365    private static final String ATTR_USER_FIXED = "fixed";
1366    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1367
1368    // System/policy permission grants are not backed up
1369    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1370            FLAG_PERMISSION_POLICY_FIXED
1371            | FLAG_PERMISSION_SYSTEM_FIXED
1372            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1373
1374    // And we back up these user-adjusted states
1375    private static final int USER_RUNTIME_GRANT_MASK =
1376            FLAG_PERMISSION_USER_SET
1377            | FLAG_PERMISSION_USER_FIXED
1378            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1379
1380    final @Nullable String mRequiredVerifierPackage;
1381    final @NonNull String mRequiredInstallerPackage;
1382    final @NonNull String mRequiredUninstallerPackage;
1383    final @Nullable String mSetupWizardPackage;
1384    final @Nullable String mStorageManagerPackage;
1385    final @NonNull String mServicesSystemSharedLibraryPackageName;
1386    final @NonNull String mSharedSystemSharedLibraryPackageName;
1387
1388    private final PackageUsage mPackageUsage = new PackageUsage();
1389    private final CompilerStats mCompilerStats = new CompilerStats();
1390
1391    class PackageHandler extends Handler {
1392        private boolean mBound = false;
1393        final ArrayList<HandlerParams> mPendingInstalls =
1394            new ArrayList<HandlerParams>();
1395
1396        private boolean connectToService() {
1397            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1398                    " DefaultContainerService");
1399            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1402                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1403                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                mBound = true;
1405                return true;
1406            }
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408            return false;
1409        }
1410
1411        private void disconnectService() {
1412            mContainerService = null;
1413            mBound = false;
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415            mContext.unbindService(mDefContainerConn);
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417        }
1418
1419        PackageHandler(Looper looper) {
1420            super(looper);
1421        }
1422
1423        public void handleMessage(Message msg) {
1424            try {
1425                doHandleMessage(msg);
1426            } finally {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428            }
1429        }
1430
1431        void doHandleMessage(Message msg) {
1432            switch (msg.what) {
1433                case INIT_COPY: {
1434                    HandlerParams params = (HandlerParams) msg.obj;
1435                    int idx = mPendingInstalls.size();
1436                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1437                    // If a bind was already initiated we dont really
1438                    // need to do anything. The pending install
1439                    // will be processed later on.
1440                    if (!mBound) {
1441                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1442                                System.identityHashCode(mHandler));
1443                        // If this is the only one pending we might
1444                        // have to bind to the service again.
1445                        if (!connectToService()) {
1446                            Slog.e(TAG, "Failed to bind to media container service");
1447                            params.serviceError();
1448                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                    System.identityHashCode(mHandler));
1450                            if (params.traceMethod != null) {
1451                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1452                                        params.traceCookie);
1453                            }
1454                            return;
1455                        } else {
1456                            // Once we bind to the service, the first
1457                            // pending request will be processed.
1458                            mPendingInstalls.add(idx, params);
1459                        }
1460                    } else {
1461                        mPendingInstalls.add(idx, params);
1462                        // Already bound to the service. Just make
1463                        // sure we trigger off processing the first request.
1464                        if (idx == 0) {
1465                            mHandler.sendEmptyMessage(MCS_BOUND);
1466                        }
1467                    }
1468                    break;
1469                }
1470                case MCS_BOUND: {
1471                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1472                    if (msg.obj != null) {
1473                        mContainerService = (IMediaContainerService) msg.obj;
1474                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                System.identityHashCode(mHandler));
1476                    }
1477                    if (mContainerService == null) {
1478                        if (!mBound) {
1479                            // Something seriously wrong since we are not bound and we are not
1480                            // waiting for connection. Bail out.
1481                            Slog.e(TAG, "Cannot bind to media container service");
1482                            for (HandlerParams params : mPendingInstalls) {
1483                                // Indicate service bind error
1484                                params.serviceError();
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486                                        System.identityHashCode(params));
1487                                if (params.traceMethod != null) {
1488                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1489                                            params.traceMethod, params.traceCookie);
1490                                }
1491                                return;
1492                            }
1493                            mPendingInstalls.clear();
1494                        } else {
1495                            Slog.w(TAG, "Waiting to connect to media container service");
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        HandlerParams params = mPendingInstalls.get(0);
1499                        if (params != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                    System.identityHashCode(params));
1502                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1503                            if (params.startCopy()) {
1504                                // We are done...  look for more work or to
1505                                // go idle.
1506                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1507                                        "Checking for more work or unbind...");
1508                                // Delete pending install
1509                                if (mPendingInstalls.size() > 0) {
1510                                    mPendingInstalls.remove(0);
1511                                }
1512                                if (mPendingInstalls.size() == 0) {
1513                                    if (mBound) {
1514                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                                "Posting delayed MCS_UNBIND");
1516                                        removeMessages(MCS_UNBIND);
1517                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1518                                        // Unbind after a little delay, to avoid
1519                                        // continual thrashing.
1520                                        sendMessageDelayed(ubmsg, 10000);
1521                                    }
1522                                } else {
1523                                    // There are more pending requests in queue.
1524                                    // Just post MCS_BOUND message to trigger processing
1525                                    // of next pending install.
1526                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                            "Posting MCS_BOUND for next work");
1528                                    mHandler.sendEmptyMessage(MCS_BOUND);
1529                                }
1530                            }
1531                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1532                        }
1533                    } else {
1534                        // Should never happen ideally.
1535                        Slog.w(TAG, "Empty queue");
1536                    }
1537                    break;
1538                }
1539                case MCS_RECONNECT: {
1540                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1541                    if (mPendingInstalls.size() > 0) {
1542                        if (mBound) {
1543                            disconnectService();
1544                        }
1545                        if (!connectToService()) {
1546                            Slog.e(TAG, "Failed to bind to media container service");
1547                            for (HandlerParams params : mPendingInstalls) {
1548                                // Indicate service bind error
1549                                params.serviceError();
1550                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1551                                        System.identityHashCode(params));
1552                            }
1553                            mPendingInstalls.clear();
1554                        }
1555                    }
1556                    break;
1557                }
1558                case MCS_UNBIND: {
1559                    // If there is no actual work left, then time to unbind.
1560                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1561
1562                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1563                        if (mBound) {
1564                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1565
1566                            disconnectService();
1567                        }
1568                    } else if (mPendingInstalls.size() > 0) {
1569                        // There are more pending requests in queue.
1570                        // Just post MCS_BOUND message to trigger processing
1571                        // of next pending install.
1572                        mHandler.sendEmptyMessage(MCS_BOUND);
1573                    }
1574
1575                    break;
1576                }
1577                case MCS_GIVE_UP: {
1578                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1579                    HandlerParams params = mPendingInstalls.remove(0);
1580                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1581                            System.identityHashCode(params));
1582                    break;
1583                }
1584                case SEND_PENDING_BROADCAST: {
1585                    String packages[];
1586                    ArrayList<String> components[];
1587                    int size = 0;
1588                    int uids[];
1589                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1590                    synchronized (mPackages) {
1591                        if (mPendingBroadcasts == null) {
1592                            return;
1593                        }
1594                        size = mPendingBroadcasts.size();
1595                        if (size <= 0) {
1596                            // Nothing to be done. Just return
1597                            return;
1598                        }
1599                        packages = new String[size];
1600                        components = new ArrayList[size];
1601                        uids = new int[size];
1602                        int i = 0;  // filling out the above arrays
1603
1604                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1605                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1606                            Iterator<Map.Entry<String, ArrayList<String>>> it
1607                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1608                                            .entrySet().iterator();
1609                            while (it.hasNext() && i < size) {
1610                                Map.Entry<String, ArrayList<String>> ent = it.next();
1611                                packages[i] = ent.getKey();
1612                                components[i] = ent.getValue();
1613                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1614                                uids[i] = (ps != null)
1615                                        ? UserHandle.getUid(packageUserId, ps.appId)
1616                                        : -1;
1617                                i++;
1618                            }
1619                        }
1620                        size = i;
1621                        mPendingBroadcasts.clear();
1622                    }
1623                    // Send broadcasts
1624                    for (int i = 0; i < size; i++) {
1625                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1626                    }
1627                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1628                    break;
1629                }
1630                case START_CLEANING_PACKAGE: {
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632                    final String packageName = (String)msg.obj;
1633                    final int userId = msg.arg1;
1634                    final boolean andCode = msg.arg2 != 0;
1635                    synchronized (mPackages) {
1636                        if (userId == UserHandle.USER_ALL) {
1637                            int[] users = sUserManager.getUserIds();
1638                            for (int user : users) {
1639                                mSettings.addPackageToCleanLPw(
1640                                        new PackageCleanItem(user, packageName, andCode));
1641                            }
1642                        } else {
1643                            mSettings.addPackageToCleanLPw(
1644                                    new PackageCleanItem(userId, packageName, andCode));
1645                        }
1646                    }
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                    startCleaningPackages();
1649                } break;
1650                case POST_INSTALL: {
1651                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1652
1653                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1654                    final boolean didRestore = (msg.arg2 != 0);
1655                    mRunningInstalls.delete(msg.arg1);
1656
1657                    if (data != null) {
1658                        InstallArgs args = data.args;
1659                        PackageInstalledInfo parentRes = data.res;
1660
1661                        final boolean grantPermissions = (args.installFlags
1662                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1663                        final boolean killApp = (args.installFlags
1664                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1665                        final boolean virtualPreload = ((args.installFlags
1666                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1667                        final String[] grantedPermissions = args.installGrantPermissions;
1668
1669                        // Handle the parent package
1670                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1671                                virtualPreload, grantedPermissions, didRestore,
1672                                args.installerPackageName, args.observer);
1673
1674                        // Handle the child packages
1675                        final int childCount = (parentRes.addedChildPackages != null)
1676                                ? parentRes.addedChildPackages.size() : 0;
1677                        for (int i = 0; i < childCount; i++) {
1678                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1679                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1680                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1681                                    args.installerPackageName, args.observer);
1682                        }
1683
1684                        // Log tracing if needed
1685                        if (args.traceMethod != null) {
1686                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1687                                    args.traceCookie);
1688                        }
1689                    } else {
1690                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1691                    }
1692
1693                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1694                } break;
1695                case WRITE_SETTINGS: {
1696                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1697                    synchronized (mPackages) {
1698                        removeMessages(WRITE_SETTINGS);
1699                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1700                        mSettings.writeLPr();
1701                        mDirtyUsers.clear();
1702                    }
1703                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1704                } break;
1705                case WRITE_PACKAGE_RESTRICTIONS: {
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1707                    synchronized (mPackages) {
1708                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1709                        for (int userId : mDirtyUsers) {
1710                            mSettings.writePackageRestrictionsLPr(userId);
1711                        }
1712                        mDirtyUsers.clear();
1713                    }
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1715                } break;
1716                case WRITE_PACKAGE_LIST: {
1717                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1718                    synchronized (mPackages) {
1719                        removeMessages(WRITE_PACKAGE_LIST);
1720                        mSettings.writePackageListLPr(msg.arg1);
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case CHECK_PENDING_VERIFICATION: {
1725                    final int verificationId = msg.arg1;
1726                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1727
1728                    if ((state != null) && !state.timeoutExtended()) {
1729                        final InstallArgs args = state.getInstallArgs();
1730                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1731
1732                        Slog.i(TAG, "Verification timed out for " + originUri);
1733                        mPendingVerification.remove(verificationId);
1734
1735                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1736
1737                        final UserHandle user = args.getUser();
1738                        if (getDefaultVerificationResponse(user)
1739                                == PackageManager.VERIFICATION_ALLOW) {
1740                            Slog.i(TAG, "Continuing with installation of " + originUri);
1741                            state.setVerifierResponse(Binder.getCallingUid(),
1742                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1743                            broadcastPackageVerified(verificationId, originUri,
1744                                    PackageManager.VERIFICATION_ALLOW, user);
1745                            try {
1746                                ret = args.copyApk(mContainerService, true);
1747                            } catch (RemoteException e) {
1748                                Slog.e(TAG, "Could not contact the ContainerService");
1749                            }
1750                        } else {
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_REJECT, user);
1753                        }
1754
1755                        Trace.asyncTraceEnd(
1756                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1757
1758                        processPendingInstall(args, ret);
1759                        mHandler.sendEmptyMessage(MCS_UNBIND);
1760                    }
1761                    break;
1762                }
1763                case PACKAGE_VERIFIED: {
1764                    final int verificationId = msg.arg1;
1765
1766                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1767                    if (state == null) {
1768                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1769                        break;
1770                    }
1771
1772                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1773
1774                    state.setVerifierResponse(response.callerUid, response.code);
1775
1776                    if (state.isVerificationComplete()) {
1777                        mPendingVerification.remove(verificationId);
1778
1779                        final InstallArgs args = state.getInstallArgs();
1780                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1781
1782                        int ret;
1783                        if (state.isInstallAllowed()) {
1784                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1785                            broadcastPackageVerified(verificationId, originUri,
1786                                    response.code, state.getInstallArgs().getUser());
1787                            try {
1788                                ret = args.copyApk(mContainerService, true);
1789                            } catch (RemoteException e) {
1790                                Slog.e(TAG, "Could not contact the ContainerService");
1791                            }
1792                        } else {
1793                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1794                        }
1795
1796                        Trace.asyncTraceEnd(
1797                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1798
1799                        processPendingInstall(args, ret);
1800                        mHandler.sendEmptyMessage(MCS_UNBIND);
1801                    }
1802
1803                    break;
1804                }
1805                case START_INTENT_FILTER_VERIFICATIONS: {
1806                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1807                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1808                            params.replacing, params.pkg);
1809                    break;
1810                }
1811                case INTENT_FILTER_VERIFIED: {
1812                    final int verificationId = msg.arg1;
1813
1814                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1815                            verificationId);
1816                    if (state == null) {
1817                        Slog.w(TAG, "Invalid IntentFilter verification token "
1818                                + verificationId + " received");
1819                        break;
1820                    }
1821
1822                    final int userId = state.getUserId();
1823
1824                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1825                            "Processing IntentFilter verification with token:"
1826                            + verificationId + " and userId:" + userId);
1827
1828                    final IntentFilterVerificationResponse response =
1829                            (IntentFilterVerificationResponse) msg.obj;
1830
1831                    state.setVerifierResponse(response.callerUid, response.code);
1832
1833                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1834                            "IntentFilter verification with token:" + verificationId
1835                            + " and userId:" + userId
1836                            + " is settings verifier response with response code:"
1837                            + response.code);
1838
1839                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1840                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1841                                + response.getFailedDomainsString());
1842                    }
1843
1844                    if (state.isVerificationComplete()) {
1845                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1846                    } else {
1847                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1848                                "IntentFilter verification with token:" + verificationId
1849                                + " was not said to be complete");
1850                    }
1851
1852                    break;
1853                }
1854                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1855                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1856                            mInstantAppResolverConnection,
1857                            (InstantAppRequest) msg.obj,
1858                            mInstantAppInstallerActivity,
1859                            mHandler);
1860                }
1861            }
1862        }
1863    }
1864
1865    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1866        @Override
1867        public void onGidsChanged(int appId, int userId) {
1868            mHandler.post(new Runnable() {
1869                @Override
1870                public void run() {
1871                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1872                }
1873            });
1874        }
1875        @Override
1876        public void onPermissionGranted(int uid, int userId) {
1877            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1878
1879            // Not critical; if this is lost, the application has to request again.
1880            synchronized (mPackages) {
1881                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1882            }
1883        }
1884        @Override
1885        public void onInstallPermissionGranted() {
1886            synchronized (mPackages) {
1887                scheduleWriteSettingsLocked();
1888            }
1889        }
1890        @Override
1891        public void onPermissionRevoked(int uid, int userId) {
1892            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1893
1894            synchronized (mPackages) {
1895                // Critical; after this call the application should never have the permission
1896                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1897            }
1898
1899            final int appId = UserHandle.getAppId(uid);
1900            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1901        }
1902        @Override
1903        public void onInstallPermissionRevoked() {
1904            synchronized (mPackages) {
1905                scheduleWriteSettingsLocked();
1906            }
1907        }
1908        @Override
1909        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1910            synchronized (mPackages) {
1911                for (int userId : updatedUserIds) {
1912                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1913                }
1914            }
1915        }
1916        @Override
1917        public void onInstallPermissionUpdated() {
1918            synchronized (mPackages) {
1919                scheduleWriteSettingsLocked();
1920            }
1921        }
1922        @Override
1923        public void onPermissionRemoved() {
1924            synchronized (mPackages) {
1925                mSettings.writeLPr();
1926            }
1927        }
1928    };
1929
1930    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1931            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1932            boolean launchedForRestore, String installerPackage,
1933            IPackageInstallObserver2 installObserver) {
1934        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1935            // Send the removed broadcasts
1936            if (res.removedInfo != null) {
1937                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1938            }
1939
1940            // Now that we successfully installed the package, grant runtime
1941            // permissions if requested before broadcasting the install. Also
1942            // for legacy apps in permission review mode we clear the permission
1943            // review flag which is used to emulate runtime permissions for
1944            // legacy apps.
1945            if (grantPermissions) {
1946                final int callingUid = Binder.getCallingUid();
1947                mPermissionManager.grantRequestedRuntimePermissions(
1948                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1949                        mPermissionCallback);
1950            }
1951
1952            final boolean update = res.removedInfo != null
1953                    && res.removedInfo.removedPackage != null;
1954            final String installerPackageName =
1955                    res.installerPackageName != null
1956                            ? res.installerPackageName
1957                            : res.removedInfo != null
1958                                    ? res.removedInfo.installerPackageName
1959                                    : null;
1960
1961            // If this is the first time we have child packages for a disabled privileged
1962            // app that had no children, we grant requested runtime permissions to the new
1963            // children if the parent on the system image had them already granted.
1964            if (res.pkg.parentPackage != null) {
1965                final int callingUid = Binder.getCallingUid();
1966                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1967                        res.pkg, callingUid, mPermissionCallback);
1968            }
1969
1970            synchronized (mPackages) {
1971                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1972            }
1973
1974            final String packageName = res.pkg.applicationInfo.packageName;
1975
1976            // Determine the set of users who are adding this package for
1977            // the first time vs. those who are seeing an update.
1978            int[] firstUsers = EMPTY_INT_ARRAY;
1979            int[] updateUsers = EMPTY_INT_ARRAY;
1980            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1981            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1982            for (int newUser : res.newUsers) {
1983                if (ps.getInstantApp(newUser)) {
1984                    continue;
1985                }
1986                if (allNewUsers) {
1987                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1988                    continue;
1989                }
1990                boolean isNew = true;
1991                for (int origUser : res.origUsers) {
1992                    if (origUser == newUser) {
1993                        isNew = false;
1994                        break;
1995                    }
1996                }
1997                if (isNew) {
1998                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1999                } else {
2000                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2001                }
2002            }
2003
2004            // Send installed broadcasts if the package is not a static shared lib.
2005            if (res.pkg.staticSharedLibName == null) {
2006                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2007
2008                // Send added for users that see the package for the first time
2009                // sendPackageAddedForNewUsers also deals with system apps
2010                int appId = UserHandle.getAppId(res.uid);
2011                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2012                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2013                        virtualPreload /*startReceiver*/, appId, firstUsers);
2014
2015                // Send added for users that don't see the package for the first time
2016                Bundle extras = new Bundle(1);
2017                extras.putInt(Intent.EXTRA_UID, res.uid);
2018                if (update) {
2019                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2020                }
2021                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2022                        extras, 0 /*flags*/,
2023                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2024                if (installerPackageName != null) {
2025                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2026                            extras, 0 /*flags*/,
2027                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2028                }
2029
2030                // Send replaced for users that don't see the package for the first time
2031                if (update) {
2032                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2033                            packageName, extras, 0 /*flags*/,
2034                            null /*targetPackage*/, null /*finishedReceiver*/,
2035                            updateUsers);
2036                    if (installerPackageName != null) {
2037                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2038                                extras, 0 /*flags*/,
2039                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2040                    }
2041                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2042                            null /*package*/, null /*extras*/, 0 /*flags*/,
2043                            packageName /*targetPackage*/,
2044                            null /*finishedReceiver*/, updateUsers);
2045                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2046                    // First-install and we did a restore, so we're responsible for the
2047                    // first-launch broadcast.
2048                    if (DEBUG_BACKUP) {
2049                        Slog.i(TAG, "Post-restore of " + packageName
2050                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2051                    }
2052                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2053                }
2054
2055                // Send broadcast package appeared if forward locked/external for all users
2056                // treat asec-hosted packages like removable media on upgrade
2057                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2058                    if (DEBUG_INSTALL) {
2059                        Slog.i(TAG, "upgrading pkg " + res.pkg
2060                                + " is ASEC-hosted -> AVAILABLE");
2061                    }
2062                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2063                    ArrayList<String> pkgList = new ArrayList<>(1);
2064                    pkgList.add(packageName);
2065                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2066                }
2067            }
2068
2069            // Work that needs to happen on first install within each user
2070            if (firstUsers != null && firstUsers.length > 0) {
2071                synchronized (mPackages) {
2072                    for (int userId : firstUsers) {
2073                        // If this app is a browser and it's newly-installed for some
2074                        // users, clear any default-browser state in those users. The
2075                        // app's nature doesn't depend on the user, so we can just check
2076                        // its browser nature in any user and generalize.
2077                        if (packageIsBrowser(packageName, userId)) {
2078                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2079                        }
2080
2081                        // We may also need to apply pending (restored) runtime
2082                        // permission grants within these users.
2083                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2084                    }
2085                }
2086            }
2087
2088            // Log current value of "unknown sources" setting
2089            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2090                    getUnknownSourcesSettings());
2091
2092            // Remove the replaced package's older resources safely now
2093            // We delete after a gc for applications  on sdcard.
2094            if (res.removedInfo != null && res.removedInfo.args != null) {
2095                Runtime.getRuntime().gc();
2096                synchronized (mInstallLock) {
2097                    res.removedInfo.args.doPostDeleteLI(true);
2098                }
2099            } else {
2100                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2101                // and not block here.
2102                VMRuntime.getRuntime().requestConcurrentGC();
2103            }
2104
2105            // Notify DexManager that the package was installed for new users.
2106            // The updated users should already be indexed and the package code paths
2107            // should not change.
2108            // Don't notify the manager for ephemeral apps as they are not expected to
2109            // survive long enough to benefit of background optimizations.
2110            for (int userId : firstUsers) {
2111                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2112                // There's a race currently where some install events may interleave with an uninstall.
2113                // This can lead to package info being null (b/36642664).
2114                if (info != null) {
2115                    mDexManager.notifyPackageInstalled(info, userId);
2116                }
2117            }
2118        }
2119
2120        // If someone is watching installs - notify them
2121        if (installObserver != null) {
2122            try {
2123                Bundle extras = extrasForInstallResult(res);
2124                installObserver.onPackageInstalled(res.name, res.returnCode,
2125                        res.returnMsg, extras);
2126            } catch (RemoteException e) {
2127                Slog.i(TAG, "Observer no longer exists.");
2128            }
2129        }
2130    }
2131
2132    private StorageEventListener mStorageListener = new StorageEventListener() {
2133        @Override
2134        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2135            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2136                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2137                    final String volumeUuid = vol.getFsUuid();
2138
2139                    // Clean up any users or apps that were removed or recreated
2140                    // while this volume was missing
2141                    sUserManager.reconcileUsers(volumeUuid);
2142                    reconcileApps(volumeUuid);
2143
2144                    // Clean up any install sessions that expired or were
2145                    // cancelled while this volume was missing
2146                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2147
2148                    loadPrivatePackages(vol);
2149
2150                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2151                    unloadPrivatePackages(vol);
2152                }
2153            }
2154        }
2155
2156        @Override
2157        public void onVolumeForgotten(String fsUuid) {
2158            if (TextUtils.isEmpty(fsUuid)) {
2159                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2160                return;
2161            }
2162
2163            // Remove any apps installed on the forgotten volume
2164            synchronized (mPackages) {
2165                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2166                for (PackageSetting ps : packages) {
2167                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2168                    deletePackageVersioned(new VersionedPackage(ps.name,
2169                            PackageManager.VERSION_CODE_HIGHEST),
2170                            new LegacyPackageDeleteObserver(null).getBinder(),
2171                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2172                    // Try very hard to release any references to this package
2173                    // so we don't risk the system server being killed due to
2174                    // open FDs
2175                    AttributeCache.instance().removePackage(ps.name);
2176                }
2177
2178                mSettings.onVolumeForgotten(fsUuid);
2179                mSettings.writeLPr();
2180            }
2181        }
2182    };
2183
2184    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2185        Bundle extras = null;
2186        switch (res.returnCode) {
2187            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2188                extras = new Bundle();
2189                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2190                        res.origPermission);
2191                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2192                        res.origPackage);
2193                break;
2194            }
2195            case PackageManager.INSTALL_SUCCEEDED: {
2196                extras = new Bundle();
2197                extras.putBoolean(Intent.EXTRA_REPLACING,
2198                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2199                break;
2200            }
2201        }
2202        return extras;
2203    }
2204
2205    void scheduleWriteSettingsLocked() {
2206        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2207            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2208        }
2209    }
2210
2211    void scheduleWritePackageListLocked(int userId) {
2212        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2213            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2214            msg.arg1 = userId;
2215            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2216        }
2217    }
2218
2219    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2220        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2221        scheduleWritePackageRestrictionsLocked(userId);
2222    }
2223
2224    void scheduleWritePackageRestrictionsLocked(int userId) {
2225        final int[] userIds = (userId == UserHandle.USER_ALL)
2226                ? sUserManager.getUserIds() : new int[]{userId};
2227        for (int nextUserId : userIds) {
2228            if (!sUserManager.exists(nextUserId)) return;
2229            mDirtyUsers.add(nextUserId);
2230            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2231                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2232            }
2233        }
2234    }
2235
2236    public static PackageManagerService main(Context context, Installer installer,
2237            boolean factoryTest, boolean onlyCore) {
2238        // Self-check for initial settings.
2239        PackageManagerServiceCompilerMapping.checkProperties();
2240
2241        PackageManagerService m = new PackageManagerService(context, installer,
2242                factoryTest, onlyCore);
2243        m.enableSystemUserPackages();
2244        ServiceManager.addService("package", m);
2245        final PackageManagerNative pmn = m.new PackageManagerNative();
2246        ServiceManager.addService("package_native", pmn);
2247        return m;
2248    }
2249
2250    private void enableSystemUserPackages() {
2251        if (!UserManager.isSplitSystemUser()) {
2252            return;
2253        }
2254        // For system user, enable apps based on the following conditions:
2255        // - app is whitelisted or belong to one of these groups:
2256        //   -- system app which has no launcher icons
2257        //   -- system app which has INTERACT_ACROSS_USERS permission
2258        //   -- system IME app
2259        // - app is not in the blacklist
2260        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2261        Set<String> enableApps = new ArraySet<>();
2262        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2263                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2264                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2265        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2266        enableApps.addAll(wlApps);
2267        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2268                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2269        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2270        enableApps.removeAll(blApps);
2271        Log.i(TAG, "Applications installed for system user: " + enableApps);
2272        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2273                UserHandle.SYSTEM);
2274        final int allAppsSize = allAps.size();
2275        synchronized (mPackages) {
2276            for (int i = 0; i < allAppsSize; i++) {
2277                String pName = allAps.get(i);
2278                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2279                // Should not happen, but we shouldn't be failing if it does
2280                if (pkgSetting == null) {
2281                    continue;
2282                }
2283                boolean install = enableApps.contains(pName);
2284                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2285                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2286                            + " for system user");
2287                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2288                }
2289            }
2290            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2291        }
2292    }
2293
2294    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2295        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2296                Context.DISPLAY_SERVICE);
2297        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2298    }
2299
2300    /**
2301     * Requests that files preopted on a secondary system partition be copied to the data partition
2302     * if possible.  Note that the actual copying of the files is accomplished by init for security
2303     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2304     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2305     */
2306    private static void requestCopyPreoptedFiles() {
2307        final int WAIT_TIME_MS = 100;
2308        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2309        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2310            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2311            // We will wait for up to 100 seconds.
2312            final long timeStart = SystemClock.uptimeMillis();
2313            final long timeEnd = timeStart + 100 * 1000;
2314            long timeNow = timeStart;
2315            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2316                try {
2317                    Thread.sleep(WAIT_TIME_MS);
2318                } catch (InterruptedException e) {
2319                    // Do nothing
2320                }
2321                timeNow = SystemClock.uptimeMillis();
2322                if (timeNow > timeEnd) {
2323                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2324                    Slog.wtf(TAG, "cppreopt did not finish!");
2325                    break;
2326                }
2327            }
2328
2329            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2330        }
2331    }
2332
2333    public PackageManagerService(Context context, Installer installer,
2334            boolean factoryTest, boolean onlyCore) {
2335        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2336        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2337        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2338                SystemClock.uptimeMillis());
2339
2340        if (mSdkVersion <= 0) {
2341            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2342        }
2343
2344        mContext = context;
2345
2346        mFactoryTest = factoryTest;
2347        mOnlyCore = onlyCore;
2348        mMetrics = new DisplayMetrics();
2349        mInstaller = installer;
2350
2351        // Create sub-components that provide services / data. Order here is important.
2352        synchronized (mInstallLock) {
2353        synchronized (mPackages) {
2354            // Expose private service for system components to use.
2355            LocalServices.addService(
2356                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2357            sUserManager = new UserManagerService(context, this,
2358                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2359            mPermissionManager = PermissionManagerService.create(context,
2360                    new DefaultPermissionGrantedCallback() {
2361                        @Override
2362                        public void onDefaultRuntimePermissionsGranted(int userId) {
2363                            synchronized(mPackages) {
2364                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2365                            }
2366                        }
2367                    }, mPackages /*externalLock*/);
2368            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2369            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2370        }
2371        }
2372        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2373                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2374        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2375                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2376        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2377                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2378        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2379                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2380        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384
2385        String separateProcesses = SystemProperties.get("debug.separate_processes");
2386        if (separateProcesses != null && separateProcesses.length() > 0) {
2387            if ("*".equals(separateProcesses)) {
2388                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2389                mSeparateProcesses = null;
2390                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2391            } else {
2392                mDefParseFlags = 0;
2393                mSeparateProcesses = separateProcesses.split(",");
2394                Slog.w(TAG, "Running with debug.separate_processes: "
2395                        + separateProcesses);
2396            }
2397        } else {
2398            mDefParseFlags = 0;
2399            mSeparateProcesses = null;
2400        }
2401
2402        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2403                "*dexopt*");
2404        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2405                installer, mInstallLock);
2406        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2407                dexManagerListener);
2408        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2409
2410        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2411                FgThread.get().getLooper());
2412
2413        getDefaultDisplayMetrics(context, mMetrics);
2414
2415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2416        SystemConfig systemConfig = SystemConfig.getInstance();
2417        mAvailableFeatures = systemConfig.getAvailableFeatures();
2418        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2419
2420        mProtectedPackages = new ProtectedPackages(mContext);
2421
2422        synchronized (mInstallLock) {
2423        // writer
2424        synchronized (mPackages) {
2425            mHandlerThread = new ServiceThread(TAG,
2426                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2427            mHandlerThread.start();
2428            mHandler = new PackageHandler(mHandlerThread.getLooper());
2429            mProcessLoggingHandler = new ProcessLoggingHandler();
2430            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2431            mInstantAppRegistry = new InstantAppRegistry(this);
2432
2433            File dataDir = Environment.getDataDirectory();
2434            mAppInstallDir = new File(dataDir, "app");
2435            mAppLib32InstallDir = new File(dataDir, "app-lib");
2436            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2437
2438            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2439            final int builtInLibCount = libConfig.size();
2440            for (int i = 0; i < builtInLibCount; i++) {
2441                String name = libConfig.keyAt(i);
2442                String path = libConfig.valueAt(i);
2443                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2444                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2445            }
2446
2447            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2448
2449            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2450            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2452
2453            // Clean up orphaned packages for which the code path doesn't exist
2454            // and they are an update to a system app - caused by bug/32321269
2455            final int packageSettingCount = mSettings.mPackages.size();
2456            for (int i = packageSettingCount - 1; i >= 0; i--) {
2457                PackageSetting ps = mSettings.mPackages.valueAt(i);
2458                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2459                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2460                    mSettings.mPackages.removeAt(i);
2461                    mSettings.enableSystemPackageLPw(ps.name);
2462                }
2463            }
2464
2465            if (mFirstBoot) {
2466                requestCopyPreoptedFiles();
2467            }
2468
2469            String customResolverActivity = Resources.getSystem().getString(
2470                    R.string.config_customResolverActivity);
2471            if (TextUtils.isEmpty(customResolverActivity)) {
2472                customResolverActivity = null;
2473            } else {
2474                mCustomResolverComponentName = ComponentName.unflattenFromString(
2475                        customResolverActivity);
2476            }
2477
2478            long startTime = SystemClock.uptimeMillis();
2479
2480            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2481                    startTime);
2482
2483            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2484            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2485
2486            if (bootClassPath == null) {
2487                Slog.w(TAG, "No BOOTCLASSPATH found!");
2488            }
2489
2490            if (systemServerClassPath == null) {
2491                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2492            }
2493
2494            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2495
2496            final VersionInfo ver = mSettings.getInternalVersion();
2497            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2498            if (mIsUpgrade) {
2499                logCriticalInfo(Log.INFO,
2500                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2501            }
2502
2503            // when upgrading from pre-M, promote system app permissions from install to runtime
2504            mPromoteSystemApps =
2505                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2506
2507            // When upgrading from pre-N, we need to handle package extraction like first boot,
2508            // as there is no profiling data available.
2509            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2510
2511            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2512
2513            // save off the names of pre-existing system packages prior to scanning; we don't
2514            // want to automatically grant runtime permissions for new system apps
2515            if (mPromoteSystemApps) {
2516                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2517                while (pkgSettingIter.hasNext()) {
2518                    PackageSetting ps = pkgSettingIter.next();
2519                    if (isSystemApp(ps)) {
2520                        mExistingSystemPackages.add(ps.name);
2521                    }
2522                }
2523            }
2524
2525            mCacheDir = preparePackageParserCache(mIsUpgrade);
2526
2527            // Set flag to monitor and not change apk file paths when
2528            // scanning install directories.
2529            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2530
2531            if (mIsUpgrade || mFirstBoot) {
2532                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2533            }
2534
2535            // Collect vendor overlay packages. (Do this before scanning any apps.)
2536            // For security and version matching reason, only consider
2537            // overlay packages if they reside in the right directory.
2538            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2539                    mDefParseFlags
2540                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2541                    scanFlags
2542                    | SCAN_AS_SYSTEM
2543                    | SCAN_TRUSTED_OVERLAY,
2544                    0);
2545
2546            mParallelPackageParserCallback.findStaticOverlayPackages();
2547
2548            // Find base frameworks (resource packages without code).
2549            scanDirTracedLI(frameworkDir,
2550                    mDefParseFlags
2551                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2552                    scanFlags
2553                    | SCAN_NO_DEX
2554                    | SCAN_AS_SYSTEM
2555                    | SCAN_AS_PRIVILEGED,
2556                    0);
2557
2558            // Collected privileged system packages.
2559            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2560            scanDirTracedLI(privilegedAppDir,
2561                    mDefParseFlags
2562                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2563                    scanFlags
2564                    | SCAN_AS_SYSTEM
2565                    | SCAN_AS_PRIVILEGED,
2566                    0);
2567
2568            // Collect ordinary system packages.
2569            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2570            scanDirTracedLI(systemAppDir,
2571                    mDefParseFlags
2572                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2573                    scanFlags
2574                    | SCAN_AS_SYSTEM,
2575                    0);
2576
2577            // Collect all vendor packages.
2578            File vendorAppDir = new File("/vendor/app");
2579            try {
2580                vendorAppDir = vendorAppDir.getCanonicalFile();
2581            } catch (IOException e) {
2582                // failed to look up canonical path, continue with original one
2583            }
2584            scanDirTracedLI(vendorAppDir,
2585                    mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2587                    scanFlags
2588                    | SCAN_AS_SYSTEM,
2589                    0);
2590
2591            // Collect all OEM packages.
2592            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2593            scanDirTracedLI(oemAppDir,
2594                    mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2596                    scanFlags
2597                    | SCAN_AS_SYSTEM
2598                    | SCAN_AS_OEM,
2599                    0);
2600
2601            // Prune any system packages that no longer exist.
2602            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2603            // Stub packages must either be replaced with full versions in the /data
2604            // partition or be disabled.
2605            final List<String> stubSystemApps = new ArrayList<>();
2606            if (!mOnlyCore) {
2607                // do this first before mucking with mPackages for the "expecting better" case
2608                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2609                while (pkgIterator.hasNext()) {
2610                    final PackageParser.Package pkg = pkgIterator.next();
2611                    if (pkg.isStub) {
2612                        stubSystemApps.add(pkg.packageName);
2613                    }
2614                }
2615
2616                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2617                while (psit.hasNext()) {
2618                    PackageSetting ps = psit.next();
2619
2620                    /*
2621                     * If this is not a system app, it can't be a
2622                     * disable system app.
2623                     */
2624                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2625                        continue;
2626                    }
2627
2628                    /*
2629                     * If the package is scanned, it's not erased.
2630                     */
2631                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2632                    if (scannedPkg != null) {
2633                        /*
2634                         * If the system app is both scanned and in the
2635                         * disabled packages list, then it must have been
2636                         * added via OTA. Remove it from the currently
2637                         * scanned package so the previously user-installed
2638                         * application can be scanned.
2639                         */
2640                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2641                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2642                                    + ps.name + "; removing system app.  Last known codePath="
2643                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2644                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2645                                    + scannedPkg.mVersionCode);
2646                            removePackageLI(scannedPkg, true);
2647                            mExpectingBetter.put(ps.name, ps.codePath);
2648                        }
2649
2650                        continue;
2651                    }
2652
2653                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2654                        psit.remove();
2655                        logCriticalInfo(Log.WARN, "System package " + ps.name
2656                                + " no longer exists; it's data will be wiped");
2657                        // Actual deletion of code and data will be handled by later
2658                        // reconciliation step
2659                    } else {
2660                        // we still have a disabled system package, but, it still might have
2661                        // been removed. check the code path still exists and check there's
2662                        // still a package. the latter can happen if an OTA keeps the same
2663                        // code path, but, changes the package name.
2664                        final PackageSetting disabledPs =
2665                                mSettings.getDisabledSystemPkgLPr(ps.name);
2666                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2667                                || disabledPs.pkg == null) {
2668                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2669                        }
2670                    }
2671                }
2672            }
2673
2674            //look for any incomplete package installations
2675            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2676            for (int i = 0; i < deletePkgsList.size(); i++) {
2677                // Actual deletion of code and data will be handled by later
2678                // reconciliation step
2679                final String packageName = deletePkgsList.get(i).name;
2680                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2681                synchronized (mPackages) {
2682                    mSettings.removePackageLPw(packageName);
2683                }
2684            }
2685
2686            //delete tmp files
2687            deleteTempPackageFiles();
2688
2689            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2690
2691            // Remove any shared userIDs that have no associated packages
2692            mSettings.pruneSharedUsersLPw();
2693            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2694            final int systemPackagesCount = mPackages.size();
2695            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2696                    + " ms, packageCount: " + systemPackagesCount
2697                    + " , timePerPackage: "
2698                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2699                    + " , cached: " + cachedSystemApps);
2700            if (mIsUpgrade && systemPackagesCount > 0) {
2701                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2702                        ((int) systemScanTime) / systemPackagesCount);
2703            }
2704            if (!mOnlyCore) {
2705                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2706                        SystemClock.uptimeMillis());
2707                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708
2709                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2710                        | PackageParser.PARSE_FORWARD_LOCK,
2711                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                // Remove disable package settings for updated system apps that were
2714                // removed via an OTA. If the update is no longer present, remove the
2715                // app completely. Otherwise, revoke their system privileges.
2716                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2717                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2718                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2719
2720                    final String msg;
2721                    if (deletedPkg == null) {
2722                        // should have found an update, but, we didn't; remove everything
2723                        msg = "Updated system package " + deletedAppName
2724                                + " no longer exists; removing its data";
2725                        // Actual deletion of code and data will be handled by later
2726                        // reconciliation step
2727                    } else {
2728                        // found an update; revoke system privileges
2729                        msg = "Updated system package + " + deletedAppName
2730                                + " no longer exists; revoking system privileges";
2731
2732                        // Don't do anything if a stub is removed from the system image. If
2733                        // we were to remove the uncompressed version from the /data partition,
2734                        // this is where it'd be done.
2735
2736                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2737                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2738                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2739                    }
2740                    logCriticalInfo(Log.WARN, msg);
2741                }
2742
2743                /*
2744                 * Make sure all system apps that we expected to appear on
2745                 * the userdata partition actually showed up. If they never
2746                 * appeared, crawl back and revive the system version.
2747                 */
2748                for (int i = 0; i < mExpectingBetter.size(); i++) {
2749                    final String packageName = mExpectingBetter.keyAt(i);
2750                    if (!mPackages.containsKey(packageName)) {
2751                        final File scanFile = mExpectingBetter.valueAt(i);
2752
2753                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2754                                + " but never showed up; reverting to system");
2755
2756                        final @ParseFlags int reparseFlags;
2757                        final @ScanFlags int rescanFlags;
2758                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2759                            reparseFlags =
2760                                    mDefParseFlags |
2761                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2762                            rescanFlags =
2763                                    scanFlags
2764                                    | SCAN_AS_SYSTEM
2765                                    | SCAN_AS_PRIVILEGED;
2766                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2767                            reparseFlags =
2768                                    mDefParseFlags |
2769                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2770                            rescanFlags =
2771                                    scanFlags
2772                                    | SCAN_AS_SYSTEM;
2773                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2774                            reparseFlags =
2775                                    mDefParseFlags |
2776                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2777                            rescanFlags =
2778                                    scanFlags
2779                                    | SCAN_AS_SYSTEM;
2780                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2781                            reparseFlags =
2782                                    mDefParseFlags |
2783                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2784                            rescanFlags =
2785                                    scanFlags
2786                                    | SCAN_AS_SYSTEM
2787                                    | SCAN_AS_OEM;
2788                        } else {
2789                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2790                            continue;
2791                        }
2792
2793                        mSettings.enableSystemPackageLPw(packageName);
2794
2795                        try {
2796                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2797                        } catch (PackageManagerException e) {
2798                            Slog.e(TAG, "Failed to parse original system package: "
2799                                    + e.getMessage());
2800                        }
2801                    }
2802                }
2803
2804                // Uncompress and install any stubbed system applications.
2805                // This must be done last to ensure all stubs are replaced or disabled.
2806                decompressSystemApplications(stubSystemApps, scanFlags);
2807
2808                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2809                                - cachedSystemApps;
2810
2811                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2812                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2813                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2814                        + " ms, packageCount: " + dataPackagesCount
2815                        + " , timePerPackage: "
2816                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2817                        + " , cached: " + cachedNonSystemApps);
2818                if (mIsUpgrade && dataPackagesCount > 0) {
2819                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2820                            ((int) dataScanTime) / dataPackagesCount);
2821                }
2822            }
2823            mExpectingBetter.clear();
2824
2825            // Resolve the storage manager.
2826            mStorageManagerPackage = getStorageManagerPackageName();
2827
2828            // Resolve protected action filters. Only the setup wizard is allowed to
2829            // have a high priority filter for these actions.
2830            mSetupWizardPackage = getSetupWizardPackageName();
2831            if (mProtectedFilters.size() > 0) {
2832                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2833                    Slog.i(TAG, "No setup wizard;"
2834                        + " All protected intents capped to priority 0");
2835                }
2836                for (ActivityIntentInfo filter : mProtectedFilters) {
2837                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2838                        if (DEBUG_FILTERS) {
2839                            Slog.i(TAG, "Found setup wizard;"
2840                                + " allow priority " + filter.getPriority() + ";"
2841                                + " package: " + filter.activity.info.packageName
2842                                + " activity: " + filter.activity.className
2843                                + " priority: " + filter.getPriority());
2844                        }
2845                        // skip setup wizard; allow it to keep the high priority filter
2846                        continue;
2847                    }
2848                    if (DEBUG_FILTERS) {
2849                        Slog.i(TAG, "Protected action; cap priority to 0;"
2850                                + " package: " + filter.activity.info.packageName
2851                                + " activity: " + filter.activity.className
2852                                + " origPrio: " + filter.getPriority());
2853                    }
2854                    filter.setPriority(0);
2855                }
2856            }
2857            mDeferProtectedFilters = false;
2858            mProtectedFilters.clear();
2859
2860            // Now that we know all of the shared libraries, update all clients to have
2861            // the correct library paths.
2862            updateAllSharedLibrariesLPw(null);
2863
2864            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2865                // NOTE: We ignore potential failures here during a system scan (like
2866                // the rest of the commands above) because there's precious little we
2867                // can do about it. A settings error is reported, though.
2868                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2869            }
2870
2871            // Now that we know all the packages we are keeping,
2872            // read and update their last usage times.
2873            mPackageUsage.read(mPackages);
2874            mCompilerStats.read();
2875
2876            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2877                    SystemClock.uptimeMillis());
2878            Slog.i(TAG, "Time to scan packages: "
2879                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2880                    + " seconds");
2881
2882            // If the platform SDK has changed since the last time we booted,
2883            // we need to re-grant app permission to catch any new ones that
2884            // appear.  This is really a hack, and means that apps can in some
2885            // cases get permissions that the user didn't initially explicitly
2886            // allow...  it would be nice to have some better way to handle
2887            // this situation.
2888            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2889            if (sdkUpdated) {
2890                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2891                        + mSdkVersion + "; regranting permissions for internal storage");
2892            }
2893            mPermissionManager.updateAllPermissions(
2894                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2895                    mPermissionCallback);
2896            ver.sdkVersion = mSdkVersion;
2897
2898            // If this is the first boot or an update from pre-M, and it is a normal
2899            // boot, then we need to initialize the default preferred apps across
2900            // all defined users.
2901            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2902                for (UserInfo user : sUserManager.getUsers(true)) {
2903                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2904                    applyFactoryDefaultBrowserLPw(user.id);
2905                    primeDomainVerificationsLPw(user.id);
2906                }
2907            }
2908
2909            // Prepare storage for system user really early during boot,
2910            // since core system apps like SettingsProvider and SystemUI
2911            // can't wait for user to start
2912            final int storageFlags;
2913            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2914                storageFlags = StorageManager.FLAG_STORAGE_DE;
2915            } else {
2916                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2917            }
2918            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2919                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2920                    true /* onlyCoreApps */);
2921            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2922                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2923                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2924                traceLog.traceBegin("AppDataFixup");
2925                try {
2926                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2927                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2928                } catch (InstallerException e) {
2929                    Slog.w(TAG, "Trouble fixing GIDs", e);
2930                }
2931                traceLog.traceEnd();
2932
2933                traceLog.traceBegin("AppDataPrepare");
2934                if (deferPackages == null || deferPackages.isEmpty()) {
2935                    return;
2936                }
2937                int count = 0;
2938                for (String pkgName : deferPackages) {
2939                    PackageParser.Package pkg = null;
2940                    synchronized (mPackages) {
2941                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2942                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2943                            pkg = ps.pkg;
2944                        }
2945                    }
2946                    if (pkg != null) {
2947                        synchronized (mInstallLock) {
2948                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2949                                    true /* maybeMigrateAppData */);
2950                        }
2951                        count++;
2952                    }
2953                }
2954                traceLog.traceEnd();
2955                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2956            }, "prepareAppData");
2957
2958            // If this is first boot after an OTA, and a normal boot, then
2959            // we need to clear code cache directories.
2960            // Note that we do *not* clear the application profiles. These remain valid
2961            // across OTAs and are used to drive profile verification (post OTA) and
2962            // profile compilation (without waiting to collect a fresh set of profiles).
2963            if (mIsUpgrade && !onlyCore) {
2964                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2965                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2966                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2967                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2968                        // No apps are running this early, so no need to freeze
2969                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2970                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2971                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2972                    }
2973                }
2974                ver.fingerprint = Build.FINGERPRINT;
2975            }
2976
2977            checkDefaultBrowser();
2978
2979            // clear only after permissions and other defaults have been updated
2980            mExistingSystemPackages.clear();
2981            mPromoteSystemApps = false;
2982
2983            // All the changes are done during package scanning.
2984            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2985
2986            // can downgrade to reader
2987            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2988            mSettings.writeLPr();
2989            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2990            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2991                    SystemClock.uptimeMillis());
2992
2993            if (!mOnlyCore) {
2994                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2995                mRequiredInstallerPackage = getRequiredInstallerLPr();
2996                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2997                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2998                if (mIntentFilterVerifierComponent != null) {
2999                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3000                            mIntentFilterVerifierComponent);
3001                } else {
3002                    mIntentFilterVerifier = null;
3003                }
3004                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3005                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3006                        SharedLibraryInfo.VERSION_UNDEFINED);
3007                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3008                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3009                        SharedLibraryInfo.VERSION_UNDEFINED);
3010            } else {
3011                mRequiredVerifierPackage = null;
3012                mRequiredInstallerPackage = null;
3013                mRequiredUninstallerPackage = null;
3014                mIntentFilterVerifierComponent = null;
3015                mIntentFilterVerifier = null;
3016                mServicesSystemSharedLibraryPackageName = null;
3017                mSharedSystemSharedLibraryPackageName = null;
3018            }
3019
3020            mInstallerService = new PackageInstallerService(context, this);
3021            final Pair<ComponentName, String> instantAppResolverComponent =
3022                    getInstantAppResolverLPr();
3023            if (instantAppResolverComponent != null) {
3024                if (DEBUG_EPHEMERAL) {
3025                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3026                }
3027                mInstantAppResolverConnection = new EphemeralResolverConnection(
3028                        mContext, instantAppResolverComponent.first,
3029                        instantAppResolverComponent.second);
3030                mInstantAppResolverSettingsComponent =
3031                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3032            } else {
3033                mInstantAppResolverConnection = null;
3034                mInstantAppResolverSettingsComponent = null;
3035            }
3036            updateInstantAppInstallerLocked(null);
3037
3038            // Read and update the usage of dex files.
3039            // Do this at the end of PM init so that all the packages have their
3040            // data directory reconciled.
3041            // At this point we know the code paths of the packages, so we can validate
3042            // the disk file and build the internal cache.
3043            // The usage file is expected to be small so loading and verifying it
3044            // should take a fairly small time compare to the other activities (e.g. package
3045            // scanning).
3046            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3047            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3048            for (int userId : currentUserIds) {
3049                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3050            }
3051            mDexManager.load(userPackages);
3052            if (mIsUpgrade) {
3053                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3054                        (int) (SystemClock.uptimeMillis() - startTime));
3055            }
3056        } // synchronized (mPackages)
3057        } // synchronized (mInstallLock)
3058
3059        // Now after opening every single application zip, make sure they
3060        // are all flushed.  Not really needed, but keeps things nice and
3061        // tidy.
3062        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3063        Runtime.getRuntime().gc();
3064        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3065
3066        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3067        FallbackCategoryProvider.loadFallbacks();
3068        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3069
3070        // The initial scanning above does many calls into installd while
3071        // holding the mPackages lock, but we're mostly interested in yelling
3072        // once we have a booted system.
3073        mInstaller.setWarnIfHeld(mPackages);
3074
3075        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3076    }
3077
3078    /**
3079     * Uncompress and install stub applications.
3080     * <p>In order to save space on the system partition, some applications are shipped in a
3081     * compressed form. In addition the compressed bits for the full application, the
3082     * system image contains a tiny stub comprised of only the Android manifest.
3083     * <p>During the first boot, attempt to uncompress and install the full application. If
3084     * the application can't be installed for any reason, disable the stub and prevent
3085     * uncompressing the full application during future boots.
3086     * <p>In order to forcefully attempt an installation of a full application, go to app
3087     * settings and enable the application.
3088     */
3089    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3090        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3091            final String pkgName = stubSystemApps.get(i);
3092            // skip if the system package is already disabled
3093            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3094                stubSystemApps.remove(i);
3095                continue;
3096            }
3097            // skip if the package isn't installed (?!); this should never happen
3098            final PackageParser.Package pkg = mPackages.get(pkgName);
3099            if (pkg == null) {
3100                stubSystemApps.remove(i);
3101                continue;
3102            }
3103            // skip if the package has been disabled by the user
3104            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3105            if (ps != null) {
3106                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3107                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3108                    stubSystemApps.remove(i);
3109                    continue;
3110                }
3111            }
3112
3113            if (DEBUG_COMPRESSION) {
3114                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3115            }
3116
3117            // uncompress the binary to its eventual destination on /data
3118            final File scanFile = decompressPackage(pkg);
3119            if (scanFile == null) {
3120                continue;
3121            }
3122
3123            // install the package to replace the stub on /system
3124            try {
3125                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3126                removePackageLI(pkg, true /*chatty*/);
3127                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3128                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3129                        UserHandle.USER_SYSTEM, "android");
3130                stubSystemApps.remove(i);
3131                continue;
3132            } catch (PackageManagerException e) {
3133                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3134            }
3135
3136            // any failed attempt to install the package will be cleaned up later
3137        }
3138
3139        // disable any stub still left; these failed to install the full application
3140        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3141            final String pkgName = stubSystemApps.get(i);
3142            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3143            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3144                    UserHandle.USER_SYSTEM, "android");
3145            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3146        }
3147    }
3148
3149    /**
3150     * Decompresses the given package on the system image onto
3151     * the /data partition.
3152     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3153     */
3154    private File decompressPackage(PackageParser.Package pkg) {
3155        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3156        if (compressedFiles == null || compressedFiles.length == 0) {
3157            if (DEBUG_COMPRESSION) {
3158                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3159            }
3160            return null;
3161        }
3162        final File dstCodePath =
3163                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3164        int ret = PackageManager.INSTALL_SUCCEEDED;
3165        try {
3166            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3167            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3168            for (File srcFile : compressedFiles) {
3169                final String srcFileName = srcFile.getName();
3170                final String dstFileName = srcFileName.substring(
3171                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3172                final File dstFile = new File(dstCodePath, dstFileName);
3173                ret = decompressFile(srcFile, dstFile);
3174                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3175                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3176                            + "; pkg: " + pkg.packageName
3177                            + ", file: " + dstFileName);
3178                    break;
3179                }
3180            }
3181        } catch (ErrnoException e) {
3182            logCriticalInfo(Log.ERROR, "Failed to decompress"
3183                    + "; pkg: " + pkg.packageName
3184                    + ", err: " + e.errno);
3185        }
3186        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3187            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3188            NativeLibraryHelper.Handle handle = null;
3189            try {
3190                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3191                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3192                        null /*abiOverride*/);
3193            } catch (IOException e) {
3194                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3195                        + "; pkg: " + pkg.packageName);
3196                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3197            } finally {
3198                IoUtils.closeQuietly(handle);
3199            }
3200        }
3201        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3202            if (dstCodePath == null || !dstCodePath.exists()) {
3203                return null;
3204            }
3205            removeCodePathLI(dstCodePath);
3206            return null;
3207        }
3208
3209        return dstCodePath;
3210    }
3211
3212    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3213        // we're only interested in updating the installer appliction when 1) it's not
3214        // already set or 2) the modified package is the installer
3215        if (mInstantAppInstallerActivity != null
3216                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3217                        .equals(modifiedPackage)) {
3218            return;
3219        }
3220        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3221    }
3222
3223    private static File preparePackageParserCache(boolean isUpgrade) {
3224        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3225            return null;
3226        }
3227
3228        // Disable package parsing on eng builds to allow for faster incremental development.
3229        if (Build.IS_ENG) {
3230            return null;
3231        }
3232
3233        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3234            Slog.i(TAG, "Disabling package parser cache due to system property.");
3235            return null;
3236        }
3237
3238        // The base directory for the package parser cache lives under /data/system/.
3239        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3240                "package_cache");
3241        if (cacheBaseDir == null) {
3242            return null;
3243        }
3244
3245        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3246        // This also serves to "GC" unused entries when the package cache version changes (which
3247        // can only happen during upgrades).
3248        if (isUpgrade) {
3249            FileUtils.deleteContents(cacheBaseDir);
3250        }
3251
3252
3253        // Return the versioned package cache directory. This is something like
3254        // "/data/system/package_cache/1"
3255        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3256
3257        // The following is a workaround to aid development on non-numbered userdebug
3258        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3259        // the system partition is newer.
3260        //
3261        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3262        // that starts with "eng." to signify that this is an engineering build and not
3263        // destined for release.
3264        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3265            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3266
3267            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3268            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3269            // in general and should not be used for production changes. In this specific case,
3270            // we know that they will work.
3271            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3272            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3273                FileUtils.deleteContents(cacheBaseDir);
3274                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3275            }
3276        }
3277
3278        return cacheDir;
3279    }
3280
3281    @Override
3282    public boolean isFirstBoot() {
3283        // allow instant applications
3284        return mFirstBoot;
3285    }
3286
3287    @Override
3288    public boolean isOnlyCoreApps() {
3289        // allow instant applications
3290        return mOnlyCore;
3291    }
3292
3293    @Override
3294    public boolean isUpgrade() {
3295        // allow instant applications
3296        // The system property allows testing ota flow when upgraded to the same image.
3297        return mIsUpgrade || SystemProperties.getBoolean(
3298                "persist.pm.mock-upgrade", false /* default */);
3299    }
3300
3301    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3302        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3303
3304        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3305                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3306                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3307        if (matches.size() == 1) {
3308            return matches.get(0).getComponentInfo().packageName;
3309        } else if (matches.size() == 0) {
3310            Log.e(TAG, "There should probably be a verifier, but, none were found");
3311            return null;
3312        }
3313        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3314    }
3315
3316    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3317        synchronized (mPackages) {
3318            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3319            if (libraryEntry == null) {
3320                throw new IllegalStateException("Missing required shared library:" + name);
3321            }
3322            return libraryEntry.apk;
3323        }
3324    }
3325
3326    private @NonNull String getRequiredInstallerLPr() {
3327        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3328        intent.addCategory(Intent.CATEGORY_DEFAULT);
3329        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3330
3331        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3332                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3333                UserHandle.USER_SYSTEM);
3334        if (matches.size() == 1) {
3335            ResolveInfo resolveInfo = matches.get(0);
3336            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3337                throw new RuntimeException("The installer must be a privileged app");
3338            }
3339            return matches.get(0).getComponentInfo().packageName;
3340        } else {
3341            throw new RuntimeException("There must be exactly one installer; found " + matches);
3342        }
3343    }
3344
3345    private @NonNull String getRequiredUninstallerLPr() {
3346        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3347        intent.addCategory(Intent.CATEGORY_DEFAULT);
3348        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3349
3350        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3351                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3352                UserHandle.USER_SYSTEM);
3353        if (resolveInfo == null ||
3354                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3355            throw new RuntimeException("There must be exactly one uninstaller; found "
3356                    + resolveInfo);
3357        }
3358        return resolveInfo.getComponentInfo().packageName;
3359    }
3360
3361    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3362        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3363
3364        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3365                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3366                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3367        ResolveInfo best = null;
3368        final int N = matches.size();
3369        for (int i = 0; i < N; i++) {
3370            final ResolveInfo cur = matches.get(i);
3371            final String packageName = cur.getComponentInfo().packageName;
3372            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3373                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3374                continue;
3375            }
3376
3377            if (best == null || cur.priority > best.priority) {
3378                best = cur;
3379            }
3380        }
3381
3382        if (best != null) {
3383            return best.getComponentInfo().getComponentName();
3384        }
3385        Slog.w(TAG, "Intent filter verifier not found");
3386        return null;
3387    }
3388
3389    @Override
3390    public @Nullable ComponentName getInstantAppResolverComponent() {
3391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3392            return null;
3393        }
3394        synchronized (mPackages) {
3395            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3396            if (instantAppResolver == null) {
3397                return null;
3398            }
3399            return instantAppResolver.first;
3400        }
3401    }
3402
3403    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3404        final String[] packageArray =
3405                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3406        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3407            if (DEBUG_EPHEMERAL) {
3408                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3409            }
3410            return null;
3411        }
3412
3413        final int callingUid = Binder.getCallingUid();
3414        final int resolveFlags =
3415                MATCH_DIRECT_BOOT_AWARE
3416                | MATCH_DIRECT_BOOT_UNAWARE
3417                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3418        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3419        final Intent resolverIntent = new Intent(actionName);
3420        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3421                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3422        // temporarily look for the old action
3423        if (resolvers.size() == 0) {
3424            if (DEBUG_EPHEMERAL) {
3425                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3426            }
3427            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3428            resolverIntent.setAction(actionName);
3429            resolvers = queryIntentServicesInternal(resolverIntent, null,
3430                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3431        }
3432        final int N = resolvers.size();
3433        if (N == 0) {
3434            if (DEBUG_EPHEMERAL) {
3435                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3436            }
3437            return null;
3438        }
3439
3440        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3441        for (int i = 0; i < N; i++) {
3442            final ResolveInfo info = resolvers.get(i);
3443
3444            if (info.serviceInfo == null) {
3445                continue;
3446            }
3447
3448            final String packageName = info.serviceInfo.packageName;
3449            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3450                if (DEBUG_EPHEMERAL) {
3451                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3452                            + " pkg: " + packageName + ", info:" + info);
3453                }
3454                continue;
3455            }
3456
3457            if (DEBUG_EPHEMERAL) {
3458                Slog.v(TAG, "Ephemeral resolver found;"
3459                        + " pkg: " + packageName + ", info:" + info);
3460            }
3461            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3462        }
3463        if (DEBUG_EPHEMERAL) {
3464            Slog.v(TAG, "Ephemeral resolver NOT found");
3465        }
3466        return null;
3467    }
3468
3469    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3470        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3471        intent.addCategory(Intent.CATEGORY_DEFAULT);
3472        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3473
3474        final int resolveFlags =
3475                MATCH_DIRECT_BOOT_AWARE
3476                | MATCH_DIRECT_BOOT_UNAWARE
3477                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3478        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3479                resolveFlags, UserHandle.USER_SYSTEM);
3480        // temporarily look for the old action
3481        if (matches.isEmpty()) {
3482            if (DEBUG_EPHEMERAL) {
3483                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3484            }
3485            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3486            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3487                    resolveFlags, UserHandle.USER_SYSTEM);
3488        }
3489        Iterator<ResolveInfo> iter = matches.iterator();
3490        while (iter.hasNext()) {
3491            final ResolveInfo rInfo = iter.next();
3492            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3493            if (ps != null) {
3494                final PermissionsState permissionsState = ps.getPermissionsState();
3495                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3496                    continue;
3497                }
3498            }
3499            iter.remove();
3500        }
3501        if (matches.size() == 0) {
3502            return null;
3503        } else if (matches.size() == 1) {
3504            return (ActivityInfo) matches.get(0).getComponentInfo();
3505        } else {
3506            throw new RuntimeException(
3507                    "There must be at most one ephemeral installer; found " + matches);
3508        }
3509    }
3510
3511    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3512            @NonNull ComponentName resolver) {
3513        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3514                .addCategory(Intent.CATEGORY_DEFAULT)
3515                .setPackage(resolver.getPackageName());
3516        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3517        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3518                UserHandle.USER_SYSTEM);
3519        // temporarily look for the old action
3520        if (matches.isEmpty()) {
3521            if (DEBUG_EPHEMERAL) {
3522                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3523            }
3524            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3525            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3526                    UserHandle.USER_SYSTEM);
3527        }
3528        if (matches.isEmpty()) {
3529            return null;
3530        }
3531        return matches.get(0).getComponentInfo().getComponentName();
3532    }
3533
3534    private void primeDomainVerificationsLPw(int userId) {
3535        if (DEBUG_DOMAIN_VERIFICATION) {
3536            Slog.d(TAG, "Priming domain verifications in user " + userId);
3537        }
3538
3539        SystemConfig systemConfig = SystemConfig.getInstance();
3540        ArraySet<String> packages = systemConfig.getLinkedApps();
3541
3542        for (String packageName : packages) {
3543            PackageParser.Package pkg = mPackages.get(packageName);
3544            if (pkg != null) {
3545                if (!pkg.isSystem()) {
3546                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3547                    continue;
3548                }
3549
3550                ArraySet<String> domains = null;
3551                for (PackageParser.Activity a : pkg.activities) {
3552                    for (ActivityIntentInfo filter : a.intents) {
3553                        if (hasValidDomains(filter)) {
3554                            if (domains == null) {
3555                                domains = new ArraySet<String>();
3556                            }
3557                            domains.addAll(filter.getHostsList());
3558                        }
3559                    }
3560                }
3561
3562                if (domains != null && domains.size() > 0) {
3563                    if (DEBUG_DOMAIN_VERIFICATION) {
3564                        Slog.v(TAG, "      + " + packageName);
3565                    }
3566                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3567                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3568                    // and then 'always' in the per-user state actually used for intent resolution.
3569                    final IntentFilterVerificationInfo ivi;
3570                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3571                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3572                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3573                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3574                } else {
3575                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3576                            + "' does not handle web links");
3577                }
3578            } else {
3579                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3580            }
3581        }
3582
3583        scheduleWritePackageRestrictionsLocked(userId);
3584        scheduleWriteSettingsLocked();
3585    }
3586
3587    private void applyFactoryDefaultBrowserLPw(int userId) {
3588        // The default browser app's package name is stored in a string resource,
3589        // with a product-specific overlay used for vendor customization.
3590        String browserPkg = mContext.getResources().getString(
3591                com.android.internal.R.string.default_browser);
3592        if (!TextUtils.isEmpty(browserPkg)) {
3593            // non-empty string => required to be a known package
3594            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3595            if (ps == null) {
3596                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3597                browserPkg = null;
3598            } else {
3599                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3600            }
3601        }
3602
3603        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3604        // default.  If there's more than one, just leave everything alone.
3605        if (browserPkg == null) {
3606            calculateDefaultBrowserLPw(userId);
3607        }
3608    }
3609
3610    private void calculateDefaultBrowserLPw(int userId) {
3611        List<String> allBrowsers = resolveAllBrowserApps(userId);
3612        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3613        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3614    }
3615
3616    private List<String> resolveAllBrowserApps(int userId) {
3617        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3618        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3619                PackageManager.MATCH_ALL, userId);
3620
3621        final int count = list.size();
3622        List<String> result = new ArrayList<String>(count);
3623        for (int i=0; i<count; i++) {
3624            ResolveInfo info = list.get(i);
3625            if (info.activityInfo == null
3626                    || !info.handleAllWebDataURI
3627                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3628                    || result.contains(info.activityInfo.packageName)) {
3629                continue;
3630            }
3631            result.add(info.activityInfo.packageName);
3632        }
3633
3634        return result;
3635    }
3636
3637    private boolean packageIsBrowser(String packageName, int userId) {
3638        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3639                PackageManager.MATCH_ALL, userId);
3640        final int N = list.size();
3641        for (int i = 0; i < N; i++) {
3642            ResolveInfo info = list.get(i);
3643            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3644                return true;
3645            }
3646        }
3647        return false;
3648    }
3649
3650    private void checkDefaultBrowser() {
3651        final int myUserId = UserHandle.myUserId();
3652        final String packageName = getDefaultBrowserPackageName(myUserId);
3653        if (packageName != null) {
3654            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3655            if (info == null) {
3656                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3657                synchronized (mPackages) {
3658                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3659                }
3660            }
3661        }
3662    }
3663
3664    @Override
3665    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3666            throws RemoteException {
3667        try {
3668            return super.onTransact(code, data, reply, flags);
3669        } catch (RuntimeException e) {
3670            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3671                Slog.wtf(TAG, "Package Manager Crash", e);
3672            }
3673            throw e;
3674        }
3675    }
3676
3677    static int[] appendInts(int[] cur, int[] add) {
3678        if (add == null) return cur;
3679        if (cur == null) return add;
3680        final int N = add.length;
3681        for (int i=0; i<N; i++) {
3682            cur = appendInt(cur, add[i]);
3683        }
3684        return cur;
3685    }
3686
3687    /**
3688     * Returns whether or not a full application can see an instant application.
3689     * <p>
3690     * Currently, there are three cases in which this can occur:
3691     * <ol>
3692     * <li>The calling application is a "special" process. Special processes
3693     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3694     * <li>The calling application has the permission
3695     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3696     * <li>The calling application is the default launcher on the
3697     *     system partition.</li>
3698     * </ol>
3699     */
3700    private boolean canViewInstantApps(int callingUid, int userId) {
3701        if (callingUid < Process.FIRST_APPLICATION_UID) {
3702            return true;
3703        }
3704        if (mContext.checkCallingOrSelfPermission(
3705                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3706            return true;
3707        }
3708        if (mContext.checkCallingOrSelfPermission(
3709                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3710            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3711            if (homeComponent != null
3712                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3713                return true;
3714            }
3715        }
3716        return false;
3717    }
3718
3719    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3720        if (!sUserManager.exists(userId)) return null;
3721        if (ps == null) {
3722            return null;
3723        }
3724        PackageParser.Package p = ps.pkg;
3725        if (p == null) {
3726            return null;
3727        }
3728        final int callingUid = Binder.getCallingUid();
3729        // Filter out ephemeral app metadata:
3730        //   * The system/shell/root can see metadata for any app
3731        //   * An installed app can see metadata for 1) other installed apps
3732        //     and 2) ephemeral apps that have explicitly interacted with it
3733        //   * Ephemeral apps can only see their own data and exposed installed apps
3734        //   * Holding a signature permission allows seeing instant apps
3735        if (filterAppAccessLPr(ps, callingUid, userId)) {
3736            return null;
3737        }
3738
3739        final PermissionsState permissionsState = ps.getPermissionsState();
3740
3741        // Compute GIDs only if requested
3742        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3743                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3744        // Compute granted permissions only if package has requested permissions
3745        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3746                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3747        final PackageUserState state = ps.readUserState(userId);
3748
3749        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3750                && ps.isSystem()) {
3751            flags |= MATCH_ANY_USER;
3752        }
3753
3754        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3755                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3756
3757        if (packageInfo == null) {
3758            return null;
3759        }
3760
3761        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3762                resolveExternalPackageNameLPr(p);
3763
3764        return packageInfo;
3765    }
3766
3767    @Override
3768    public void checkPackageStartable(String packageName, int userId) {
3769        final int callingUid = Binder.getCallingUid();
3770        if (getInstantAppPackageName(callingUid) != null) {
3771            throw new SecurityException("Instant applications don't have access to this method");
3772        }
3773        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3774        synchronized (mPackages) {
3775            final PackageSetting ps = mSettings.mPackages.get(packageName);
3776            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3777                throw new SecurityException("Package " + packageName + " was not found!");
3778            }
3779
3780            if (!ps.getInstalled(userId)) {
3781                throw new SecurityException(
3782                        "Package " + packageName + " was not installed for user " + userId + "!");
3783            }
3784
3785            if (mSafeMode && !ps.isSystem()) {
3786                throw new SecurityException("Package " + packageName + " not a system app!");
3787            }
3788
3789            if (mFrozenPackages.contains(packageName)) {
3790                throw new SecurityException("Package " + packageName + " is currently frozen!");
3791            }
3792
3793            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3794                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3795            }
3796        }
3797    }
3798
3799    @Override
3800    public boolean isPackageAvailable(String packageName, int userId) {
3801        if (!sUserManager.exists(userId)) return false;
3802        final int callingUid = Binder.getCallingUid();
3803        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3804                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3805        synchronized (mPackages) {
3806            PackageParser.Package p = mPackages.get(packageName);
3807            if (p != null) {
3808                final PackageSetting ps = (PackageSetting) p.mExtras;
3809                if (filterAppAccessLPr(ps, callingUid, userId)) {
3810                    return false;
3811                }
3812                if (ps != null) {
3813                    final PackageUserState state = ps.readUserState(userId);
3814                    if (state != null) {
3815                        return PackageParser.isAvailable(state);
3816                    }
3817                }
3818            }
3819        }
3820        return false;
3821    }
3822
3823    @Override
3824    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3825        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3826                flags, Binder.getCallingUid(), userId);
3827    }
3828
3829    @Override
3830    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3831            int flags, int userId) {
3832        return getPackageInfoInternal(versionedPackage.getPackageName(),
3833                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3834    }
3835
3836    /**
3837     * Important: The provided filterCallingUid is used exclusively to filter out packages
3838     * that can be seen based on user state. It's typically the original caller uid prior
3839     * to clearing. Because it can only be provided by trusted code, it's value can be
3840     * trusted and will be used as-is; unlike userId which will be validated by this method.
3841     */
3842    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3843            int flags, int filterCallingUid, int userId) {
3844        if (!sUserManager.exists(userId)) return null;
3845        flags = updateFlagsForPackage(flags, userId, packageName);
3846        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3847                false /* requireFullPermission */, false /* checkShell */, "get package info");
3848
3849        // reader
3850        synchronized (mPackages) {
3851            // Normalize package name to handle renamed packages and static libs
3852            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3853
3854            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3855            if (matchFactoryOnly) {
3856                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3857                if (ps != null) {
3858                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3859                        return null;
3860                    }
3861                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3862                        return null;
3863                    }
3864                    return generatePackageInfo(ps, flags, userId);
3865                }
3866            }
3867
3868            PackageParser.Package p = mPackages.get(packageName);
3869            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3870                return null;
3871            }
3872            if (DEBUG_PACKAGE_INFO)
3873                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3874            if (p != null) {
3875                final PackageSetting ps = (PackageSetting) p.mExtras;
3876                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3877                    return null;
3878                }
3879                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3880                    return null;
3881                }
3882                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3883            }
3884            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3885                final PackageSetting ps = mSettings.mPackages.get(packageName);
3886                if (ps == null) return null;
3887                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3888                    return null;
3889                }
3890                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3891                    return null;
3892                }
3893                return generatePackageInfo(ps, flags, userId);
3894            }
3895        }
3896        return null;
3897    }
3898
3899    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3900        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3901            return true;
3902        }
3903        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3904            return true;
3905        }
3906        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3907            return true;
3908        }
3909        return false;
3910    }
3911
3912    private boolean isComponentVisibleToInstantApp(
3913            @Nullable ComponentName component, @ComponentType int type) {
3914        if (type == TYPE_ACTIVITY) {
3915            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3916            return activity != null
3917                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3918                    : false;
3919        } else if (type == TYPE_RECEIVER) {
3920            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3921            return activity != null
3922                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3923                    : false;
3924        } else if (type == TYPE_SERVICE) {
3925            final PackageParser.Service service = mServices.mServices.get(component);
3926            return service != null
3927                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3928                    : false;
3929        } else if (type == TYPE_PROVIDER) {
3930            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3931            return provider != null
3932                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3933                    : false;
3934        } else if (type == TYPE_UNKNOWN) {
3935            return isComponentVisibleToInstantApp(component);
3936        }
3937        return false;
3938    }
3939
3940    /**
3941     * Returns whether or not access to the application should be filtered.
3942     * <p>
3943     * Access may be limited based upon whether the calling or target applications
3944     * are instant applications.
3945     *
3946     * @see #canAccessInstantApps(int)
3947     */
3948    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3949            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3950        // if we're in an isolated process, get the real calling UID
3951        if (Process.isIsolated(callingUid)) {
3952            callingUid = mIsolatedOwners.get(callingUid);
3953        }
3954        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3955        final boolean callerIsInstantApp = instantAppPkgName != null;
3956        if (ps == null) {
3957            if (callerIsInstantApp) {
3958                // pretend the application exists, but, needs to be filtered
3959                return true;
3960            }
3961            return false;
3962        }
3963        // if the target and caller are the same application, don't filter
3964        if (isCallerSameApp(ps.name, callingUid)) {
3965            return false;
3966        }
3967        if (callerIsInstantApp) {
3968            // request for a specific component; if it hasn't been explicitly exposed, filter
3969            if (component != null) {
3970                return !isComponentVisibleToInstantApp(component, componentType);
3971            }
3972            // request for application; if no components have been explicitly exposed, filter
3973            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3974        }
3975        if (ps.getInstantApp(userId)) {
3976            // caller can see all components of all instant applications, don't filter
3977            if (canViewInstantApps(callingUid, userId)) {
3978                return false;
3979            }
3980            // request for a specific instant application component, filter
3981            if (component != null) {
3982                return true;
3983            }
3984            // request for an instant application; if the caller hasn't been granted access, filter
3985            return !mInstantAppRegistry.isInstantAccessGranted(
3986                    userId, UserHandle.getAppId(callingUid), ps.appId);
3987        }
3988        return false;
3989    }
3990
3991    /**
3992     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3993     */
3994    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3995        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3996    }
3997
3998    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3999            int flags) {
4000        // Callers can access only the libs they depend on, otherwise they need to explicitly
4001        // ask for the shared libraries given the caller is allowed to access all static libs.
4002        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4003            // System/shell/root get to see all static libs
4004            final int appId = UserHandle.getAppId(uid);
4005            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4006                    || appId == Process.ROOT_UID) {
4007                return false;
4008            }
4009        }
4010
4011        // No package means no static lib as it is always on internal storage
4012        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4013            return false;
4014        }
4015
4016        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4017                ps.pkg.staticSharedLibVersion);
4018        if (libEntry == null) {
4019            return false;
4020        }
4021
4022        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4023        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4024        if (uidPackageNames == null) {
4025            return true;
4026        }
4027
4028        for (String uidPackageName : uidPackageNames) {
4029            if (ps.name.equals(uidPackageName)) {
4030                return false;
4031            }
4032            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4033            if (uidPs != null) {
4034                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4035                        libEntry.info.getName());
4036                if (index < 0) {
4037                    continue;
4038                }
4039                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4040                    return false;
4041                }
4042            }
4043        }
4044        return true;
4045    }
4046
4047    @Override
4048    public String[] currentToCanonicalPackageNames(String[] names) {
4049        final int callingUid = Binder.getCallingUid();
4050        if (getInstantAppPackageName(callingUid) != null) {
4051            return names;
4052        }
4053        final String[] out = new String[names.length];
4054        // reader
4055        synchronized (mPackages) {
4056            final int callingUserId = UserHandle.getUserId(callingUid);
4057            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4058            for (int i=names.length-1; i>=0; i--) {
4059                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4060                boolean translateName = false;
4061                if (ps != null && ps.realName != null) {
4062                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4063                    translateName = !targetIsInstantApp
4064                            || canViewInstantApps
4065                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4066                                    UserHandle.getAppId(callingUid), ps.appId);
4067                }
4068                out[i] = translateName ? ps.realName : names[i];
4069            }
4070        }
4071        return out;
4072    }
4073
4074    @Override
4075    public String[] canonicalToCurrentPackageNames(String[] names) {
4076        final int callingUid = Binder.getCallingUid();
4077        if (getInstantAppPackageName(callingUid) != null) {
4078            return names;
4079        }
4080        final String[] out = new String[names.length];
4081        // reader
4082        synchronized (mPackages) {
4083            final int callingUserId = UserHandle.getUserId(callingUid);
4084            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4085            for (int i=names.length-1; i>=0; i--) {
4086                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4087                boolean translateName = false;
4088                if (cur != null) {
4089                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4090                    final boolean targetIsInstantApp =
4091                            ps != null && ps.getInstantApp(callingUserId);
4092                    translateName = !targetIsInstantApp
4093                            || canViewInstantApps
4094                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4095                                    UserHandle.getAppId(callingUid), ps.appId);
4096                }
4097                out[i] = translateName ? cur : names[i];
4098            }
4099        }
4100        return out;
4101    }
4102
4103    @Override
4104    public int getPackageUid(String packageName, int flags, int userId) {
4105        if (!sUserManager.exists(userId)) return -1;
4106        final int callingUid = Binder.getCallingUid();
4107        flags = updateFlagsForPackage(flags, userId, packageName);
4108        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4109                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4110
4111        // reader
4112        synchronized (mPackages) {
4113            final PackageParser.Package p = mPackages.get(packageName);
4114            if (p != null && p.isMatch(flags)) {
4115                PackageSetting ps = (PackageSetting) p.mExtras;
4116                if (filterAppAccessLPr(ps, callingUid, userId)) {
4117                    return -1;
4118                }
4119                return UserHandle.getUid(userId, p.applicationInfo.uid);
4120            }
4121            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4122                final PackageSetting ps = mSettings.mPackages.get(packageName);
4123                if (ps != null && ps.isMatch(flags)
4124                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4125                    return UserHandle.getUid(userId, ps.appId);
4126                }
4127            }
4128        }
4129
4130        return -1;
4131    }
4132
4133    @Override
4134    public int[] getPackageGids(String packageName, int flags, int userId) {
4135        if (!sUserManager.exists(userId)) return null;
4136        final int callingUid = Binder.getCallingUid();
4137        flags = updateFlagsForPackage(flags, userId, packageName);
4138        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4139                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4140
4141        // reader
4142        synchronized (mPackages) {
4143            final PackageParser.Package p = mPackages.get(packageName);
4144            if (p != null && p.isMatch(flags)) {
4145                PackageSetting ps = (PackageSetting) p.mExtras;
4146                if (filterAppAccessLPr(ps, callingUid, userId)) {
4147                    return null;
4148                }
4149                // TODO: Shouldn't this be checking for package installed state for userId and
4150                // return null?
4151                return ps.getPermissionsState().computeGids(userId);
4152            }
4153            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4154                final PackageSetting ps = mSettings.mPackages.get(packageName);
4155                if (ps != null && ps.isMatch(flags)
4156                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4157                    return ps.getPermissionsState().computeGids(userId);
4158                }
4159            }
4160        }
4161
4162        return null;
4163    }
4164
4165    @Override
4166    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4167        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4168    }
4169
4170    @Override
4171    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4172            int flags) {
4173        final List<PermissionInfo> permissionList =
4174                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4175        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4176    }
4177
4178    @Override
4179    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4180        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4181    }
4182
4183    @Override
4184    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4185        final List<PermissionGroupInfo> permissionList =
4186                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4187        return (permissionList == null)
4188                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4189    }
4190
4191    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4192            int filterCallingUid, int userId) {
4193        if (!sUserManager.exists(userId)) return null;
4194        PackageSetting ps = mSettings.mPackages.get(packageName);
4195        if (ps != null) {
4196            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4197                return null;
4198            }
4199            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4200                return null;
4201            }
4202            if (ps.pkg == null) {
4203                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4204                if (pInfo != null) {
4205                    return pInfo.applicationInfo;
4206                }
4207                return null;
4208            }
4209            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4210                    ps.readUserState(userId), userId);
4211            if (ai != null) {
4212                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4213            }
4214            return ai;
4215        }
4216        return null;
4217    }
4218
4219    @Override
4220    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4221        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4222    }
4223
4224    /**
4225     * Important: The provided filterCallingUid is used exclusively to filter out applications
4226     * that can be seen based on user state. It's typically the original caller uid prior
4227     * to clearing. Because it can only be provided by trusted code, it's value can be
4228     * trusted and will be used as-is; unlike userId which will be validated by this method.
4229     */
4230    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4231            int filterCallingUid, int userId) {
4232        if (!sUserManager.exists(userId)) return null;
4233        flags = updateFlagsForApplication(flags, userId, packageName);
4234        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4235                false /* requireFullPermission */, false /* checkShell */, "get application info");
4236
4237        // writer
4238        synchronized (mPackages) {
4239            // Normalize package name to handle renamed packages and static libs
4240            packageName = resolveInternalPackageNameLPr(packageName,
4241                    PackageManager.VERSION_CODE_HIGHEST);
4242
4243            PackageParser.Package p = mPackages.get(packageName);
4244            if (DEBUG_PACKAGE_INFO) Log.v(
4245                    TAG, "getApplicationInfo " + packageName
4246                    + ": " + p);
4247            if (p != null) {
4248                PackageSetting ps = mSettings.mPackages.get(packageName);
4249                if (ps == null) return null;
4250                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4251                    return null;
4252                }
4253                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4254                    return null;
4255                }
4256                // Note: isEnabledLP() does not apply here - always return info
4257                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4258                        p, flags, ps.readUserState(userId), userId);
4259                if (ai != null) {
4260                    ai.packageName = resolveExternalPackageNameLPr(p);
4261                }
4262                return ai;
4263            }
4264            if ("android".equals(packageName)||"system".equals(packageName)) {
4265                return mAndroidApplication;
4266            }
4267            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4268                // Already generates the external package name
4269                return generateApplicationInfoFromSettingsLPw(packageName,
4270                        flags, filterCallingUid, userId);
4271            }
4272        }
4273        return null;
4274    }
4275
4276    private String normalizePackageNameLPr(String packageName) {
4277        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4278        return normalizedPackageName != null ? normalizedPackageName : packageName;
4279    }
4280
4281    @Override
4282    public void deletePreloadsFileCache() {
4283        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4284            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4285        }
4286        File dir = Environment.getDataPreloadsFileCacheDirectory();
4287        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4288        FileUtils.deleteContents(dir);
4289    }
4290
4291    @Override
4292    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4293            final int storageFlags, final IPackageDataObserver observer) {
4294        mContext.enforceCallingOrSelfPermission(
4295                android.Manifest.permission.CLEAR_APP_CACHE, null);
4296        mHandler.post(() -> {
4297            boolean success = false;
4298            try {
4299                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4300                success = true;
4301            } catch (IOException e) {
4302                Slog.w(TAG, e);
4303            }
4304            if (observer != null) {
4305                try {
4306                    observer.onRemoveCompleted(null, success);
4307                } catch (RemoteException e) {
4308                    Slog.w(TAG, e);
4309                }
4310            }
4311        });
4312    }
4313
4314    @Override
4315    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4316            final int storageFlags, final IntentSender pi) {
4317        mContext.enforceCallingOrSelfPermission(
4318                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4319        mHandler.post(() -> {
4320            boolean success = false;
4321            try {
4322                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4323                success = true;
4324            } catch (IOException e) {
4325                Slog.w(TAG, e);
4326            }
4327            if (pi != null) {
4328                try {
4329                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4330                } catch (SendIntentException e) {
4331                    Slog.w(TAG, e);
4332                }
4333            }
4334        });
4335    }
4336
4337    /**
4338     * Blocking call to clear various types of cached data across the system
4339     * until the requested bytes are available.
4340     */
4341    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4342        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4343        final File file = storage.findPathForUuid(volumeUuid);
4344        if (file.getUsableSpace() >= bytes) return;
4345
4346        if (ENABLE_FREE_CACHE_V2) {
4347            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4348                    volumeUuid);
4349            final boolean aggressive = (storageFlags
4350                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4351            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4352
4353            // 1. Pre-flight to determine if we have any chance to succeed
4354            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4355            if (internalVolume && (aggressive || SystemProperties
4356                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4357                deletePreloadsFileCache();
4358                if (file.getUsableSpace() >= bytes) return;
4359            }
4360
4361            // 3. Consider parsed APK data (aggressive only)
4362            if (internalVolume && aggressive) {
4363                FileUtils.deleteContents(mCacheDir);
4364                if (file.getUsableSpace() >= bytes) return;
4365            }
4366
4367            // 4. Consider cached app data (above quotas)
4368            try {
4369                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4370                        Installer.FLAG_FREE_CACHE_V2);
4371            } catch (InstallerException ignored) {
4372            }
4373            if (file.getUsableSpace() >= bytes) return;
4374
4375            // 5. Consider shared libraries with refcount=0 and age>min cache period
4376            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4377                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4378                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4379                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4380                return;
4381            }
4382
4383            // 6. Consider dexopt output (aggressive only)
4384            // TODO: Implement
4385
4386            // 7. Consider installed instant apps unused longer than min cache period
4387            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4388                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4389                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4390                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4391                return;
4392            }
4393
4394            // 8. Consider cached app data (below quotas)
4395            try {
4396                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4397                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4398            } catch (InstallerException ignored) {
4399            }
4400            if (file.getUsableSpace() >= bytes) return;
4401
4402            // 9. Consider DropBox entries
4403            // TODO: Implement
4404
4405            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4406            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4407                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4408                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4409                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4410                return;
4411            }
4412        } else {
4413            try {
4414                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4415            } catch (InstallerException ignored) {
4416            }
4417            if (file.getUsableSpace() >= bytes) return;
4418        }
4419
4420        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4421    }
4422
4423    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4424            throws IOException {
4425        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4426        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4427
4428        List<VersionedPackage> packagesToDelete = null;
4429        final long now = System.currentTimeMillis();
4430
4431        synchronized (mPackages) {
4432            final int[] allUsers = sUserManager.getUserIds();
4433            final int libCount = mSharedLibraries.size();
4434            for (int i = 0; i < libCount; i++) {
4435                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4436                if (versionedLib == null) {
4437                    continue;
4438                }
4439                final int versionCount = versionedLib.size();
4440                for (int j = 0; j < versionCount; j++) {
4441                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4442                    // Skip packages that are not static shared libs.
4443                    if (!libInfo.isStatic()) {
4444                        break;
4445                    }
4446                    // Important: We skip static shared libs used for some user since
4447                    // in such a case we need to keep the APK on the device. The check for
4448                    // a lib being used for any user is performed by the uninstall call.
4449                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4450                    // Resolve the package name - we use synthetic package names internally
4451                    final String internalPackageName = resolveInternalPackageNameLPr(
4452                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4453                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4454                    // Skip unused static shared libs cached less than the min period
4455                    // to prevent pruning a lib needed by a subsequently installed package.
4456                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4457                        continue;
4458                    }
4459                    if (packagesToDelete == null) {
4460                        packagesToDelete = new ArrayList<>();
4461                    }
4462                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4463                            declaringPackage.getVersionCode()));
4464                }
4465            }
4466        }
4467
4468        if (packagesToDelete != null) {
4469            final int packageCount = packagesToDelete.size();
4470            for (int i = 0; i < packageCount; i++) {
4471                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4472                // Delete the package synchronously (will fail of the lib used for any user).
4473                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4474                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4475                                == PackageManager.DELETE_SUCCEEDED) {
4476                    if (volume.getUsableSpace() >= neededSpace) {
4477                        return true;
4478                    }
4479                }
4480            }
4481        }
4482
4483        return false;
4484    }
4485
4486    /**
4487     * Update given flags based on encryption status of current user.
4488     */
4489    private int updateFlags(int flags, int userId) {
4490        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4491                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4492            // Caller expressed an explicit opinion about what encryption
4493            // aware/unaware components they want to see, so fall through and
4494            // give them what they want
4495        } else {
4496            // Caller expressed no opinion, so match based on user state
4497            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4498                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4499            } else {
4500                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4501            }
4502        }
4503        return flags;
4504    }
4505
4506    private UserManagerInternal getUserManagerInternal() {
4507        if (mUserManagerInternal == null) {
4508            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4509        }
4510        return mUserManagerInternal;
4511    }
4512
4513    private DeviceIdleController.LocalService getDeviceIdleController() {
4514        if (mDeviceIdleController == null) {
4515            mDeviceIdleController =
4516                    LocalServices.getService(DeviceIdleController.LocalService.class);
4517        }
4518        return mDeviceIdleController;
4519    }
4520
4521    /**
4522     * Update given flags when being used to request {@link PackageInfo}.
4523     */
4524    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4525        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4526        boolean triaged = true;
4527        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4528                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4529            // Caller is asking for component details, so they'd better be
4530            // asking for specific encryption matching behavior, or be triaged
4531            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4532                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4533                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4534                triaged = false;
4535            }
4536        }
4537        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4538                | PackageManager.MATCH_SYSTEM_ONLY
4539                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4540            triaged = false;
4541        }
4542        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4543            mPermissionManager.enforceCrossUserPermission(
4544                    Binder.getCallingUid(), userId, false, false,
4545                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4546                    + Debug.getCallers(5));
4547        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4548                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4549            // If the caller wants all packages and has a restricted profile associated with it,
4550            // then match all users. This is to make sure that launchers that need to access work
4551            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4552            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4553            flags |= PackageManager.MATCH_ANY_USER;
4554        }
4555        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4556            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4557                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4558        }
4559        return updateFlags(flags, userId);
4560    }
4561
4562    /**
4563     * Update given flags when being used to request {@link ApplicationInfo}.
4564     */
4565    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4566        return updateFlagsForPackage(flags, userId, cookie);
4567    }
4568
4569    /**
4570     * Update given flags when being used to request {@link ComponentInfo}.
4571     */
4572    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4573        if (cookie instanceof Intent) {
4574            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4575                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4576            }
4577        }
4578
4579        boolean triaged = true;
4580        // Caller is asking for component details, so they'd better be
4581        // asking for specific encryption matching behavior, or be triaged
4582        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4583                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4584                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4585            triaged = false;
4586        }
4587        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4588            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4589                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4590        }
4591
4592        return updateFlags(flags, userId);
4593    }
4594
4595    /**
4596     * Update given intent when being used to request {@link ResolveInfo}.
4597     */
4598    private Intent updateIntentForResolve(Intent intent) {
4599        if (intent.getSelector() != null) {
4600            intent = intent.getSelector();
4601        }
4602        if (DEBUG_PREFERRED) {
4603            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4604        }
4605        return intent;
4606    }
4607
4608    /**
4609     * Update given flags when being used to request {@link ResolveInfo}.
4610     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4611     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4612     * flag set. However, this flag is only honoured in three circumstances:
4613     * <ul>
4614     * <li>when called from a system process</li>
4615     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4616     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4617     * action and a {@code android.intent.category.BROWSABLE} category</li>
4618     * </ul>
4619     */
4620    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4621        return updateFlagsForResolve(flags, userId, intent, callingUid,
4622                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4623    }
4624    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4625            boolean wantInstantApps) {
4626        return updateFlagsForResolve(flags, userId, intent, callingUid,
4627                wantInstantApps, false /*onlyExposedExplicitly*/);
4628    }
4629    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4630            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4631        // Safe mode means we shouldn't match any third-party components
4632        if (mSafeMode) {
4633            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4634        }
4635        if (getInstantAppPackageName(callingUid) != null) {
4636            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4637            if (onlyExposedExplicitly) {
4638                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4639            }
4640            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4641            flags |= PackageManager.MATCH_INSTANT;
4642        } else {
4643            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4644            final boolean allowMatchInstant =
4645                    (wantInstantApps
4646                            && Intent.ACTION_VIEW.equals(intent.getAction())
4647                            && hasWebURI(intent))
4648                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4649            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4650                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4651            if (!allowMatchInstant) {
4652                flags &= ~PackageManager.MATCH_INSTANT;
4653            }
4654        }
4655        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4656    }
4657
4658    @Override
4659    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4660        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4661    }
4662
4663    /**
4664     * Important: The provided filterCallingUid is used exclusively to filter out activities
4665     * that can be seen based on user state. It's typically the original caller uid prior
4666     * to clearing. Because it can only be provided by trusted code, it's value can be
4667     * trusted and will be used as-is; unlike userId which will be validated by this method.
4668     */
4669    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4670            int filterCallingUid, int userId) {
4671        if (!sUserManager.exists(userId)) return null;
4672        flags = updateFlagsForComponent(flags, userId, component);
4673        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4674                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4675        synchronized (mPackages) {
4676            PackageParser.Activity a = mActivities.mActivities.get(component);
4677
4678            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4679            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4680                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4681                if (ps == null) return null;
4682                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4683                    return null;
4684                }
4685                return PackageParser.generateActivityInfo(
4686                        a, flags, ps.readUserState(userId), userId);
4687            }
4688            if (mResolveComponentName.equals(component)) {
4689                return PackageParser.generateActivityInfo(
4690                        mResolveActivity, flags, new PackageUserState(), userId);
4691            }
4692        }
4693        return null;
4694    }
4695
4696    @Override
4697    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4698            String resolvedType) {
4699        synchronized (mPackages) {
4700            if (component.equals(mResolveComponentName)) {
4701                // The resolver supports EVERYTHING!
4702                return true;
4703            }
4704            final int callingUid = Binder.getCallingUid();
4705            final int callingUserId = UserHandle.getUserId(callingUid);
4706            PackageParser.Activity a = mActivities.mActivities.get(component);
4707            if (a == null) {
4708                return false;
4709            }
4710            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4711            if (ps == null) {
4712                return false;
4713            }
4714            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4715                return false;
4716            }
4717            for (int i=0; i<a.intents.size(); i++) {
4718                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4719                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4720                    return true;
4721                }
4722            }
4723            return false;
4724        }
4725    }
4726
4727    @Override
4728    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4729        if (!sUserManager.exists(userId)) return null;
4730        final int callingUid = Binder.getCallingUid();
4731        flags = updateFlagsForComponent(flags, userId, component);
4732        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4733                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4734        synchronized (mPackages) {
4735            PackageParser.Activity a = mReceivers.mActivities.get(component);
4736            if (DEBUG_PACKAGE_INFO) Log.v(
4737                TAG, "getReceiverInfo " + component + ": " + a);
4738            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4739                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4740                if (ps == null) return null;
4741                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4742                    return null;
4743                }
4744                return PackageParser.generateActivityInfo(
4745                        a, flags, ps.readUserState(userId), userId);
4746            }
4747        }
4748        return null;
4749    }
4750
4751    @Override
4752    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4753            int flags, int userId) {
4754        if (!sUserManager.exists(userId)) return null;
4755        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4756        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4757            return null;
4758        }
4759
4760        flags = updateFlagsForPackage(flags, userId, null);
4761
4762        final boolean canSeeStaticLibraries =
4763                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4764                        == PERMISSION_GRANTED
4765                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4766                        == PERMISSION_GRANTED
4767                || canRequestPackageInstallsInternal(packageName,
4768                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4769                        false  /* throwIfPermNotDeclared*/)
4770                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4771                        == PERMISSION_GRANTED;
4772
4773        synchronized (mPackages) {
4774            List<SharedLibraryInfo> result = null;
4775
4776            final int libCount = mSharedLibraries.size();
4777            for (int i = 0; i < libCount; i++) {
4778                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4779                if (versionedLib == null) {
4780                    continue;
4781                }
4782
4783                final int versionCount = versionedLib.size();
4784                for (int j = 0; j < versionCount; j++) {
4785                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4786                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4787                        break;
4788                    }
4789                    final long identity = Binder.clearCallingIdentity();
4790                    try {
4791                        PackageInfo packageInfo = getPackageInfoVersioned(
4792                                libInfo.getDeclaringPackage(), flags
4793                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4794                        if (packageInfo == null) {
4795                            continue;
4796                        }
4797                    } finally {
4798                        Binder.restoreCallingIdentity(identity);
4799                    }
4800
4801                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4802                            libInfo.getVersion(), libInfo.getType(),
4803                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4804                            flags, userId));
4805
4806                    if (result == null) {
4807                        result = new ArrayList<>();
4808                    }
4809                    result.add(resLibInfo);
4810                }
4811            }
4812
4813            return result != null ? new ParceledListSlice<>(result) : null;
4814        }
4815    }
4816
4817    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4818            SharedLibraryInfo libInfo, int flags, int userId) {
4819        List<VersionedPackage> versionedPackages = null;
4820        final int packageCount = mSettings.mPackages.size();
4821        for (int i = 0; i < packageCount; i++) {
4822            PackageSetting ps = mSettings.mPackages.valueAt(i);
4823
4824            if (ps == null) {
4825                continue;
4826            }
4827
4828            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4829                continue;
4830            }
4831
4832            final String libName = libInfo.getName();
4833            if (libInfo.isStatic()) {
4834                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4835                if (libIdx < 0) {
4836                    continue;
4837                }
4838                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4839                    continue;
4840                }
4841                if (versionedPackages == null) {
4842                    versionedPackages = new ArrayList<>();
4843                }
4844                // If the dependent is a static shared lib, use the public package name
4845                String dependentPackageName = ps.name;
4846                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4847                    dependentPackageName = ps.pkg.manifestPackageName;
4848                }
4849                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4850            } else if (ps.pkg != null) {
4851                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4852                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4853                    if (versionedPackages == null) {
4854                        versionedPackages = new ArrayList<>();
4855                    }
4856                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4857                }
4858            }
4859        }
4860
4861        return versionedPackages;
4862    }
4863
4864    @Override
4865    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4866        if (!sUserManager.exists(userId)) return null;
4867        final int callingUid = Binder.getCallingUid();
4868        flags = updateFlagsForComponent(flags, userId, component);
4869        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4870                false /* requireFullPermission */, false /* checkShell */, "get service info");
4871        synchronized (mPackages) {
4872            PackageParser.Service s = mServices.mServices.get(component);
4873            if (DEBUG_PACKAGE_INFO) Log.v(
4874                TAG, "getServiceInfo " + component + ": " + s);
4875            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4876                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4877                if (ps == null) return null;
4878                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4879                    return null;
4880                }
4881                return PackageParser.generateServiceInfo(
4882                        s, flags, ps.readUserState(userId), userId);
4883            }
4884        }
4885        return null;
4886    }
4887
4888    @Override
4889    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4890        if (!sUserManager.exists(userId)) return null;
4891        final int callingUid = Binder.getCallingUid();
4892        flags = updateFlagsForComponent(flags, userId, component);
4893        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4894                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4895        synchronized (mPackages) {
4896            PackageParser.Provider p = mProviders.mProviders.get(component);
4897            if (DEBUG_PACKAGE_INFO) Log.v(
4898                TAG, "getProviderInfo " + component + ": " + p);
4899            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4900                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4901                if (ps == null) return null;
4902                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4903                    return null;
4904                }
4905                return PackageParser.generateProviderInfo(
4906                        p, flags, ps.readUserState(userId), userId);
4907            }
4908        }
4909        return null;
4910    }
4911
4912    @Override
4913    public String[] getSystemSharedLibraryNames() {
4914        // allow instant applications
4915        synchronized (mPackages) {
4916            Set<String> libs = null;
4917            final int libCount = mSharedLibraries.size();
4918            for (int i = 0; i < libCount; i++) {
4919                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4920                if (versionedLib == null) {
4921                    continue;
4922                }
4923                final int versionCount = versionedLib.size();
4924                for (int j = 0; j < versionCount; j++) {
4925                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4926                    if (!libEntry.info.isStatic()) {
4927                        if (libs == null) {
4928                            libs = new ArraySet<>();
4929                        }
4930                        libs.add(libEntry.info.getName());
4931                        break;
4932                    }
4933                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4934                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4935                            UserHandle.getUserId(Binder.getCallingUid()),
4936                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4937                        if (libs == null) {
4938                            libs = new ArraySet<>();
4939                        }
4940                        libs.add(libEntry.info.getName());
4941                        break;
4942                    }
4943                }
4944            }
4945
4946            if (libs != null) {
4947                String[] libsArray = new String[libs.size()];
4948                libs.toArray(libsArray);
4949                return libsArray;
4950            }
4951
4952            return null;
4953        }
4954    }
4955
4956    @Override
4957    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4958        // allow instant applications
4959        synchronized (mPackages) {
4960            return mServicesSystemSharedLibraryPackageName;
4961        }
4962    }
4963
4964    @Override
4965    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4966        // allow instant applications
4967        synchronized (mPackages) {
4968            return mSharedSystemSharedLibraryPackageName;
4969        }
4970    }
4971
4972    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4973        for (int i = userList.length - 1; i >= 0; --i) {
4974            final int userId = userList[i];
4975            // don't add instant app to the list of updates
4976            if (pkgSetting.getInstantApp(userId)) {
4977                continue;
4978            }
4979            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4980            if (changedPackages == null) {
4981                changedPackages = new SparseArray<>();
4982                mChangedPackages.put(userId, changedPackages);
4983            }
4984            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4985            if (sequenceNumbers == null) {
4986                sequenceNumbers = new HashMap<>();
4987                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4988            }
4989            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4990            if (sequenceNumber != null) {
4991                changedPackages.remove(sequenceNumber);
4992            }
4993            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4994            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4995        }
4996        mChangedPackagesSequenceNumber++;
4997    }
4998
4999    @Override
5000    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5001        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5002            return null;
5003        }
5004        synchronized (mPackages) {
5005            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5006                return null;
5007            }
5008            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5009            if (changedPackages == null) {
5010                return null;
5011            }
5012            final List<String> packageNames =
5013                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5014            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5015                final String packageName = changedPackages.get(i);
5016                if (packageName != null) {
5017                    packageNames.add(packageName);
5018                }
5019            }
5020            return packageNames.isEmpty()
5021                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5022        }
5023    }
5024
5025    @Override
5026    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5027        // allow instant applications
5028        ArrayList<FeatureInfo> res;
5029        synchronized (mAvailableFeatures) {
5030            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5031            res.addAll(mAvailableFeatures.values());
5032        }
5033        final FeatureInfo fi = new FeatureInfo();
5034        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5035                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5036        res.add(fi);
5037
5038        return new ParceledListSlice<>(res);
5039    }
5040
5041    @Override
5042    public boolean hasSystemFeature(String name, int version) {
5043        // allow instant applications
5044        synchronized (mAvailableFeatures) {
5045            final FeatureInfo feat = mAvailableFeatures.get(name);
5046            if (feat == null) {
5047                return false;
5048            } else {
5049                return feat.version >= version;
5050            }
5051        }
5052    }
5053
5054    @Override
5055    public int checkPermission(String permName, String pkgName, int userId) {
5056        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5057    }
5058
5059    @Override
5060    public int checkUidPermission(String permName, int uid) {
5061        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5062    }
5063
5064    @Override
5065    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5066        if (UserHandle.getCallingUserId() != userId) {
5067            mContext.enforceCallingPermission(
5068                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5069                    "isPermissionRevokedByPolicy for user " + userId);
5070        }
5071
5072        if (checkPermission(permission, packageName, userId)
5073                == PackageManager.PERMISSION_GRANTED) {
5074            return false;
5075        }
5076
5077        final int callingUid = Binder.getCallingUid();
5078        if (getInstantAppPackageName(callingUid) != null) {
5079            if (!isCallerSameApp(packageName, callingUid)) {
5080                return false;
5081            }
5082        } else {
5083            if (isInstantApp(packageName, userId)) {
5084                return false;
5085            }
5086        }
5087
5088        final long identity = Binder.clearCallingIdentity();
5089        try {
5090            final int flags = getPermissionFlags(permission, packageName, userId);
5091            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5092        } finally {
5093            Binder.restoreCallingIdentity(identity);
5094        }
5095    }
5096
5097    @Override
5098    public String getPermissionControllerPackageName() {
5099        synchronized (mPackages) {
5100            return mRequiredInstallerPackage;
5101        }
5102    }
5103
5104    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5105        return mPermissionManager.addDynamicPermission(
5106                info, async, getCallingUid(), new PermissionCallback() {
5107                    @Override
5108                    public void onPermissionChanged() {
5109                        if (!async) {
5110                            mSettings.writeLPr();
5111                        } else {
5112                            scheduleWriteSettingsLocked();
5113                        }
5114                    }
5115                });
5116    }
5117
5118    @Override
5119    public boolean addPermission(PermissionInfo info) {
5120        synchronized (mPackages) {
5121            return addDynamicPermission(info, false);
5122        }
5123    }
5124
5125    @Override
5126    public boolean addPermissionAsync(PermissionInfo info) {
5127        synchronized (mPackages) {
5128            return addDynamicPermission(info, true);
5129        }
5130    }
5131
5132    @Override
5133    public void removePermission(String permName) {
5134        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5135    }
5136
5137    @Override
5138    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5139        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5140                getCallingUid(), userId, mPermissionCallback);
5141    }
5142
5143    @Override
5144    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5145        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5146                getCallingUid(), userId, mPermissionCallback);
5147    }
5148
5149    @Override
5150    public void resetRuntimePermissions() {
5151        mContext.enforceCallingOrSelfPermission(
5152                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5153                "revokeRuntimePermission");
5154
5155        int callingUid = Binder.getCallingUid();
5156        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5157            mContext.enforceCallingOrSelfPermission(
5158                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5159                    "resetRuntimePermissions");
5160        }
5161
5162        synchronized (mPackages) {
5163            mPermissionManager.updateAllPermissions(
5164                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5165                    mPermissionCallback);
5166            for (int userId : UserManagerService.getInstance().getUserIds()) {
5167                final int packageCount = mPackages.size();
5168                for (int i = 0; i < packageCount; i++) {
5169                    PackageParser.Package pkg = mPackages.valueAt(i);
5170                    if (!(pkg.mExtras instanceof PackageSetting)) {
5171                        continue;
5172                    }
5173                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5174                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5175                }
5176            }
5177        }
5178    }
5179
5180    @Override
5181    public int getPermissionFlags(String permName, String packageName, int userId) {
5182        return mPermissionManager.getPermissionFlags(
5183                permName, packageName, getCallingUid(), userId);
5184    }
5185
5186    @Override
5187    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5188            int flagValues, int userId) {
5189        mPermissionManager.updatePermissionFlags(
5190                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5191                mPermissionCallback);
5192    }
5193
5194    /**
5195     * Update the permission flags for all packages and runtime permissions of a user in order
5196     * to allow device or profile owner to remove POLICY_FIXED.
5197     */
5198    @Override
5199    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5200        synchronized (mPackages) {
5201            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5202                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5203                    mPermissionCallback);
5204            if (changed) {
5205                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5206            }
5207        }
5208    }
5209
5210    @Override
5211    public boolean shouldShowRequestPermissionRationale(String permissionName,
5212            String packageName, int userId) {
5213        if (UserHandle.getCallingUserId() != userId) {
5214            mContext.enforceCallingPermission(
5215                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5216                    "canShowRequestPermissionRationale for user " + userId);
5217        }
5218
5219        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5220        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5221            return false;
5222        }
5223
5224        if (checkPermission(permissionName, packageName, userId)
5225                == PackageManager.PERMISSION_GRANTED) {
5226            return false;
5227        }
5228
5229        final int flags;
5230
5231        final long identity = Binder.clearCallingIdentity();
5232        try {
5233            flags = getPermissionFlags(permissionName,
5234                    packageName, userId);
5235        } finally {
5236            Binder.restoreCallingIdentity(identity);
5237        }
5238
5239        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5240                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5241                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5242
5243        if ((flags & fixedFlags) != 0) {
5244            return false;
5245        }
5246
5247        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5248    }
5249
5250    @Override
5251    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5252        mContext.enforceCallingOrSelfPermission(
5253                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5254                "addOnPermissionsChangeListener");
5255
5256        synchronized (mPackages) {
5257            mOnPermissionChangeListeners.addListenerLocked(listener);
5258        }
5259    }
5260
5261    @Override
5262    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5264            throw new SecurityException("Instant applications don't have access to this method");
5265        }
5266        synchronized (mPackages) {
5267            mOnPermissionChangeListeners.removeListenerLocked(listener);
5268        }
5269    }
5270
5271    @Override
5272    public boolean isProtectedBroadcast(String actionName) {
5273        // allow instant applications
5274        synchronized (mProtectedBroadcasts) {
5275            if (mProtectedBroadcasts.contains(actionName)) {
5276                return true;
5277            } else if (actionName != null) {
5278                // TODO: remove these terrible hacks
5279                if (actionName.startsWith("android.net.netmon.lingerExpired")
5280                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5281                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5282                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5283                    return true;
5284                }
5285            }
5286        }
5287        return false;
5288    }
5289
5290    @Override
5291    public int checkSignatures(String pkg1, String pkg2) {
5292        synchronized (mPackages) {
5293            final PackageParser.Package p1 = mPackages.get(pkg1);
5294            final PackageParser.Package p2 = mPackages.get(pkg2);
5295            if (p1 == null || p1.mExtras == null
5296                    || p2 == null || p2.mExtras == null) {
5297                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5298            }
5299            final int callingUid = Binder.getCallingUid();
5300            final int callingUserId = UserHandle.getUserId(callingUid);
5301            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5302            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5303            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5304                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5305                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5306            }
5307            return compareSignatures(p1.mSignatures, p2.mSignatures);
5308        }
5309    }
5310
5311    @Override
5312    public int checkUidSignatures(int uid1, int uid2) {
5313        final int callingUid = Binder.getCallingUid();
5314        final int callingUserId = UserHandle.getUserId(callingUid);
5315        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5316        // Map to base uids.
5317        uid1 = UserHandle.getAppId(uid1);
5318        uid2 = UserHandle.getAppId(uid2);
5319        // reader
5320        synchronized (mPackages) {
5321            Signature[] s1;
5322            Signature[] s2;
5323            Object obj = mSettings.getUserIdLPr(uid1);
5324            if (obj != null) {
5325                if (obj instanceof SharedUserSetting) {
5326                    if (isCallerInstantApp) {
5327                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5328                    }
5329                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5330                } else if (obj instanceof PackageSetting) {
5331                    final PackageSetting ps = (PackageSetting) obj;
5332                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5333                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5334                    }
5335                    s1 = ps.signatures.mSignatures;
5336                } else {
5337                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5338                }
5339            } else {
5340                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5341            }
5342            obj = mSettings.getUserIdLPr(uid2);
5343            if (obj != null) {
5344                if (obj instanceof SharedUserSetting) {
5345                    if (isCallerInstantApp) {
5346                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5347                    }
5348                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5349                } else if (obj instanceof PackageSetting) {
5350                    final PackageSetting ps = (PackageSetting) obj;
5351                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5352                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5353                    }
5354                    s2 = ps.signatures.mSignatures;
5355                } else {
5356                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5357                }
5358            } else {
5359                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5360            }
5361            return compareSignatures(s1, s2);
5362        }
5363    }
5364
5365    /**
5366     * This method should typically only be used when granting or revoking
5367     * permissions, since the app may immediately restart after this call.
5368     * <p>
5369     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5370     * guard your work against the app being relaunched.
5371     */
5372    private void killUid(int appId, int userId, String reason) {
5373        final long identity = Binder.clearCallingIdentity();
5374        try {
5375            IActivityManager am = ActivityManager.getService();
5376            if (am != null) {
5377                try {
5378                    am.killUid(appId, userId, reason);
5379                } catch (RemoteException e) {
5380                    /* ignore - same process */
5381                }
5382            }
5383        } finally {
5384            Binder.restoreCallingIdentity(identity);
5385        }
5386    }
5387
5388    /**
5389     * If the database version for this type of package (internal storage or
5390     * external storage) is less than the version where package signatures
5391     * were updated, return true.
5392     */
5393    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5394        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5395        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5396    }
5397
5398    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5399        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5400        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5401    }
5402
5403    @Override
5404    public List<String> getAllPackages() {
5405        final int callingUid = Binder.getCallingUid();
5406        final int callingUserId = UserHandle.getUserId(callingUid);
5407        synchronized (mPackages) {
5408            if (canViewInstantApps(callingUid, callingUserId)) {
5409                return new ArrayList<String>(mPackages.keySet());
5410            }
5411            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5412            final List<String> result = new ArrayList<>();
5413            if (instantAppPkgName != null) {
5414                // caller is an instant application; filter unexposed applications
5415                for (PackageParser.Package pkg : mPackages.values()) {
5416                    if (!pkg.visibleToInstantApps) {
5417                        continue;
5418                    }
5419                    result.add(pkg.packageName);
5420                }
5421            } else {
5422                // caller is a normal application; filter instant applications
5423                for (PackageParser.Package pkg : mPackages.values()) {
5424                    final PackageSetting ps =
5425                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5426                    if (ps != null
5427                            && ps.getInstantApp(callingUserId)
5428                            && !mInstantAppRegistry.isInstantAccessGranted(
5429                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5430                        continue;
5431                    }
5432                    result.add(pkg.packageName);
5433                }
5434            }
5435            return result;
5436        }
5437    }
5438
5439    @Override
5440    public String[] getPackagesForUid(int uid) {
5441        final int callingUid = Binder.getCallingUid();
5442        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5443        final int userId = UserHandle.getUserId(uid);
5444        uid = UserHandle.getAppId(uid);
5445        // reader
5446        synchronized (mPackages) {
5447            Object obj = mSettings.getUserIdLPr(uid);
5448            if (obj instanceof SharedUserSetting) {
5449                if (isCallerInstantApp) {
5450                    return null;
5451                }
5452                final SharedUserSetting sus = (SharedUserSetting) obj;
5453                final int N = sus.packages.size();
5454                String[] res = new String[N];
5455                final Iterator<PackageSetting> it = sus.packages.iterator();
5456                int i = 0;
5457                while (it.hasNext()) {
5458                    PackageSetting ps = it.next();
5459                    if (ps.getInstalled(userId)) {
5460                        res[i++] = ps.name;
5461                    } else {
5462                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5463                    }
5464                }
5465                return res;
5466            } else if (obj instanceof PackageSetting) {
5467                final PackageSetting ps = (PackageSetting) obj;
5468                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5469                    return new String[]{ps.name};
5470                }
5471            }
5472        }
5473        return null;
5474    }
5475
5476    @Override
5477    public String getNameForUid(int uid) {
5478        final int callingUid = Binder.getCallingUid();
5479        if (getInstantAppPackageName(callingUid) != null) {
5480            return null;
5481        }
5482        synchronized (mPackages) {
5483            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5484            if (obj instanceof SharedUserSetting) {
5485                final SharedUserSetting sus = (SharedUserSetting) obj;
5486                return sus.name + ":" + sus.userId;
5487            } else if (obj instanceof PackageSetting) {
5488                final PackageSetting ps = (PackageSetting) obj;
5489                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5490                    return null;
5491                }
5492                return ps.name;
5493            }
5494            return null;
5495        }
5496    }
5497
5498    @Override
5499    public String[] getNamesForUids(int[] uids) {
5500        if (uids == null || uids.length == 0) {
5501            return null;
5502        }
5503        final int callingUid = Binder.getCallingUid();
5504        if (getInstantAppPackageName(callingUid) != null) {
5505            return null;
5506        }
5507        final String[] names = new String[uids.length];
5508        synchronized (mPackages) {
5509            for (int i = uids.length - 1; i >= 0; i--) {
5510                final int uid = uids[i];
5511                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5512                if (obj instanceof SharedUserSetting) {
5513                    final SharedUserSetting sus = (SharedUserSetting) obj;
5514                    names[i] = "shared:" + sus.name;
5515                } else if (obj instanceof PackageSetting) {
5516                    final PackageSetting ps = (PackageSetting) obj;
5517                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5518                        names[i] = null;
5519                    } else {
5520                        names[i] = ps.name;
5521                    }
5522                } else {
5523                    names[i] = null;
5524                }
5525            }
5526        }
5527        return names;
5528    }
5529
5530    @Override
5531    public int getUidForSharedUser(String sharedUserName) {
5532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5533            return -1;
5534        }
5535        if (sharedUserName == null) {
5536            return -1;
5537        }
5538        // reader
5539        synchronized (mPackages) {
5540            SharedUserSetting suid;
5541            try {
5542                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5543                if (suid != null) {
5544                    return suid.userId;
5545                }
5546            } catch (PackageManagerException ignore) {
5547                // can't happen, but, still need to catch it
5548            }
5549            return -1;
5550        }
5551    }
5552
5553    @Override
5554    public int getFlagsForUid(int uid) {
5555        final int callingUid = Binder.getCallingUid();
5556        if (getInstantAppPackageName(callingUid) != null) {
5557            return 0;
5558        }
5559        synchronized (mPackages) {
5560            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5561            if (obj instanceof SharedUserSetting) {
5562                final SharedUserSetting sus = (SharedUserSetting) obj;
5563                return sus.pkgFlags;
5564            } else if (obj instanceof PackageSetting) {
5565                final PackageSetting ps = (PackageSetting) obj;
5566                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5567                    return 0;
5568                }
5569                return ps.pkgFlags;
5570            }
5571        }
5572        return 0;
5573    }
5574
5575    @Override
5576    public int getPrivateFlagsForUid(int uid) {
5577        final int callingUid = Binder.getCallingUid();
5578        if (getInstantAppPackageName(callingUid) != null) {
5579            return 0;
5580        }
5581        synchronized (mPackages) {
5582            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5583            if (obj instanceof SharedUserSetting) {
5584                final SharedUserSetting sus = (SharedUserSetting) obj;
5585                return sus.pkgPrivateFlags;
5586            } else if (obj instanceof PackageSetting) {
5587                final PackageSetting ps = (PackageSetting) obj;
5588                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5589                    return 0;
5590                }
5591                return ps.pkgPrivateFlags;
5592            }
5593        }
5594        return 0;
5595    }
5596
5597    @Override
5598    public boolean isUidPrivileged(int uid) {
5599        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5600            return false;
5601        }
5602        uid = UserHandle.getAppId(uid);
5603        // reader
5604        synchronized (mPackages) {
5605            Object obj = mSettings.getUserIdLPr(uid);
5606            if (obj instanceof SharedUserSetting) {
5607                final SharedUserSetting sus = (SharedUserSetting) obj;
5608                final Iterator<PackageSetting> it = sus.packages.iterator();
5609                while (it.hasNext()) {
5610                    if (it.next().isPrivileged()) {
5611                        return true;
5612                    }
5613                }
5614            } else if (obj instanceof PackageSetting) {
5615                final PackageSetting ps = (PackageSetting) obj;
5616                return ps.isPrivileged();
5617            }
5618        }
5619        return false;
5620    }
5621
5622    @Override
5623    public String[] getAppOpPermissionPackages(String permName) {
5624        return mPermissionManager.getAppOpPermissionPackages(permName);
5625    }
5626
5627    @Override
5628    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5629            int flags, int userId) {
5630        return resolveIntentInternal(
5631                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5632    }
5633
5634    /**
5635     * Normally instant apps can only be resolved when they're visible to the caller.
5636     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5637     * since we need to allow the system to start any installed application.
5638     */
5639    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5640            int flags, int userId, boolean resolveForStart) {
5641        try {
5642            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5643
5644            if (!sUserManager.exists(userId)) return null;
5645            final int callingUid = Binder.getCallingUid();
5646            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5647            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5648                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5649
5650            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5651            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5652                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5653            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5654
5655            final ResolveInfo bestChoice =
5656                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5657            return bestChoice;
5658        } finally {
5659            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5660        }
5661    }
5662
5663    @Override
5664    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5665        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5666            throw new SecurityException(
5667                    "findPersistentPreferredActivity can only be run by the system");
5668        }
5669        if (!sUserManager.exists(userId)) {
5670            return null;
5671        }
5672        final int callingUid = Binder.getCallingUid();
5673        intent = updateIntentForResolve(intent);
5674        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5675        final int flags = updateFlagsForResolve(
5676                0, userId, intent, callingUid, false /*includeInstantApps*/);
5677        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5678                userId);
5679        synchronized (mPackages) {
5680            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5681                    userId);
5682        }
5683    }
5684
5685    @Override
5686    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5687            IntentFilter filter, int match, ComponentName activity) {
5688        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5689            return;
5690        }
5691        final int userId = UserHandle.getCallingUserId();
5692        if (DEBUG_PREFERRED) {
5693            Log.v(TAG, "setLastChosenActivity intent=" + intent
5694                + " resolvedType=" + resolvedType
5695                + " flags=" + flags
5696                + " filter=" + filter
5697                + " match=" + match
5698                + " activity=" + activity);
5699            filter.dump(new PrintStreamPrinter(System.out), "    ");
5700        }
5701        intent.setComponent(null);
5702        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5703                userId);
5704        // Find any earlier preferred or last chosen entries and nuke them
5705        findPreferredActivity(intent, resolvedType,
5706                flags, query, 0, false, true, false, userId);
5707        // Add the new activity as the last chosen for this filter
5708        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5709                "Setting last chosen");
5710    }
5711
5712    @Override
5713    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5714        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5715            return null;
5716        }
5717        final int userId = UserHandle.getCallingUserId();
5718        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5719        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5720                userId);
5721        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5722                false, false, false, userId);
5723    }
5724
5725    /**
5726     * Returns whether or not instant apps have been disabled remotely.
5727     */
5728    private boolean isEphemeralDisabled() {
5729        return mEphemeralAppsDisabled;
5730    }
5731
5732    private boolean isInstantAppAllowed(
5733            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5734            boolean skipPackageCheck) {
5735        if (mInstantAppResolverConnection == null) {
5736            return false;
5737        }
5738        if (mInstantAppInstallerActivity == null) {
5739            return false;
5740        }
5741        if (intent.getComponent() != null) {
5742            return false;
5743        }
5744        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5745            return false;
5746        }
5747        if (!skipPackageCheck && intent.getPackage() != null) {
5748            return false;
5749        }
5750        final boolean isWebUri = hasWebURI(intent);
5751        if (!isWebUri || intent.getData().getHost() == null) {
5752            return false;
5753        }
5754        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5755        // Or if there's already an ephemeral app installed that handles the action
5756        synchronized (mPackages) {
5757            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5758            for (int n = 0; n < count; n++) {
5759                final ResolveInfo info = resolvedActivities.get(n);
5760                final String packageName = info.activityInfo.packageName;
5761                final PackageSetting ps = mSettings.mPackages.get(packageName);
5762                if (ps != null) {
5763                    // only check domain verification status if the app is not a browser
5764                    if (!info.handleAllWebDataURI) {
5765                        // Try to get the status from User settings first
5766                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5767                        final int status = (int) (packedStatus >> 32);
5768                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5769                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5770                            if (DEBUG_EPHEMERAL) {
5771                                Slog.v(TAG, "DENY instant app;"
5772                                    + " pkg: " + packageName + ", status: " + status);
5773                            }
5774                            return false;
5775                        }
5776                    }
5777                    if (ps.getInstantApp(userId)) {
5778                        if (DEBUG_EPHEMERAL) {
5779                            Slog.v(TAG, "DENY instant app installed;"
5780                                    + " pkg: " + packageName);
5781                        }
5782                        return false;
5783                    }
5784                }
5785            }
5786        }
5787        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5788        return true;
5789    }
5790
5791    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5792            Intent origIntent, String resolvedType, String callingPackage,
5793            Bundle verificationBundle, int userId) {
5794        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5795                new InstantAppRequest(responseObj, origIntent, resolvedType,
5796                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5797        mHandler.sendMessage(msg);
5798    }
5799
5800    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5801            int flags, List<ResolveInfo> query, int userId) {
5802        if (query != null) {
5803            final int N = query.size();
5804            if (N == 1) {
5805                return query.get(0);
5806            } else if (N > 1) {
5807                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5808                // If there is more than one activity with the same priority,
5809                // then let the user decide between them.
5810                ResolveInfo r0 = query.get(0);
5811                ResolveInfo r1 = query.get(1);
5812                if (DEBUG_INTENT_MATCHING || debug) {
5813                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5814                            + r1.activityInfo.name + "=" + r1.priority);
5815                }
5816                // If the first activity has a higher priority, or a different
5817                // default, then it is always desirable to pick it.
5818                if (r0.priority != r1.priority
5819                        || r0.preferredOrder != r1.preferredOrder
5820                        || r0.isDefault != r1.isDefault) {
5821                    return query.get(0);
5822                }
5823                // If we have saved a preference for a preferred activity for
5824                // this Intent, use that.
5825                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5826                        flags, query, r0.priority, true, false, debug, userId);
5827                if (ri != null) {
5828                    return ri;
5829                }
5830                // If we have an ephemeral app, use it
5831                for (int i = 0; i < N; i++) {
5832                    ri = query.get(i);
5833                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5834                        final String packageName = ri.activityInfo.packageName;
5835                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5836                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5837                        final int status = (int)(packedStatus >> 32);
5838                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5839                            return ri;
5840                        }
5841                    }
5842                }
5843                ri = new ResolveInfo(mResolveInfo);
5844                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5845                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5846                // If all of the options come from the same package, show the application's
5847                // label and icon instead of the generic resolver's.
5848                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5849                // and then throw away the ResolveInfo itself, meaning that the caller loses
5850                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5851                // a fallback for this case; we only set the target package's resources on
5852                // the ResolveInfo, not the ActivityInfo.
5853                final String intentPackage = intent.getPackage();
5854                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5855                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5856                    ri.resolvePackageName = intentPackage;
5857                    if (userNeedsBadging(userId)) {
5858                        ri.noResourceId = true;
5859                    } else {
5860                        ri.icon = appi.icon;
5861                    }
5862                    ri.iconResourceId = appi.icon;
5863                    ri.labelRes = appi.labelRes;
5864                }
5865                ri.activityInfo.applicationInfo = new ApplicationInfo(
5866                        ri.activityInfo.applicationInfo);
5867                if (userId != 0) {
5868                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5869                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5870                }
5871                // Make sure that the resolver is displayable in car mode
5872                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5873                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5874                return ri;
5875            }
5876        }
5877        return null;
5878    }
5879
5880    /**
5881     * Return true if the given list is not empty and all of its contents have
5882     * an activityInfo with the given package name.
5883     */
5884    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5885        if (ArrayUtils.isEmpty(list)) {
5886            return false;
5887        }
5888        for (int i = 0, N = list.size(); i < N; i++) {
5889            final ResolveInfo ri = list.get(i);
5890            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5891            if (ai == null || !packageName.equals(ai.packageName)) {
5892                return false;
5893            }
5894        }
5895        return true;
5896    }
5897
5898    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5899            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5900        final int N = query.size();
5901        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5902                .get(userId);
5903        // Get the list of persistent preferred activities that handle the intent
5904        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5905        List<PersistentPreferredActivity> pprefs = ppir != null
5906                ? ppir.queryIntent(intent, resolvedType,
5907                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5908                        userId)
5909                : null;
5910        if (pprefs != null && pprefs.size() > 0) {
5911            final int M = pprefs.size();
5912            for (int i=0; i<M; i++) {
5913                final PersistentPreferredActivity ppa = pprefs.get(i);
5914                if (DEBUG_PREFERRED || debug) {
5915                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5916                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5917                            + "\n  component=" + ppa.mComponent);
5918                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5919                }
5920                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5921                        flags | MATCH_DISABLED_COMPONENTS, userId);
5922                if (DEBUG_PREFERRED || debug) {
5923                    Slog.v(TAG, "Found persistent preferred activity:");
5924                    if (ai != null) {
5925                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5926                    } else {
5927                        Slog.v(TAG, "  null");
5928                    }
5929                }
5930                if (ai == null) {
5931                    // This previously registered persistent preferred activity
5932                    // component is no longer known. Ignore it and do NOT remove it.
5933                    continue;
5934                }
5935                for (int j=0; j<N; j++) {
5936                    final ResolveInfo ri = query.get(j);
5937                    if (!ri.activityInfo.applicationInfo.packageName
5938                            .equals(ai.applicationInfo.packageName)) {
5939                        continue;
5940                    }
5941                    if (!ri.activityInfo.name.equals(ai.name)) {
5942                        continue;
5943                    }
5944                    //  Found a persistent preference that can handle the intent.
5945                    if (DEBUG_PREFERRED || debug) {
5946                        Slog.v(TAG, "Returning persistent preferred activity: " +
5947                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5948                    }
5949                    return ri;
5950                }
5951            }
5952        }
5953        return null;
5954    }
5955
5956    // TODO: handle preferred activities missing while user has amnesia
5957    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5958            List<ResolveInfo> query, int priority, boolean always,
5959            boolean removeMatches, boolean debug, int userId) {
5960        if (!sUserManager.exists(userId)) return null;
5961        final int callingUid = Binder.getCallingUid();
5962        flags = updateFlagsForResolve(
5963                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5964        intent = updateIntentForResolve(intent);
5965        // writer
5966        synchronized (mPackages) {
5967            // Try to find a matching persistent preferred activity.
5968            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5969                    debug, userId);
5970
5971            // If a persistent preferred activity matched, use it.
5972            if (pri != null) {
5973                return pri;
5974            }
5975
5976            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5977            // Get the list of preferred activities that handle the intent
5978            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5979            List<PreferredActivity> prefs = pir != null
5980                    ? pir.queryIntent(intent, resolvedType,
5981                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5982                            userId)
5983                    : null;
5984            if (prefs != null && prefs.size() > 0) {
5985                boolean changed = false;
5986                try {
5987                    // First figure out how good the original match set is.
5988                    // We will only allow preferred activities that came
5989                    // from the same match quality.
5990                    int match = 0;
5991
5992                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5993
5994                    final int N = query.size();
5995                    for (int j=0; j<N; j++) {
5996                        final ResolveInfo ri = query.get(j);
5997                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5998                                + ": 0x" + Integer.toHexString(match));
5999                        if (ri.match > match) {
6000                            match = ri.match;
6001                        }
6002                    }
6003
6004                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6005                            + Integer.toHexString(match));
6006
6007                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6008                    final int M = prefs.size();
6009                    for (int i=0; i<M; i++) {
6010                        final PreferredActivity pa = prefs.get(i);
6011                        if (DEBUG_PREFERRED || debug) {
6012                            Slog.v(TAG, "Checking PreferredActivity ds="
6013                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6014                                    + "\n  component=" + pa.mPref.mComponent);
6015                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6016                        }
6017                        if (pa.mPref.mMatch != match) {
6018                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6019                                    + Integer.toHexString(pa.mPref.mMatch));
6020                            continue;
6021                        }
6022                        // If it's not an "always" type preferred activity and that's what we're
6023                        // looking for, skip it.
6024                        if (always && !pa.mPref.mAlways) {
6025                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6026                            continue;
6027                        }
6028                        final ActivityInfo ai = getActivityInfo(
6029                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6030                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6031                                userId);
6032                        if (DEBUG_PREFERRED || debug) {
6033                            Slog.v(TAG, "Found preferred activity:");
6034                            if (ai != null) {
6035                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6036                            } else {
6037                                Slog.v(TAG, "  null");
6038                            }
6039                        }
6040                        if (ai == null) {
6041                            // This previously registered preferred activity
6042                            // component is no longer known.  Most likely an update
6043                            // to the app was installed and in the new version this
6044                            // component no longer exists.  Clean it up by removing
6045                            // it from the preferred activities list, and skip it.
6046                            Slog.w(TAG, "Removing dangling preferred activity: "
6047                                    + pa.mPref.mComponent);
6048                            pir.removeFilter(pa);
6049                            changed = true;
6050                            continue;
6051                        }
6052                        for (int j=0; j<N; j++) {
6053                            final ResolveInfo ri = query.get(j);
6054                            if (!ri.activityInfo.applicationInfo.packageName
6055                                    .equals(ai.applicationInfo.packageName)) {
6056                                continue;
6057                            }
6058                            if (!ri.activityInfo.name.equals(ai.name)) {
6059                                continue;
6060                            }
6061
6062                            if (removeMatches) {
6063                                pir.removeFilter(pa);
6064                                changed = true;
6065                                if (DEBUG_PREFERRED) {
6066                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6067                                }
6068                                break;
6069                            }
6070
6071                            // Okay we found a previously set preferred or last chosen app.
6072                            // If the result set is different from when this
6073                            // was created, and is not a subset of the preferred set, we need to
6074                            // clear it and re-ask the user their preference, if we're looking for
6075                            // an "always" type entry.
6076                            if (always && !pa.mPref.sameSet(query)) {
6077                                if (pa.mPref.isSuperset(query)) {
6078                                    // some components of the set are no longer present in
6079                                    // the query, but the preferred activity can still be reused
6080                                    if (DEBUG_PREFERRED) {
6081                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6082                                                + " still valid as only non-preferred components"
6083                                                + " were removed for " + intent + " type "
6084                                                + resolvedType);
6085                                    }
6086                                    // remove obsolete components and re-add the up-to-date filter
6087                                    PreferredActivity freshPa = new PreferredActivity(pa,
6088                                            pa.mPref.mMatch,
6089                                            pa.mPref.discardObsoleteComponents(query),
6090                                            pa.mPref.mComponent,
6091                                            pa.mPref.mAlways);
6092                                    pir.removeFilter(pa);
6093                                    pir.addFilter(freshPa);
6094                                    changed = true;
6095                                } else {
6096                                    Slog.i(TAG,
6097                                            "Result set changed, dropping preferred activity for "
6098                                                    + intent + " type " + resolvedType);
6099                                    if (DEBUG_PREFERRED) {
6100                                        Slog.v(TAG, "Removing preferred activity since set changed "
6101                                                + pa.mPref.mComponent);
6102                                    }
6103                                    pir.removeFilter(pa);
6104                                    // Re-add the filter as a "last chosen" entry (!always)
6105                                    PreferredActivity lastChosen = new PreferredActivity(
6106                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6107                                    pir.addFilter(lastChosen);
6108                                    changed = true;
6109                                    return null;
6110                                }
6111                            }
6112
6113                            // Yay! Either the set matched or we're looking for the last chosen
6114                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6115                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6116                            return ri;
6117                        }
6118                    }
6119                } finally {
6120                    if (changed) {
6121                        if (DEBUG_PREFERRED) {
6122                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6123                        }
6124                        scheduleWritePackageRestrictionsLocked(userId);
6125                    }
6126                }
6127            }
6128        }
6129        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6130        return null;
6131    }
6132
6133    /*
6134     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6135     */
6136    @Override
6137    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6138            int targetUserId) {
6139        mContext.enforceCallingOrSelfPermission(
6140                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6141        List<CrossProfileIntentFilter> matches =
6142                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6143        if (matches != null) {
6144            int size = matches.size();
6145            for (int i = 0; i < size; i++) {
6146                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6147            }
6148        }
6149        if (hasWebURI(intent)) {
6150            // cross-profile app linking works only towards the parent.
6151            final int callingUid = Binder.getCallingUid();
6152            final UserInfo parent = getProfileParent(sourceUserId);
6153            synchronized(mPackages) {
6154                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6155                        false /*includeInstantApps*/);
6156                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6157                        intent, resolvedType, flags, sourceUserId, parent.id);
6158                return xpDomainInfo != null;
6159            }
6160        }
6161        return false;
6162    }
6163
6164    private UserInfo getProfileParent(int userId) {
6165        final long identity = Binder.clearCallingIdentity();
6166        try {
6167            return sUserManager.getProfileParent(userId);
6168        } finally {
6169            Binder.restoreCallingIdentity(identity);
6170        }
6171    }
6172
6173    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6174            String resolvedType, int userId) {
6175        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6176        if (resolver != null) {
6177            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6178        }
6179        return null;
6180    }
6181
6182    @Override
6183    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6184            String resolvedType, int flags, int userId) {
6185        try {
6186            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6187
6188            return new ParceledListSlice<>(
6189                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6190        } finally {
6191            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6192        }
6193    }
6194
6195    /**
6196     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6197     * instant, returns {@code null}.
6198     */
6199    private String getInstantAppPackageName(int callingUid) {
6200        synchronized (mPackages) {
6201            // If the caller is an isolated app use the owner's uid for the lookup.
6202            if (Process.isIsolated(callingUid)) {
6203                callingUid = mIsolatedOwners.get(callingUid);
6204            }
6205            final int appId = UserHandle.getAppId(callingUid);
6206            final Object obj = mSettings.getUserIdLPr(appId);
6207            if (obj instanceof PackageSetting) {
6208                final PackageSetting ps = (PackageSetting) obj;
6209                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6210                return isInstantApp ? ps.pkg.packageName : null;
6211            }
6212        }
6213        return null;
6214    }
6215
6216    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6217            String resolvedType, int flags, int userId) {
6218        return queryIntentActivitiesInternal(
6219                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6220                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6221    }
6222
6223    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6224            String resolvedType, int flags, int filterCallingUid, int userId,
6225            boolean resolveForStart, boolean allowDynamicSplits) {
6226        if (!sUserManager.exists(userId)) return Collections.emptyList();
6227        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6228        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6229                false /* requireFullPermission */, false /* checkShell */,
6230                "query intent activities");
6231        final String pkgName = intent.getPackage();
6232        ComponentName comp = intent.getComponent();
6233        if (comp == null) {
6234            if (intent.getSelector() != null) {
6235                intent = intent.getSelector();
6236                comp = intent.getComponent();
6237            }
6238        }
6239
6240        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6241                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6242        if (comp != null) {
6243            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6244            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6245            if (ai != null) {
6246                // When specifying an explicit component, we prevent the activity from being
6247                // used when either 1) the calling package is normal and the activity is within
6248                // an ephemeral application or 2) the calling package is ephemeral and the
6249                // activity is not visible to ephemeral applications.
6250                final boolean matchInstantApp =
6251                        (flags & PackageManager.MATCH_INSTANT) != 0;
6252                final boolean matchVisibleToInstantAppOnly =
6253                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6254                final boolean matchExplicitlyVisibleOnly =
6255                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6256                final boolean isCallerInstantApp =
6257                        instantAppPkgName != null;
6258                final boolean isTargetSameInstantApp =
6259                        comp.getPackageName().equals(instantAppPkgName);
6260                final boolean isTargetInstantApp =
6261                        (ai.applicationInfo.privateFlags
6262                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6263                final boolean isTargetVisibleToInstantApp =
6264                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6265                final boolean isTargetExplicitlyVisibleToInstantApp =
6266                        isTargetVisibleToInstantApp
6267                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6268                final boolean isTargetHiddenFromInstantApp =
6269                        !isTargetVisibleToInstantApp
6270                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6271                final boolean blockResolution =
6272                        !isTargetSameInstantApp
6273                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6274                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6275                                        && isTargetHiddenFromInstantApp));
6276                if (!blockResolution) {
6277                    final ResolveInfo ri = new ResolveInfo();
6278                    ri.activityInfo = ai;
6279                    list.add(ri);
6280                }
6281            }
6282            return applyPostResolutionFilter(
6283                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6284        }
6285
6286        // reader
6287        boolean sortResult = false;
6288        boolean addEphemeral = false;
6289        List<ResolveInfo> result;
6290        final boolean ephemeralDisabled = isEphemeralDisabled();
6291        synchronized (mPackages) {
6292            if (pkgName == null) {
6293                List<CrossProfileIntentFilter> matchingFilters =
6294                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6295                // Check for results that need to skip the current profile.
6296                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6297                        resolvedType, flags, userId);
6298                if (xpResolveInfo != null) {
6299                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6300                    xpResult.add(xpResolveInfo);
6301                    return applyPostResolutionFilter(
6302                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6303                            allowDynamicSplits, filterCallingUid, userId);
6304                }
6305
6306                // Check for results in the current profile.
6307                result = filterIfNotSystemUser(mActivities.queryIntent(
6308                        intent, resolvedType, flags, userId), userId);
6309                addEphemeral = !ephemeralDisabled
6310                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6311                // Check for cross profile results.
6312                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6313                xpResolveInfo = queryCrossProfileIntents(
6314                        matchingFilters, intent, resolvedType, flags, userId,
6315                        hasNonNegativePriorityResult);
6316                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6317                    boolean isVisibleToUser = filterIfNotSystemUser(
6318                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6319                    if (isVisibleToUser) {
6320                        result.add(xpResolveInfo);
6321                        sortResult = true;
6322                    }
6323                }
6324                if (hasWebURI(intent)) {
6325                    CrossProfileDomainInfo xpDomainInfo = null;
6326                    final UserInfo parent = getProfileParent(userId);
6327                    if (parent != null) {
6328                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6329                                flags, userId, parent.id);
6330                    }
6331                    if (xpDomainInfo != null) {
6332                        if (xpResolveInfo != null) {
6333                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6334                            // in the result.
6335                            result.remove(xpResolveInfo);
6336                        }
6337                        if (result.size() == 0 && !addEphemeral) {
6338                            // No result in current profile, but found candidate in parent user.
6339                            // And we are not going to add emphemeral app, so we can return the
6340                            // result straight away.
6341                            result.add(xpDomainInfo.resolveInfo);
6342                            return applyPostResolutionFilter(result, instantAppPkgName,
6343                                    allowDynamicSplits, filterCallingUid, userId);
6344                        }
6345                    } else if (result.size() <= 1 && !addEphemeral) {
6346                        // No result in parent user and <= 1 result in current profile, and we
6347                        // are not going to add emphemeral app, so we can return the result without
6348                        // further processing.
6349                        return applyPostResolutionFilter(result, instantAppPkgName,
6350                                allowDynamicSplits, filterCallingUid, userId);
6351                    }
6352                    // We have more than one candidate (combining results from current and parent
6353                    // profile), so we need filtering and sorting.
6354                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6355                            intent, flags, result, xpDomainInfo, userId);
6356                    sortResult = true;
6357                }
6358            } else {
6359                final PackageParser.Package pkg = mPackages.get(pkgName);
6360                result = null;
6361                if (pkg != null) {
6362                    result = filterIfNotSystemUser(
6363                            mActivities.queryIntentForPackage(
6364                                    intent, resolvedType, flags, pkg.activities, userId),
6365                            userId);
6366                }
6367                if (result == null || result.size() == 0) {
6368                    // the caller wants to resolve for a particular package; however, there
6369                    // were no installed results, so, try to find an ephemeral result
6370                    addEphemeral = !ephemeralDisabled
6371                            && isInstantAppAllowed(
6372                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6373                    if (result == null) {
6374                        result = new ArrayList<>();
6375                    }
6376                }
6377            }
6378        }
6379        if (addEphemeral) {
6380            result = maybeAddInstantAppInstaller(
6381                    result, intent, resolvedType, flags, userId, resolveForStart);
6382        }
6383        if (sortResult) {
6384            Collections.sort(result, mResolvePrioritySorter);
6385        }
6386        return applyPostResolutionFilter(
6387                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6388    }
6389
6390    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6391            String resolvedType, int flags, int userId, boolean resolveForStart) {
6392        // first, check to see if we've got an instant app already installed
6393        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6394        ResolveInfo localInstantApp = null;
6395        boolean blockResolution = false;
6396        if (!alreadyResolvedLocally) {
6397            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6398                    flags
6399                        | PackageManager.GET_RESOLVED_FILTER
6400                        | PackageManager.MATCH_INSTANT
6401                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6402                    userId);
6403            for (int i = instantApps.size() - 1; i >= 0; --i) {
6404                final ResolveInfo info = instantApps.get(i);
6405                final String packageName = info.activityInfo.packageName;
6406                final PackageSetting ps = mSettings.mPackages.get(packageName);
6407                if (ps.getInstantApp(userId)) {
6408                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6409                    final int status = (int)(packedStatus >> 32);
6410                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6411                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6412                        // there's a local instant application installed, but, the user has
6413                        // chosen to never use it; skip resolution and don't acknowledge
6414                        // an instant application is even available
6415                        if (DEBUG_EPHEMERAL) {
6416                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6417                        }
6418                        blockResolution = true;
6419                        break;
6420                    } else {
6421                        // we have a locally installed instant application; skip resolution
6422                        // but acknowledge there's an instant application available
6423                        if (DEBUG_EPHEMERAL) {
6424                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6425                        }
6426                        localInstantApp = info;
6427                        break;
6428                    }
6429                }
6430            }
6431        }
6432        // no app installed, let's see if one's available
6433        AuxiliaryResolveInfo auxiliaryResponse = null;
6434        if (!blockResolution) {
6435            if (localInstantApp == null) {
6436                // we don't have an instant app locally, resolve externally
6437                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6438                final InstantAppRequest requestObject = new InstantAppRequest(
6439                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6440                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6441                        resolveForStart);
6442                auxiliaryResponse =
6443                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6444                                mContext, mInstantAppResolverConnection, requestObject);
6445                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6446            } else {
6447                // we have an instant application locally, but, we can't admit that since
6448                // callers shouldn't be able to determine prior browsing. create a dummy
6449                // auxiliary response so the downstream code behaves as if there's an
6450                // instant application available externally. when it comes time to start
6451                // the instant application, we'll do the right thing.
6452                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6453                auxiliaryResponse = new AuxiliaryResolveInfo(
6454                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6455                        ai.versionCode, null /*failureIntent*/);
6456            }
6457        }
6458        if (auxiliaryResponse != null) {
6459            if (DEBUG_EPHEMERAL) {
6460                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6461            }
6462            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6463            final PackageSetting ps =
6464                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6465            if (ps != null) {
6466                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6467                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6468                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6469                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6470                // make sure this resolver is the default
6471                ephemeralInstaller.isDefault = true;
6472                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6473                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6474                // add a non-generic filter
6475                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6476                ephemeralInstaller.filter.addDataPath(
6477                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6478                ephemeralInstaller.isInstantAppAvailable = true;
6479                result.add(ephemeralInstaller);
6480            }
6481        }
6482        return result;
6483    }
6484
6485    private static class CrossProfileDomainInfo {
6486        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6487        ResolveInfo resolveInfo;
6488        /* Best domain verification status of the activities found in the other profile */
6489        int bestDomainVerificationStatus;
6490    }
6491
6492    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6493            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6494        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6495                sourceUserId)) {
6496            return null;
6497        }
6498        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6499                resolvedType, flags, parentUserId);
6500
6501        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6502            return null;
6503        }
6504        CrossProfileDomainInfo result = null;
6505        int size = resultTargetUser.size();
6506        for (int i = 0; i < size; i++) {
6507            ResolveInfo riTargetUser = resultTargetUser.get(i);
6508            // Intent filter verification is only for filters that specify a host. So don't return
6509            // those that handle all web uris.
6510            if (riTargetUser.handleAllWebDataURI) {
6511                continue;
6512            }
6513            String packageName = riTargetUser.activityInfo.packageName;
6514            PackageSetting ps = mSettings.mPackages.get(packageName);
6515            if (ps == null) {
6516                continue;
6517            }
6518            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6519            int status = (int)(verificationState >> 32);
6520            if (result == null) {
6521                result = new CrossProfileDomainInfo();
6522                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6523                        sourceUserId, parentUserId);
6524                result.bestDomainVerificationStatus = status;
6525            } else {
6526                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6527                        result.bestDomainVerificationStatus);
6528            }
6529        }
6530        // Don't consider matches with status NEVER across profiles.
6531        if (result != null && result.bestDomainVerificationStatus
6532                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6533            return null;
6534        }
6535        return result;
6536    }
6537
6538    /**
6539     * Verification statuses are ordered from the worse to the best, except for
6540     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6541     */
6542    private int bestDomainVerificationStatus(int status1, int status2) {
6543        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6544            return status2;
6545        }
6546        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6547            return status1;
6548        }
6549        return (int) MathUtils.max(status1, status2);
6550    }
6551
6552    private boolean isUserEnabled(int userId) {
6553        long callingId = Binder.clearCallingIdentity();
6554        try {
6555            UserInfo userInfo = sUserManager.getUserInfo(userId);
6556            return userInfo != null && userInfo.isEnabled();
6557        } finally {
6558            Binder.restoreCallingIdentity(callingId);
6559        }
6560    }
6561
6562    /**
6563     * Filter out activities with systemUserOnly flag set, when current user is not System.
6564     *
6565     * @return filtered list
6566     */
6567    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6568        if (userId == UserHandle.USER_SYSTEM) {
6569            return resolveInfos;
6570        }
6571        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6572            ResolveInfo info = resolveInfos.get(i);
6573            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6574                resolveInfos.remove(i);
6575            }
6576        }
6577        return resolveInfos;
6578    }
6579
6580    /**
6581     * Filters out ephemeral activities.
6582     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6583     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6584     *
6585     * @param resolveInfos The pre-filtered list of resolved activities
6586     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6587     *          is performed.
6588     * @return A filtered list of resolved activities.
6589     */
6590    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6591            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6592        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6593            final ResolveInfo info = resolveInfos.get(i);
6594            // allow activities that are defined in the provided package
6595            if (allowDynamicSplits
6596                    && info.activityInfo.splitName != null
6597                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6598                            info.activityInfo.splitName)) {
6599                if (mInstantAppInstallerInfo == null) {
6600                    if (DEBUG_INSTALL) {
6601                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6602                    }
6603                    resolveInfos.remove(i);
6604                    continue;
6605                }
6606                // requested activity is defined in a split that hasn't been installed yet.
6607                // add the installer to the resolve list
6608                if (DEBUG_INSTALL) {
6609                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6610                }
6611                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6612                final ComponentName installFailureActivity = findInstallFailureActivity(
6613                        info.activityInfo.packageName,  filterCallingUid, userId);
6614                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6615                        info.activityInfo.packageName, info.activityInfo.splitName,
6616                        installFailureActivity,
6617                        info.activityInfo.applicationInfo.versionCode,
6618                        null /*failureIntent*/);
6619                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6620                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6621                // add a non-generic filter
6622                installerInfo.filter = new IntentFilter();
6623
6624                // This resolve info may appear in the chooser UI, so let us make it
6625                // look as the one it replaces as far as the user is concerned which
6626                // requires loading the correct label and icon for the resolve info.
6627                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6628                installerInfo.labelRes = info.resolveLabelResId();
6629                installerInfo.icon = info.resolveIconResId();
6630
6631                // propagate priority/preferred order/default
6632                installerInfo.priority = info.priority;
6633                installerInfo.preferredOrder = info.preferredOrder;
6634                installerInfo.isDefault = info.isDefault;
6635                resolveInfos.set(i, installerInfo);
6636                continue;
6637            }
6638            // caller is a full app, don't need to apply any other filtering
6639            if (ephemeralPkgName == null) {
6640                continue;
6641            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6642                // caller is same app; don't need to apply any other filtering
6643                continue;
6644            }
6645            // allow activities that have been explicitly exposed to ephemeral apps
6646            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6647            if (!isEphemeralApp
6648                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6649                continue;
6650            }
6651            resolveInfos.remove(i);
6652        }
6653        return resolveInfos;
6654    }
6655
6656    /**
6657     * Returns the activity component that can handle install failures.
6658     * <p>By default, the instant application installer handles failures. However, an
6659     * application may want to handle failures on its own. Applications do this by
6660     * creating an activity with an intent filter that handles the action
6661     * {@link Intent#ACTION_INSTALL_FAILURE}.
6662     */
6663    private @Nullable ComponentName findInstallFailureActivity(
6664            String packageName, int filterCallingUid, int userId) {
6665        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6666        failureActivityIntent.setPackage(packageName);
6667        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6668        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6669                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6670                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6671        final int NR = result.size();
6672        if (NR > 0) {
6673            for (int i = 0; i < NR; i++) {
6674                final ResolveInfo info = result.get(i);
6675                if (info.activityInfo.splitName != null) {
6676                    continue;
6677                }
6678                return new ComponentName(packageName, info.activityInfo.name);
6679            }
6680        }
6681        return null;
6682    }
6683
6684    /**
6685     * @param resolveInfos list of resolve infos in descending priority order
6686     * @return if the list contains a resolve info with non-negative priority
6687     */
6688    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6689        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6690    }
6691
6692    private static boolean hasWebURI(Intent intent) {
6693        if (intent.getData() == null) {
6694            return false;
6695        }
6696        final String scheme = intent.getScheme();
6697        if (TextUtils.isEmpty(scheme)) {
6698            return false;
6699        }
6700        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6701    }
6702
6703    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6704            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6705            int userId) {
6706        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6707
6708        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6709            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6710                    candidates.size());
6711        }
6712
6713        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6714        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6715        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6716        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6717        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6718        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6719
6720        synchronized (mPackages) {
6721            final int count = candidates.size();
6722            // First, try to use linked apps. Partition the candidates into four lists:
6723            // one for the final results, one for the "do not use ever", one for "undefined status"
6724            // and finally one for "browser app type".
6725            for (int n=0; n<count; n++) {
6726                ResolveInfo info = candidates.get(n);
6727                String packageName = info.activityInfo.packageName;
6728                PackageSetting ps = mSettings.mPackages.get(packageName);
6729                if (ps != null) {
6730                    // Add to the special match all list (Browser use case)
6731                    if (info.handleAllWebDataURI) {
6732                        matchAllList.add(info);
6733                        continue;
6734                    }
6735                    // Try to get the status from User settings first
6736                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6737                    int status = (int)(packedStatus >> 32);
6738                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6739                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6740                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6741                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6742                                    + " : linkgen=" + linkGeneration);
6743                        }
6744                        // Use link-enabled generation as preferredOrder, i.e.
6745                        // prefer newly-enabled over earlier-enabled.
6746                        info.preferredOrder = linkGeneration;
6747                        alwaysList.add(info);
6748                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6749                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6750                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6751                        }
6752                        neverList.add(info);
6753                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6754                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6755                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6756                        }
6757                        alwaysAskList.add(info);
6758                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6759                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6760                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6761                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6762                        }
6763                        undefinedList.add(info);
6764                    }
6765                }
6766            }
6767
6768            // We'll want to include browser possibilities in a few cases
6769            boolean includeBrowser = false;
6770
6771            // First try to add the "always" resolution(s) for the current user, if any
6772            if (alwaysList.size() > 0) {
6773                result.addAll(alwaysList);
6774            } else {
6775                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6776                result.addAll(undefinedList);
6777                // Maybe add one for the other profile.
6778                if (xpDomainInfo != null && (
6779                        xpDomainInfo.bestDomainVerificationStatus
6780                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6781                    result.add(xpDomainInfo.resolveInfo);
6782                }
6783                includeBrowser = true;
6784            }
6785
6786            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6787            // If there were 'always' entries their preferred order has been set, so we also
6788            // back that off to make the alternatives equivalent
6789            if (alwaysAskList.size() > 0) {
6790                for (ResolveInfo i : result) {
6791                    i.preferredOrder = 0;
6792                }
6793                result.addAll(alwaysAskList);
6794                includeBrowser = true;
6795            }
6796
6797            if (includeBrowser) {
6798                // Also add browsers (all of them or only the default one)
6799                if (DEBUG_DOMAIN_VERIFICATION) {
6800                    Slog.v(TAG, "   ...including browsers in candidate set");
6801                }
6802                if ((matchFlags & MATCH_ALL) != 0) {
6803                    result.addAll(matchAllList);
6804                } else {
6805                    // Browser/generic handling case.  If there's a default browser, go straight
6806                    // to that (but only if there is no other higher-priority match).
6807                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6808                    int maxMatchPrio = 0;
6809                    ResolveInfo defaultBrowserMatch = null;
6810                    final int numCandidates = matchAllList.size();
6811                    for (int n = 0; n < numCandidates; n++) {
6812                        ResolveInfo info = matchAllList.get(n);
6813                        // track the highest overall match priority...
6814                        if (info.priority > maxMatchPrio) {
6815                            maxMatchPrio = info.priority;
6816                        }
6817                        // ...and the highest-priority default browser match
6818                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6819                            if (defaultBrowserMatch == null
6820                                    || (defaultBrowserMatch.priority < info.priority)) {
6821                                if (debug) {
6822                                    Slog.v(TAG, "Considering default browser match " + info);
6823                                }
6824                                defaultBrowserMatch = info;
6825                            }
6826                        }
6827                    }
6828                    if (defaultBrowserMatch != null
6829                            && defaultBrowserMatch.priority >= maxMatchPrio
6830                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6831                    {
6832                        if (debug) {
6833                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6834                        }
6835                        result.add(defaultBrowserMatch);
6836                    } else {
6837                        result.addAll(matchAllList);
6838                    }
6839                }
6840
6841                // If there is nothing selected, add all candidates and remove the ones that the user
6842                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6843                if (result.size() == 0) {
6844                    result.addAll(candidates);
6845                    result.removeAll(neverList);
6846                }
6847            }
6848        }
6849        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6850            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6851                    result.size());
6852            for (ResolveInfo info : result) {
6853                Slog.v(TAG, "  + " + info.activityInfo);
6854            }
6855        }
6856        return result;
6857    }
6858
6859    // Returns a packed value as a long:
6860    //
6861    // high 'int'-sized word: link status: undefined/ask/never/always.
6862    // low 'int'-sized word: relative priority among 'always' results.
6863    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6864        long result = ps.getDomainVerificationStatusForUser(userId);
6865        // if none available, get the master status
6866        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6867            if (ps.getIntentFilterVerificationInfo() != null) {
6868                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6869            }
6870        }
6871        return result;
6872    }
6873
6874    private ResolveInfo querySkipCurrentProfileIntents(
6875            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6876            int flags, int sourceUserId) {
6877        if (matchingFilters != null) {
6878            int size = matchingFilters.size();
6879            for (int i = 0; i < size; i ++) {
6880                CrossProfileIntentFilter filter = matchingFilters.get(i);
6881                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6882                    // Checking if there are activities in the target user that can handle the
6883                    // intent.
6884                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6885                            resolvedType, flags, sourceUserId);
6886                    if (resolveInfo != null) {
6887                        return resolveInfo;
6888                    }
6889                }
6890            }
6891        }
6892        return null;
6893    }
6894
6895    // Return matching ResolveInfo in target user if any.
6896    private ResolveInfo queryCrossProfileIntents(
6897            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6898            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6899        if (matchingFilters != null) {
6900            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6901            // match the same intent. For performance reasons, it is better not to
6902            // run queryIntent twice for the same userId
6903            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6904            int size = matchingFilters.size();
6905            for (int i = 0; i < size; i++) {
6906                CrossProfileIntentFilter filter = matchingFilters.get(i);
6907                int targetUserId = filter.getTargetUserId();
6908                boolean skipCurrentProfile =
6909                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6910                boolean skipCurrentProfileIfNoMatchFound =
6911                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6912                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6913                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6914                    // Checking if there are activities in the target user that can handle the
6915                    // intent.
6916                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6917                            resolvedType, flags, sourceUserId);
6918                    if (resolveInfo != null) return resolveInfo;
6919                    alreadyTriedUserIds.put(targetUserId, true);
6920                }
6921            }
6922        }
6923        return null;
6924    }
6925
6926    /**
6927     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6928     * will forward the intent to the filter's target user.
6929     * Otherwise, returns null.
6930     */
6931    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6932            String resolvedType, int flags, int sourceUserId) {
6933        int targetUserId = filter.getTargetUserId();
6934        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6935                resolvedType, flags, targetUserId);
6936        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6937            // If all the matches in the target profile are suspended, return null.
6938            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6939                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6940                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6941                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6942                            targetUserId);
6943                }
6944            }
6945        }
6946        return null;
6947    }
6948
6949    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6950            int sourceUserId, int targetUserId) {
6951        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6952        long ident = Binder.clearCallingIdentity();
6953        boolean targetIsProfile;
6954        try {
6955            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6956        } finally {
6957            Binder.restoreCallingIdentity(ident);
6958        }
6959        String className;
6960        if (targetIsProfile) {
6961            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6962        } else {
6963            className = FORWARD_INTENT_TO_PARENT;
6964        }
6965        ComponentName forwardingActivityComponentName = new ComponentName(
6966                mAndroidApplication.packageName, className);
6967        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6968                sourceUserId);
6969        if (!targetIsProfile) {
6970            forwardingActivityInfo.showUserIcon = targetUserId;
6971            forwardingResolveInfo.noResourceId = true;
6972        }
6973        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6974        forwardingResolveInfo.priority = 0;
6975        forwardingResolveInfo.preferredOrder = 0;
6976        forwardingResolveInfo.match = 0;
6977        forwardingResolveInfo.isDefault = true;
6978        forwardingResolveInfo.filter = filter;
6979        forwardingResolveInfo.targetUserId = targetUserId;
6980        return forwardingResolveInfo;
6981    }
6982
6983    @Override
6984    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6985            Intent[] specifics, String[] specificTypes, Intent intent,
6986            String resolvedType, int flags, int userId) {
6987        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6988                specificTypes, intent, resolvedType, flags, userId));
6989    }
6990
6991    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6992            Intent[] specifics, String[] specificTypes, Intent intent,
6993            String resolvedType, int flags, int userId) {
6994        if (!sUserManager.exists(userId)) return Collections.emptyList();
6995        final int callingUid = Binder.getCallingUid();
6996        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6997                false /*includeInstantApps*/);
6998        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
6999                false /*requireFullPermission*/, false /*checkShell*/,
7000                "query intent activity options");
7001        final String resultsAction = intent.getAction();
7002
7003        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7004                | PackageManager.GET_RESOLVED_FILTER, userId);
7005
7006        if (DEBUG_INTENT_MATCHING) {
7007            Log.v(TAG, "Query " + intent + ": " + results);
7008        }
7009
7010        int specificsPos = 0;
7011        int N;
7012
7013        // todo: note that the algorithm used here is O(N^2).  This
7014        // isn't a problem in our current environment, but if we start running
7015        // into situations where we have more than 5 or 10 matches then this
7016        // should probably be changed to something smarter...
7017
7018        // First we go through and resolve each of the specific items
7019        // that were supplied, taking care of removing any corresponding
7020        // duplicate items in the generic resolve list.
7021        if (specifics != null) {
7022            for (int i=0; i<specifics.length; i++) {
7023                final Intent sintent = specifics[i];
7024                if (sintent == null) {
7025                    continue;
7026                }
7027
7028                if (DEBUG_INTENT_MATCHING) {
7029                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7030                }
7031
7032                String action = sintent.getAction();
7033                if (resultsAction != null && resultsAction.equals(action)) {
7034                    // If this action was explicitly requested, then don't
7035                    // remove things that have it.
7036                    action = null;
7037                }
7038
7039                ResolveInfo ri = null;
7040                ActivityInfo ai = null;
7041
7042                ComponentName comp = sintent.getComponent();
7043                if (comp == null) {
7044                    ri = resolveIntent(
7045                        sintent,
7046                        specificTypes != null ? specificTypes[i] : null,
7047                            flags, userId);
7048                    if (ri == null) {
7049                        continue;
7050                    }
7051                    if (ri == mResolveInfo) {
7052                        // ACK!  Must do something better with this.
7053                    }
7054                    ai = ri.activityInfo;
7055                    comp = new ComponentName(ai.applicationInfo.packageName,
7056                            ai.name);
7057                } else {
7058                    ai = getActivityInfo(comp, flags, userId);
7059                    if (ai == null) {
7060                        continue;
7061                    }
7062                }
7063
7064                // Look for any generic query activities that are duplicates
7065                // of this specific one, and remove them from the results.
7066                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7067                N = results.size();
7068                int j;
7069                for (j=specificsPos; j<N; j++) {
7070                    ResolveInfo sri = results.get(j);
7071                    if ((sri.activityInfo.name.equals(comp.getClassName())
7072                            && sri.activityInfo.applicationInfo.packageName.equals(
7073                                    comp.getPackageName()))
7074                        || (action != null && sri.filter.matchAction(action))) {
7075                        results.remove(j);
7076                        if (DEBUG_INTENT_MATCHING) Log.v(
7077                            TAG, "Removing duplicate item from " + j
7078                            + " due to specific " + specificsPos);
7079                        if (ri == null) {
7080                            ri = sri;
7081                        }
7082                        j--;
7083                        N--;
7084                    }
7085                }
7086
7087                // Add this specific item to its proper place.
7088                if (ri == null) {
7089                    ri = new ResolveInfo();
7090                    ri.activityInfo = ai;
7091                }
7092                results.add(specificsPos, ri);
7093                ri.specificIndex = i;
7094                specificsPos++;
7095            }
7096        }
7097
7098        // Now we go through the remaining generic results and remove any
7099        // duplicate actions that are found here.
7100        N = results.size();
7101        for (int i=specificsPos; i<N-1; i++) {
7102            final ResolveInfo rii = results.get(i);
7103            if (rii.filter == null) {
7104                continue;
7105            }
7106
7107            // Iterate over all of the actions of this result's intent
7108            // filter...  typically this should be just one.
7109            final Iterator<String> it = rii.filter.actionsIterator();
7110            if (it == null) {
7111                continue;
7112            }
7113            while (it.hasNext()) {
7114                final String action = it.next();
7115                if (resultsAction != null && resultsAction.equals(action)) {
7116                    // If this action was explicitly requested, then don't
7117                    // remove things that have it.
7118                    continue;
7119                }
7120                for (int j=i+1; j<N; j++) {
7121                    final ResolveInfo rij = results.get(j);
7122                    if (rij.filter != null && rij.filter.hasAction(action)) {
7123                        results.remove(j);
7124                        if (DEBUG_INTENT_MATCHING) Log.v(
7125                            TAG, "Removing duplicate item from " + j
7126                            + " due to action " + action + " at " + i);
7127                        j--;
7128                        N--;
7129                    }
7130                }
7131            }
7132
7133            // If the caller didn't request filter information, drop it now
7134            // so we don't have to marshall/unmarshall it.
7135            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7136                rii.filter = null;
7137            }
7138        }
7139
7140        // Filter out the caller activity if so requested.
7141        if (caller != null) {
7142            N = results.size();
7143            for (int i=0; i<N; i++) {
7144                ActivityInfo ainfo = results.get(i).activityInfo;
7145                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7146                        && caller.getClassName().equals(ainfo.name)) {
7147                    results.remove(i);
7148                    break;
7149                }
7150            }
7151        }
7152
7153        // If the caller didn't request filter information,
7154        // drop them now so we don't have to
7155        // marshall/unmarshall it.
7156        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7157            N = results.size();
7158            for (int i=0; i<N; i++) {
7159                results.get(i).filter = null;
7160            }
7161        }
7162
7163        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7164        return results;
7165    }
7166
7167    @Override
7168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7169            String resolvedType, int flags, int userId) {
7170        return new ParceledListSlice<>(
7171                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7172                        false /*allowDynamicSplits*/));
7173    }
7174
7175    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7176            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7177        if (!sUserManager.exists(userId)) return Collections.emptyList();
7178        final int callingUid = Binder.getCallingUid();
7179        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7180                false /*requireFullPermission*/, false /*checkShell*/,
7181                "query intent receivers");
7182        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7183        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7184                false /*includeInstantApps*/);
7185        ComponentName comp = intent.getComponent();
7186        if (comp == null) {
7187            if (intent.getSelector() != null) {
7188                intent = intent.getSelector();
7189                comp = intent.getComponent();
7190            }
7191        }
7192        if (comp != null) {
7193            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7194            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7195            if (ai != null) {
7196                // When specifying an explicit component, we prevent the activity from being
7197                // used when either 1) the calling package is normal and the activity is within
7198                // an instant application or 2) the calling package is ephemeral and the
7199                // activity is not visible to instant applications.
7200                final boolean matchInstantApp =
7201                        (flags & PackageManager.MATCH_INSTANT) != 0;
7202                final boolean matchVisibleToInstantAppOnly =
7203                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7204                final boolean matchExplicitlyVisibleOnly =
7205                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7206                final boolean isCallerInstantApp =
7207                        instantAppPkgName != null;
7208                final boolean isTargetSameInstantApp =
7209                        comp.getPackageName().equals(instantAppPkgName);
7210                final boolean isTargetInstantApp =
7211                        (ai.applicationInfo.privateFlags
7212                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7213                final boolean isTargetVisibleToInstantApp =
7214                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7215                final boolean isTargetExplicitlyVisibleToInstantApp =
7216                        isTargetVisibleToInstantApp
7217                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7218                final boolean isTargetHiddenFromInstantApp =
7219                        !isTargetVisibleToInstantApp
7220                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7221                final boolean blockResolution =
7222                        !isTargetSameInstantApp
7223                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7224                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7225                                        && isTargetHiddenFromInstantApp));
7226                if (!blockResolution) {
7227                    ResolveInfo ri = new ResolveInfo();
7228                    ri.activityInfo = ai;
7229                    list.add(ri);
7230                }
7231            }
7232            return applyPostResolutionFilter(
7233                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7234        }
7235
7236        // reader
7237        synchronized (mPackages) {
7238            String pkgName = intent.getPackage();
7239            if (pkgName == null) {
7240                final List<ResolveInfo> result =
7241                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7242                return applyPostResolutionFilter(
7243                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7244            }
7245            final PackageParser.Package pkg = mPackages.get(pkgName);
7246            if (pkg != null) {
7247                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7248                        intent, resolvedType, flags, pkg.receivers, userId);
7249                return applyPostResolutionFilter(
7250                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7251            }
7252            return Collections.emptyList();
7253        }
7254    }
7255
7256    @Override
7257    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7258        final int callingUid = Binder.getCallingUid();
7259        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7260    }
7261
7262    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7263            int userId, int callingUid) {
7264        if (!sUserManager.exists(userId)) return null;
7265        flags = updateFlagsForResolve(
7266                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7267        List<ResolveInfo> query = queryIntentServicesInternal(
7268                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7269        if (query != null) {
7270            if (query.size() >= 1) {
7271                // If there is more than one service with the same priority,
7272                // just arbitrarily pick the first one.
7273                return query.get(0);
7274            }
7275        }
7276        return null;
7277    }
7278
7279    @Override
7280    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7281            String resolvedType, int flags, int userId) {
7282        final int callingUid = Binder.getCallingUid();
7283        return new ParceledListSlice<>(queryIntentServicesInternal(
7284                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7285    }
7286
7287    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7288            String resolvedType, int flags, int userId, int callingUid,
7289            boolean includeInstantApps) {
7290        if (!sUserManager.exists(userId)) return Collections.emptyList();
7291        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7292                false /*requireFullPermission*/, false /*checkShell*/,
7293                "query intent receivers");
7294        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7295        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7296        ComponentName comp = intent.getComponent();
7297        if (comp == null) {
7298            if (intent.getSelector() != null) {
7299                intent = intent.getSelector();
7300                comp = intent.getComponent();
7301            }
7302        }
7303        if (comp != null) {
7304            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7305            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7306            if (si != null) {
7307                // When specifying an explicit component, we prevent the service from being
7308                // used when either 1) the service is in an instant application and the
7309                // caller is not the same instant application or 2) the calling package is
7310                // ephemeral and the activity is not visible to ephemeral applications.
7311                final boolean matchInstantApp =
7312                        (flags & PackageManager.MATCH_INSTANT) != 0;
7313                final boolean matchVisibleToInstantAppOnly =
7314                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7315                final boolean isCallerInstantApp =
7316                        instantAppPkgName != null;
7317                final boolean isTargetSameInstantApp =
7318                        comp.getPackageName().equals(instantAppPkgName);
7319                final boolean isTargetInstantApp =
7320                        (si.applicationInfo.privateFlags
7321                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7322                final boolean isTargetHiddenFromInstantApp =
7323                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7324                final boolean blockResolution =
7325                        !isTargetSameInstantApp
7326                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7327                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7328                                        && isTargetHiddenFromInstantApp));
7329                if (!blockResolution) {
7330                    final ResolveInfo ri = new ResolveInfo();
7331                    ri.serviceInfo = si;
7332                    list.add(ri);
7333                }
7334            }
7335            return list;
7336        }
7337
7338        // reader
7339        synchronized (mPackages) {
7340            String pkgName = intent.getPackage();
7341            if (pkgName == null) {
7342                return applyPostServiceResolutionFilter(
7343                        mServices.queryIntent(intent, resolvedType, flags, userId),
7344                        instantAppPkgName);
7345            }
7346            final PackageParser.Package pkg = mPackages.get(pkgName);
7347            if (pkg != null) {
7348                return applyPostServiceResolutionFilter(
7349                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7350                                userId),
7351                        instantAppPkgName);
7352            }
7353            return Collections.emptyList();
7354        }
7355    }
7356
7357    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7358            String instantAppPkgName) {
7359        if (instantAppPkgName == null) {
7360            return resolveInfos;
7361        }
7362        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7363            final ResolveInfo info = resolveInfos.get(i);
7364            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7365            // allow services that are defined in the provided package
7366            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7367                if (info.serviceInfo.splitName != null
7368                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7369                                info.serviceInfo.splitName)) {
7370                    // requested service is defined in a split that hasn't been installed yet.
7371                    // add the installer to the resolve list
7372                    if (DEBUG_EPHEMERAL) {
7373                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7374                    }
7375                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7376                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7377                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7378                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7379                            null /*failureIntent*/);
7380                    // make sure this resolver is the default
7381                    installerInfo.isDefault = true;
7382                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7383                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7384                    // add a non-generic filter
7385                    installerInfo.filter = new IntentFilter();
7386                    // load resources from the correct package
7387                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7388                    resolveInfos.set(i, installerInfo);
7389                }
7390                continue;
7391            }
7392            // allow services that have been explicitly exposed to ephemeral apps
7393            if (!isEphemeralApp
7394                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7395                continue;
7396            }
7397            resolveInfos.remove(i);
7398        }
7399        return resolveInfos;
7400    }
7401
7402    @Override
7403    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7404            String resolvedType, int flags, int userId) {
7405        return new ParceledListSlice<>(
7406                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7407    }
7408
7409    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7410            Intent intent, String resolvedType, int flags, int userId) {
7411        if (!sUserManager.exists(userId)) return Collections.emptyList();
7412        final int callingUid = Binder.getCallingUid();
7413        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7414        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7415                false /*includeInstantApps*/);
7416        ComponentName comp = intent.getComponent();
7417        if (comp == null) {
7418            if (intent.getSelector() != null) {
7419                intent = intent.getSelector();
7420                comp = intent.getComponent();
7421            }
7422        }
7423        if (comp != null) {
7424            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7425            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7426            if (pi != null) {
7427                // When specifying an explicit component, we prevent the provider from being
7428                // used when either 1) the provider is in an instant application and the
7429                // caller is not the same instant application or 2) the calling package is an
7430                // instant application and the provider is not visible to instant applications.
7431                final boolean matchInstantApp =
7432                        (flags & PackageManager.MATCH_INSTANT) != 0;
7433                final boolean matchVisibleToInstantAppOnly =
7434                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7435                final boolean isCallerInstantApp =
7436                        instantAppPkgName != null;
7437                final boolean isTargetSameInstantApp =
7438                        comp.getPackageName().equals(instantAppPkgName);
7439                final boolean isTargetInstantApp =
7440                        (pi.applicationInfo.privateFlags
7441                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7442                final boolean isTargetHiddenFromInstantApp =
7443                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7444                final boolean blockResolution =
7445                        !isTargetSameInstantApp
7446                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7447                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7448                                        && isTargetHiddenFromInstantApp));
7449                if (!blockResolution) {
7450                    final ResolveInfo ri = new ResolveInfo();
7451                    ri.providerInfo = pi;
7452                    list.add(ri);
7453                }
7454            }
7455            return list;
7456        }
7457
7458        // reader
7459        synchronized (mPackages) {
7460            String pkgName = intent.getPackage();
7461            if (pkgName == null) {
7462                return applyPostContentProviderResolutionFilter(
7463                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7464                        instantAppPkgName);
7465            }
7466            final PackageParser.Package pkg = mPackages.get(pkgName);
7467            if (pkg != null) {
7468                return applyPostContentProviderResolutionFilter(
7469                        mProviders.queryIntentForPackage(
7470                        intent, resolvedType, flags, pkg.providers, userId),
7471                        instantAppPkgName);
7472            }
7473            return Collections.emptyList();
7474        }
7475    }
7476
7477    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7478            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7479        if (instantAppPkgName == null) {
7480            return resolveInfos;
7481        }
7482        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7483            final ResolveInfo info = resolveInfos.get(i);
7484            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7485            // allow providers that are defined in the provided package
7486            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7487                if (info.providerInfo.splitName != null
7488                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7489                                info.providerInfo.splitName)) {
7490                    // requested provider is defined in a split that hasn't been installed yet.
7491                    // add the installer to the resolve list
7492                    if (DEBUG_EPHEMERAL) {
7493                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7494                    }
7495                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7496                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7497                            info.providerInfo.packageName, info.providerInfo.splitName,
7498                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7499                            null /*failureIntent*/);
7500                    // make sure this resolver is the default
7501                    installerInfo.isDefault = true;
7502                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7503                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7504                    // add a non-generic filter
7505                    installerInfo.filter = new IntentFilter();
7506                    // load resources from the correct package
7507                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7508                    resolveInfos.set(i, installerInfo);
7509                }
7510                continue;
7511            }
7512            // allow providers that have been explicitly exposed to instant applications
7513            if (!isEphemeralApp
7514                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7515                continue;
7516            }
7517            resolveInfos.remove(i);
7518        }
7519        return resolveInfos;
7520    }
7521
7522    @Override
7523    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7524        final int callingUid = Binder.getCallingUid();
7525        if (getInstantAppPackageName(callingUid) != null) {
7526            return ParceledListSlice.emptyList();
7527        }
7528        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7529        flags = updateFlagsForPackage(flags, userId, null);
7530        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7531        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7532                true /* requireFullPermission */, false /* checkShell */,
7533                "get installed packages");
7534
7535        // writer
7536        synchronized (mPackages) {
7537            ArrayList<PackageInfo> list;
7538            if (listUninstalled) {
7539                list = new ArrayList<>(mSettings.mPackages.size());
7540                for (PackageSetting ps : mSettings.mPackages.values()) {
7541                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7542                        continue;
7543                    }
7544                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7545                        continue;
7546                    }
7547                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7548                    if (pi != null) {
7549                        list.add(pi);
7550                    }
7551                }
7552            } else {
7553                list = new ArrayList<>(mPackages.size());
7554                for (PackageParser.Package p : mPackages.values()) {
7555                    final PackageSetting ps = (PackageSetting) p.mExtras;
7556                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7557                        continue;
7558                    }
7559                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7560                        continue;
7561                    }
7562                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7563                            p.mExtras, flags, userId);
7564                    if (pi != null) {
7565                        list.add(pi);
7566                    }
7567                }
7568            }
7569
7570            return new ParceledListSlice<>(list);
7571        }
7572    }
7573
7574    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7575            String[] permissions, boolean[] tmp, int flags, int userId) {
7576        int numMatch = 0;
7577        final PermissionsState permissionsState = ps.getPermissionsState();
7578        for (int i=0; i<permissions.length; i++) {
7579            final String permission = permissions[i];
7580            if (permissionsState.hasPermission(permission, userId)) {
7581                tmp[i] = true;
7582                numMatch++;
7583            } else {
7584                tmp[i] = false;
7585            }
7586        }
7587        if (numMatch == 0) {
7588            return;
7589        }
7590        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7591
7592        // The above might return null in cases of uninstalled apps or install-state
7593        // skew across users/profiles.
7594        if (pi != null) {
7595            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7596                if (numMatch == permissions.length) {
7597                    pi.requestedPermissions = permissions;
7598                } else {
7599                    pi.requestedPermissions = new String[numMatch];
7600                    numMatch = 0;
7601                    for (int i=0; i<permissions.length; i++) {
7602                        if (tmp[i]) {
7603                            pi.requestedPermissions[numMatch] = permissions[i];
7604                            numMatch++;
7605                        }
7606                    }
7607                }
7608            }
7609            list.add(pi);
7610        }
7611    }
7612
7613    @Override
7614    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7615            String[] permissions, int flags, int userId) {
7616        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7617        flags = updateFlagsForPackage(flags, userId, permissions);
7618        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7619                true /* requireFullPermission */, false /* checkShell */,
7620                "get packages holding permissions");
7621        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7622
7623        // writer
7624        synchronized (mPackages) {
7625            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7626            boolean[] tmpBools = new boolean[permissions.length];
7627            if (listUninstalled) {
7628                for (PackageSetting ps : mSettings.mPackages.values()) {
7629                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7630                            userId);
7631                }
7632            } else {
7633                for (PackageParser.Package pkg : mPackages.values()) {
7634                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7635                    if (ps != null) {
7636                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7637                                userId);
7638                    }
7639                }
7640            }
7641
7642            return new ParceledListSlice<PackageInfo>(list);
7643        }
7644    }
7645
7646    @Override
7647    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7648        final int callingUid = Binder.getCallingUid();
7649        if (getInstantAppPackageName(callingUid) != null) {
7650            return ParceledListSlice.emptyList();
7651        }
7652        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7653        flags = updateFlagsForApplication(flags, userId, null);
7654        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7655
7656        // writer
7657        synchronized (mPackages) {
7658            ArrayList<ApplicationInfo> list;
7659            if (listUninstalled) {
7660                list = new ArrayList<>(mSettings.mPackages.size());
7661                for (PackageSetting ps : mSettings.mPackages.values()) {
7662                    ApplicationInfo ai;
7663                    int effectiveFlags = flags;
7664                    if (ps.isSystem()) {
7665                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7666                    }
7667                    if (ps.pkg != null) {
7668                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7669                            continue;
7670                        }
7671                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7672                            continue;
7673                        }
7674                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7675                                ps.readUserState(userId), userId);
7676                        if (ai != null) {
7677                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7678                        }
7679                    } else {
7680                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7681                        // and already converts to externally visible package name
7682                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7683                                callingUid, effectiveFlags, userId);
7684                    }
7685                    if (ai != null) {
7686                        list.add(ai);
7687                    }
7688                }
7689            } else {
7690                list = new ArrayList<>(mPackages.size());
7691                for (PackageParser.Package p : mPackages.values()) {
7692                    if (p.mExtras != null) {
7693                        PackageSetting ps = (PackageSetting) p.mExtras;
7694                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7695                            continue;
7696                        }
7697                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7698                            continue;
7699                        }
7700                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7701                                ps.readUserState(userId), userId);
7702                        if (ai != null) {
7703                            ai.packageName = resolveExternalPackageNameLPr(p);
7704                            list.add(ai);
7705                        }
7706                    }
7707                }
7708            }
7709
7710            return new ParceledListSlice<>(list);
7711        }
7712    }
7713
7714    @Override
7715    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7716        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7717            return null;
7718        }
7719        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7720            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7721                    "getEphemeralApplications");
7722        }
7723        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7724                true /* requireFullPermission */, false /* checkShell */,
7725                "getEphemeralApplications");
7726        synchronized (mPackages) {
7727            List<InstantAppInfo> instantApps = mInstantAppRegistry
7728                    .getInstantAppsLPr(userId);
7729            if (instantApps != null) {
7730                return new ParceledListSlice<>(instantApps);
7731            }
7732        }
7733        return null;
7734    }
7735
7736    @Override
7737    public boolean isInstantApp(String packageName, int userId) {
7738        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7739                true /* requireFullPermission */, false /* checkShell */,
7740                "isInstantApp");
7741        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7742            return false;
7743        }
7744
7745        synchronized (mPackages) {
7746            int callingUid = Binder.getCallingUid();
7747            if (Process.isIsolated(callingUid)) {
7748                callingUid = mIsolatedOwners.get(callingUid);
7749            }
7750            final PackageSetting ps = mSettings.mPackages.get(packageName);
7751            PackageParser.Package pkg = mPackages.get(packageName);
7752            final boolean returnAllowed =
7753                    ps != null
7754                    && (isCallerSameApp(packageName, callingUid)
7755                            || canViewInstantApps(callingUid, userId)
7756                            || mInstantAppRegistry.isInstantAccessGranted(
7757                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7758            if (returnAllowed) {
7759                return ps.getInstantApp(userId);
7760            }
7761        }
7762        return false;
7763    }
7764
7765    @Override
7766    public byte[] getInstantAppCookie(String packageName, int userId) {
7767        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7768            return null;
7769        }
7770
7771        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7772                true /* requireFullPermission */, false /* checkShell */,
7773                "getInstantAppCookie");
7774        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7775            return null;
7776        }
7777        synchronized (mPackages) {
7778            return mInstantAppRegistry.getInstantAppCookieLPw(
7779                    packageName, userId);
7780        }
7781    }
7782
7783    @Override
7784    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7785        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7786            return true;
7787        }
7788
7789        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7790                true /* requireFullPermission */, true /* checkShell */,
7791                "setInstantAppCookie");
7792        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7793            return false;
7794        }
7795        synchronized (mPackages) {
7796            return mInstantAppRegistry.setInstantAppCookieLPw(
7797                    packageName, cookie, userId);
7798        }
7799    }
7800
7801    @Override
7802    public Bitmap getInstantAppIcon(String packageName, int userId) {
7803        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7804            return null;
7805        }
7806
7807        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7808            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7809                    "getInstantAppIcon");
7810        }
7811        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7812                true /* requireFullPermission */, false /* checkShell */,
7813                "getInstantAppIcon");
7814
7815        synchronized (mPackages) {
7816            return mInstantAppRegistry.getInstantAppIconLPw(
7817                    packageName, userId);
7818        }
7819    }
7820
7821    private boolean isCallerSameApp(String packageName, int uid) {
7822        PackageParser.Package pkg = mPackages.get(packageName);
7823        return pkg != null
7824                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7825    }
7826
7827    @Override
7828    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7829        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7830            return ParceledListSlice.emptyList();
7831        }
7832        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7833    }
7834
7835    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7836        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7837
7838        // reader
7839        synchronized (mPackages) {
7840            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7841            final int userId = UserHandle.getCallingUserId();
7842            while (i.hasNext()) {
7843                final PackageParser.Package p = i.next();
7844                if (p.applicationInfo == null) continue;
7845
7846                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7847                        && !p.applicationInfo.isDirectBootAware();
7848                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7849                        && p.applicationInfo.isDirectBootAware();
7850
7851                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7852                        && (!mSafeMode || isSystemApp(p))
7853                        && (matchesUnaware || matchesAware)) {
7854                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7855                    if (ps != null) {
7856                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7857                                ps.readUserState(userId), userId);
7858                        if (ai != null) {
7859                            finalList.add(ai);
7860                        }
7861                    }
7862                }
7863            }
7864        }
7865
7866        return finalList;
7867    }
7868
7869    @Override
7870    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7871        return resolveContentProviderInternal(name, flags, userId);
7872    }
7873
7874    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7875        if (!sUserManager.exists(userId)) return null;
7876        flags = updateFlagsForComponent(flags, userId, name);
7877        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7878        // reader
7879        synchronized (mPackages) {
7880            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7881            PackageSetting ps = provider != null
7882                    ? mSettings.mPackages.get(provider.owner.packageName)
7883                    : null;
7884            if (ps != null) {
7885                final boolean isInstantApp = ps.getInstantApp(userId);
7886                // normal application; filter out instant application provider
7887                if (instantAppPkgName == null && isInstantApp) {
7888                    return null;
7889                }
7890                // instant application; filter out other instant applications
7891                if (instantAppPkgName != null
7892                        && isInstantApp
7893                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7894                    return null;
7895                }
7896                // instant application; filter out non-exposed provider
7897                if (instantAppPkgName != null
7898                        && !isInstantApp
7899                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7900                    return null;
7901                }
7902                // provider not enabled
7903                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7904                    return null;
7905                }
7906                return PackageParser.generateProviderInfo(
7907                        provider, flags, ps.readUserState(userId), userId);
7908            }
7909            return null;
7910        }
7911    }
7912
7913    /**
7914     * @deprecated
7915     */
7916    @Deprecated
7917    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7918        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7919            return;
7920        }
7921        // reader
7922        synchronized (mPackages) {
7923            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7924                    .entrySet().iterator();
7925            final int userId = UserHandle.getCallingUserId();
7926            while (i.hasNext()) {
7927                Map.Entry<String, PackageParser.Provider> entry = i.next();
7928                PackageParser.Provider p = entry.getValue();
7929                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7930
7931                if (ps != null && p.syncable
7932                        && (!mSafeMode || (p.info.applicationInfo.flags
7933                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7934                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7935                            ps.readUserState(userId), userId);
7936                    if (info != null) {
7937                        outNames.add(entry.getKey());
7938                        outInfo.add(info);
7939                    }
7940                }
7941            }
7942        }
7943    }
7944
7945    @Override
7946    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7947            int uid, int flags, String metaDataKey) {
7948        final int callingUid = Binder.getCallingUid();
7949        final int userId = processName != null ? UserHandle.getUserId(uid)
7950                : UserHandle.getCallingUserId();
7951        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7952        flags = updateFlagsForComponent(flags, userId, processName);
7953        ArrayList<ProviderInfo> finalList = null;
7954        // reader
7955        synchronized (mPackages) {
7956            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7957            while (i.hasNext()) {
7958                final PackageParser.Provider p = i.next();
7959                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7960                if (ps != null && p.info.authority != null
7961                        && (processName == null
7962                                || (p.info.processName.equals(processName)
7963                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7964                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7965
7966                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7967                    // parameter.
7968                    if (metaDataKey != null
7969                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7970                        continue;
7971                    }
7972                    final ComponentName component =
7973                            new ComponentName(p.info.packageName, p.info.name);
7974                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
7975                        continue;
7976                    }
7977                    if (finalList == null) {
7978                        finalList = new ArrayList<ProviderInfo>(3);
7979                    }
7980                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7981                            ps.readUserState(userId), userId);
7982                    if (info != null) {
7983                        finalList.add(info);
7984                    }
7985                }
7986            }
7987        }
7988
7989        if (finalList != null) {
7990            Collections.sort(finalList, mProviderInitOrderSorter);
7991            return new ParceledListSlice<ProviderInfo>(finalList);
7992        }
7993
7994        return ParceledListSlice.emptyList();
7995    }
7996
7997    @Override
7998    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
7999        // reader
8000        synchronized (mPackages) {
8001            final int callingUid = Binder.getCallingUid();
8002            final int callingUserId = UserHandle.getUserId(callingUid);
8003            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8004            if (ps == null) return null;
8005            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8006                return null;
8007            }
8008            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8009            return PackageParser.generateInstrumentationInfo(i, flags);
8010        }
8011    }
8012
8013    @Override
8014    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8015            String targetPackage, int flags) {
8016        final int callingUid = Binder.getCallingUid();
8017        final int callingUserId = UserHandle.getUserId(callingUid);
8018        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8019        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8020            return ParceledListSlice.emptyList();
8021        }
8022        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8023    }
8024
8025    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8026            int flags) {
8027        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8028
8029        // reader
8030        synchronized (mPackages) {
8031            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8032            while (i.hasNext()) {
8033                final PackageParser.Instrumentation p = i.next();
8034                if (targetPackage == null
8035                        || targetPackage.equals(p.info.targetPackage)) {
8036                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8037                            flags);
8038                    if (ii != null) {
8039                        finalList.add(ii);
8040                    }
8041                }
8042            }
8043        }
8044
8045        return finalList;
8046    }
8047
8048    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8049        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8050        try {
8051            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8052        } finally {
8053            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8054        }
8055    }
8056
8057    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8058        final File[] files = dir.listFiles();
8059        if (ArrayUtils.isEmpty(files)) {
8060            Log.d(TAG, "No files in app dir " + dir);
8061            return;
8062        }
8063
8064        if (DEBUG_PACKAGE_SCANNING) {
8065            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8066                    + " flags=0x" + Integer.toHexString(parseFlags));
8067        }
8068        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8069                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8070                mParallelPackageParserCallback)) {
8071            // Submit files for parsing in parallel
8072            int fileCount = 0;
8073            for (File file : files) {
8074                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8075                        && !PackageInstallerService.isStageName(file.getName());
8076                if (!isPackage) {
8077                    // Ignore entries which are not packages
8078                    continue;
8079                }
8080                parallelPackageParser.submit(file, parseFlags);
8081                fileCount++;
8082            }
8083
8084            // Process results one by one
8085            for (; fileCount > 0; fileCount--) {
8086                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8087                Throwable throwable = parseResult.throwable;
8088                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8089
8090                if (throwable == null) {
8091                    // Static shared libraries have synthetic package names
8092                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8093                        renameStaticSharedLibraryPackage(parseResult.pkg);
8094                    }
8095                    try {
8096                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8097                            scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8098                                    currentTime, null);
8099                        }
8100                    } catch (PackageManagerException e) {
8101                        errorCode = e.error;
8102                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8103                    }
8104                } else if (throwable instanceof PackageParser.PackageParserException) {
8105                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8106                            throwable;
8107                    errorCode = e.error;
8108                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8109                } else {
8110                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8111                            + parseResult.scanFile, throwable);
8112                }
8113
8114                // Delete invalid userdata apps
8115                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8116                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8117                    logCriticalInfo(Log.WARN,
8118                            "Deleting invalid package at " + parseResult.scanFile);
8119                    removeCodePathLI(parseResult.scanFile);
8120                }
8121            }
8122        }
8123    }
8124
8125    public static void reportSettingsProblem(int priority, String msg) {
8126        logCriticalInfo(priority, msg);
8127    }
8128
8129    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8130            final @ParseFlags int parseFlags) throws PackageManagerException {
8131        // When upgrading from pre-N MR1, verify the package time stamp using the package
8132        // directory and not the APK file.
8133        final long lastModifiedTime = mIsPreNMR1Upgrade
8134                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8135        if (ps != null
8136                && ps.codePath.equals(srcFile)
8137                && ps.timeStamp == lastModifiedTime
8138                && !isCompatSignatureUpdateNeeded(pkg)
8139                && !isRecoverSignatureUpdateNeeded(pkg)) {
8140            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8141            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8142            ArraySet<PublicKey> signingKs;
8143            synchronized (mPackages) {
8144                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8145            }
8146            if (ps.signatures.mSignatures != null
8147                    && ps.signatures.mSignatures.length != 0
8148                    && signingKs != null) {
8149                // Optimization: reuse the existing cached certificates
8150                // if the package appears to be unchanged.
8151                pkg.mSignatures = ps.signatures.mSignatures;
8152                pkg.mSigningKeys = signingKs;
8153                return;
8154            }
8155
8156            Slog.w(TAG, "PackageSetting for " + ps.name
8157                    + " is missing signatures.  Collecting certs again to recover them.");
8158        } else {
8159            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8160        }
8161
8162        try {
8163            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8164            PackageParser.collectCertificates(pkg, parseFlags);
8165        } catch (PackageParserException e) {
8166            throw PackageManagerException.from(e);
8167        } finally {
8168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8169        }
8170    }
8171
8172    /**
8173     *  Traces a package scan.
8174     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8175     */
8176    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8177            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8178        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8179        try {
8180            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8181        } finally {
8182            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8183        }
8184    }
8185
8186    /**
8187     *  Scans a package and returns the newly parsed package.
8188     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8189     */
8190    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8191            long currentTime, UserHandle user) throws PackageManagerException {
8192        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8193        PackageParser pp = new PackageParser();
8194        pp.setSeparateProcesses(mSeparateProcesses);
8195        pp.setOnlyCoreApps(mOnlyCore);
8196        pp.setDisplayMetrics(mMetrics);
8197        pp.setCallback(mPackageParserCallback);
8198
8199        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8200        final PackageParser.Package pkg;
8201        try {
8202            pkg = pp.parsePackage(scanFile, parseFlags);
8203        } catch (PackageParserException e) {
8204            throw PackageManagerException.from(e);
8205        } finally {
8206            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8207        }
8208
8209        // Static shared libraries have synthetic package names
8210        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8211            renameStaticSharedLibraryPackage(pkg);
8212        }
8213
8214        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8215    }
8216
8217    /**
8218     *  Scans a package and returns the newly parsed package.
8219     *  @throws PackageManagerException on a parse error.
8220     */
8221    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8222            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8223            @Nullable UserHandle user)
8224                    throws PackageManagerException {
8225        // If the package has children and this is the first dive in the function
8226        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8227        // packages (parent and children) would be successfully scanned before the
8228        // actual scan since scanning mutates internal state and we want to atomically
8229        // install the package and its children.
8230        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8231            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8232                scanFlags |= SCAN_CHECK_ONLY;
8233            }
8234        } else {
8235            scanFlags &= ~SCAN_CHECK_ONLY;
8236        }
8237
8238        // Scan the parent
8239        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
8240                scanFlags, currentTime, user);
8241
8242        // Scan the children
8243        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8244        for (int i = 0; i < childCount; i++) {
8245            PackageParser.Package childPackage = pkg.childPackages.get(i);
8246            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
8247                    currentTime, user);
8248        }
8249
8250
8251        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8252            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8253        }
8254
8255        return scannedPkg;
8256    }
8257
8258    /**
8259     *  Scans a package and returns the newly parsed package.
8260     *  @throws PackageManagerException on a parse error.
8261     */
8262    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8263            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8264            @Nullable UserHandle user)
8265                    throws PackageManagerException {
8266        PackageSetting ps = null;
8267        PackageSetting updatedPkg;
8268        // reader
8269        synchronized (mPackages) {
8270            // Look to see if we already know about this package.
8271            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8272            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8273                // This package has been renamed to its original name.  Let's
8274                // use that.
8275                ps = mSettings.getPackageLPr(oldName);
8276            }
8277            // If there was no original package, see one for the real package name.
8278            if (ps == null) {
8279                ps = mSettings.getPackageLPr(pkg.packageName);
8280            }
8281            // Check to see if this package could be hiding/updating a system
8282            // package.  Must look for it either under the original or real
8283            // package name depending on our state.
8284            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8285            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8286
8287            // If this is a package we don't know about on the system partition, we
8288            // may need to remove disabled child packages on the system partition
8289            // or may need to not add child packages if the parent apk is updated
8290            // on the data partition and no longer defines this child package.
8291            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8292                // If this is a parent package for an updated system app and this system
8293                // app got an OTA update which no longer defines some of the child packages
8294                // we have to prune them from the disabled system packages.
8295                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8296                if (disabledPs != null) {
8297                    final int scannedChildCount = (pkg.childPackages != null)
8298                            ? pkg.childPackages.size() : 0;
8299                    final int disabledChildCount = disabledPs.childPackageNames != null
8300                            ? disabledPs.childPackageNames.size() : 0;
8301                    for (int i = 0; i < disabledChildCount; i++) {
8302                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8303                        boolean disabledPackageAvailable = false;
8304                        for (int j = 0; j < scannedChildCount; j++) {
8305                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8306                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8307                                disabledPackageAvailable = true;
8308                                break;
8309                            }
8310                         }
8311                         if (!disabledPackageAvailable) {
8312                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8313                         }
8314                    }
8315                }
8316            }
8317        }
8318
8319        final boolean isUpdatedPkg = updatedPkg != null;
8320        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8321        boolean isUpdatedPkgBetter = false;
8322        // First check if this is a system package that may involve an update
8323        if (isUpdatedSystemPkg) {
8324            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8325            // it needs to drop FLAG_PRIVILEGED.
8326            if (locationIsPrivileged(scanFile)) {
8327                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8328            } else {
8329                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8330            }
8331            // If new package is not located in "/oem" (e.g. due to an OTA),
8332            // it needs to drop FLAG_OEM.
8333            if (locationIsOem(scanFile)) {
8334                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8335            } else {
8336                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8337            }
8338
8339            if (ps != null && !ps.codePath.equals(scanFile)) {
8340                // The path has changed from what was last scanned...  check the
8341                // version of the new path against what we have stored to determine
8342                // what to do.
8343                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8344                if (pkg.mVersionCode <= ps.versionCode) {
8345                    // The system package has been updated and the code path does not match
8346                    // Ignore entry. Skip it.
8347                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8348                            + " ignored: updated version " + ps.versionCode
8349                            + " better than this " + pkg.mVersionCode);
8350                    if (!updatedPkg.codePath.equals(scanFile)) {
8351                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8352                                + ps.name + " changing from " + updatedPkg.codePathString
8353                                + " to " + scanFile);
8354                        updatedPkg.codePath = scanFile;
8355                        updatedPkg.codePathString = scanFile.toString();
8356                        updatedPkg.resourcePath = scanFile;
8357                        updatedPkg.resourcePathString = scanFile.toString();
8358                    }
8359                    updatedPkg.pkg = pkg;
8360                    updatedPkg.versionCode = pkg.mVersionCode;
8361
8362                    // Update the disabled system child packages to point to the package too.
8363                    final int childCount = updatedPkg.childPackageNames != null
8364                            ? updatedPkg.childPackageNames.size() : 0;
8365                    for (int i = 0; i < childCount; i++) {
8366                        String childPackageName = updatedPkg.childPackageNames.get(i);
8367                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8368                                childPackageName);
8369                        if (updatedChildPkg != null) {
8370                            updatedChildPkg.pkg = pkg;
8371                            updatedChildPkg.versionCode = pkg.mVersionCode;
8372                        }
8373                    }
8374                } else {
8375                    // The current app on the system partition is better than
8376                    // what we have updated to on the data partition; switch
8377                    // back to the system partition version.
8378                    // At this point, its safely assumed that package installation for
8379                    // apps in system partition will go through. If not there won't be a working
8380                    // version of the app
8381                    // writer
8382                    synchronized (mPackages) {
8383                        // Just remove the loaded entries from package lists.
8384                        mPackages.remove(ps.name);
8385                    }
8386
8387                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8388                            + " reverting from " + ps.codePathString
8389                            + ": new version " + pkg.mVersionCode
8390                            + " better than installed " + ps.versionCode);
8391
8392                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8393                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8394                    synchronized (mInstallLock) {
8395                        args.cleanUpResourcesLI();
8396                    }
8397                    synchronized (mPackages) {
8398                        mSettings.enableSystemPackageLPw(ps.name);
8399                    }
8400                    isUpdatedPkgBetter = true;
8401                }
8402            }
8403        }
8404
8405        String resourcePath = null;
8406        String baseResourcePath = null;
8407        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8408            if (ps != null && ps.resourcePathString != null) {
8409                resourcePath = ps.resourcePathString;
8410                baseResourcePath = ps.resourcePathString;
8411            } else {
8412                // Should not happen at all. Just log an error.
8413                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8414            }
8415        } else {
8416            resourcePath = pkg.codePath;
8417            baseResourcePath = pkg.baseCodePath;
8418        }
8419
8420        // Set application objects path explicitly.
8421        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8422        pkg.setApplicationInfoCodePath(pkg.codePath);
8423        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8424        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8425        pkg.setApplicationInfoResourcePath(resourcePath);
8426        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8427        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8428
8429        // throw an exception if we have an update to a system application, but, it's not more
8430        // recent than the package we've already scanned
8431        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8432            // Set CPU Abis to application info.
8433            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8434                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8435                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8436            } else {
8437                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8438                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8439            }
8440            pkg.mExtras = updatedPkg;
8441
8442            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8443                    + scanFile + " ignored: updated version " + ps.versionCode
8444                    + " better than this " + pkg.mVersionCode);
8445        }
8446
8447        if (isUpdatedPkg) {
8448            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8449            scanFlags |= SCAN_AS_SYSTEM;
8450
8451            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8452            // flag set initially
8453            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8454                scanFlags |= SCAN_AS_PRIVILEGED;
8455            }
8456
8457            // An updated OEM app will not have the PARSE_IS_OEM
8458            // flag set initially
8459            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8460                scanFlags |= SCAN_AS_OEM;
8461            }
8462        }
8463
8464        // Verify certificates against what was last scanned
8465        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
8466
8467        /*
8468         * A new system app appeared, but we already had a non-system one of the
8469         * same name installed earlier.
8470         */
8471        boolean shouldHideSystemApp = false;
8472        if (!isUpdatedPkg && ps != null
8473                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8474            /*
8475             * Check to make sure the signatures match first. If they don't,
8476             * wipe the installed application and its data.
8477             */
8478            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8479                    != PackageManager.SIGNATURE_MATCH) {
8480                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8481                        + " signatures don't match existing userdata copy; removing");
8482                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8483                        "scanPackageInternalLI")) {
8484                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8485                }
8486                ps = null;
8487            } else {
8488                /*
8489                 * If the newly-added system app is an older version than the
8490                 * already installed version, hide it. It will be scanned later
8491                 * and re-added like an update.
8492                 */
8493                if (pkg.mVersionCode <= ps.versionCode) {
8494                    shouldHideSystemApp = true;
8495                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8496                            + " but new version " + pkg.mVersionCode + " better than installed "
8497                            + ps.versionCode + "; hiding system");
8498                } else {
8499                    /*
8500                     * The newly found system app is a newer version that the
8501                     * one previously installed. Simply remove the
8502                     * already-installed application and replace it with our own
8503                     * while keeping the application data.
8504                     */
8505                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8506                            + " reverting from " + ps.codePathString + ": new version "
8507                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8508                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8509                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8510                    synchronized (mInstallLock) {
8511                        args.cleanUpResourcesLI();
8512                    }
8513                }
8514            }
8515        }
8516
8517        // The apk is forward locked (not public) if its code and resources
8518        // are kept in different files. (except for app in either system or
8519        // vendor path).
8520        // TODO grab this value from PackageSettings
8521        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8522            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8523                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
8524            }
8525        }
8526
8527        final int userId = ((user == null) ? 0 : user.getIdentifier());
8528        if (ps != null && ps.getInstantApp(userId)) {
8529            scanFlags |= SCAN_AS_INSTANT_APP;
8530        }
8531        if (ps != null && ps.getVirtulalPreload(userId)) {
8532            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8533        }
8534
8535        // Note that we invoke the following method only if we are about to unpack an application
8536        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
8537                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8538
8539        /*
8540         * If the system app should be overridden by a previously installed
8541         * data, hide the system app now and let the /data/app scan pick it up
8542         * again.
8543         */
8544        if (shouldHideSystemApp) {
8545            synchronized (mPackages) {
8546                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8547            }
8548        }
8549
8550        return scannedPkg;
8551    }
8552
8553    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8554        // Derive the new package synthetic package name
8555        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8556                + pkg.staticSharedLibVersion);
8557    }
8558
8559    private static String fixProcessName(String defProcessName,
8560            String processName) {
8561        if (processName == null) {
8562            return defProcessName;
8563        }
8564        return processName;
8565    }
8566
8567    /**
8568     * Enforces that only the system UID or root's UID can call a method exposed
8569     * via Binder.
8570     *
8571     * @param message used as message if SecurityException is thrown
8572     * @throws SecurityException if the caller is not system or root
8573     */
8574    private static final void enforceSystemOrRoot(String message) {
8575        final int uid = Binder.getCallingUid();
8576        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8577            throw new SecurityException(message);
8578        }
8579    }
8580
8581    @Override
8582    public void performFstrimIfNeeded() {
8583        enforceSystemOrRoot("Only the system can request fstrim");
8584
8585        // Before everything else, see whether we need to fstrim.
8586        try {
8587            IStorageManager sm = PackageHelper.getStorageManager();
8588            if (sm != null) {
8589                boolean doTrim = false;
8590                final long interval = android.provider.Settings.Global.getLong(
8591                        mContext.getContentResolver(),
8592                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8593                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8594                if (interval > 0) {
8595                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8596                    if (timeSinceLast > interval) {
8597                        doTrim = true;
8598                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8599                                + "; running immediately");
8600                    }
8601                }
8602                if (doTrim) {
8603                    final boolean dexOptDialogShown;
8604                    synchronized (mPackages) {
8605                        dexOptDialogShown = mDexOptDialogShown;
8606                    }
8607                    if (!isFirstBoot() && dexOptDialogShown) {
8608                        try {
8609                            ActivityManager.getService().showBootMessage(
8610                                    mContext.getResources().getString(
8611                                            R.string.android_upgrading_fstrim), true);
8612                        } catch (RemoteException e) {
8613                        }
8614                    }
8615                    sm.runMaintenance();
8616                }
8617            } else {
8618                Slog.e(TAG, "storageManager service unavailable!");
8619            }
8620        } catch (RemoteException e) {
8621            // Can't happen; StorageManagerService is local
8622        }
8623    }
8624
8625    @Override
8626    public void updatePackagesIfNeeded() {
8627        enforceSystemOrRoot("Only the system can request package update");
8628
8629        // We need to re-extract after an OTA.
8630        boolean causeUpgrade = isUpgrade();
8631
8632        // First boot or factory reset.
8633        // Note: we also handle devices that are upgrading to N right now as if it is their
8634        //       first boot, as they do not have profile data.
8635        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8636
8637        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8638        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8639
8640        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8641            return;
8642        }
8643
8644        List<PackageParser.Package> pkgs;
8645        synchronized (mPackages) {
8646            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8647        }
8648
8649        final long startTime = System.nanoTime();
8650        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8651                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8652                    false /* bootComplete */);
8653
8654        final int elapsedTimeSeconds =
8655                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8656
8657        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8658        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8659        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8660        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8661        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8662    }
8663
8664    /*
8665     * Return the prebuilt profile path given a package base code path.
8666     */
8667    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8668        return pkg.baseCodePath + ".prof";
8669    }
8670
8671    /**
8672     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8673     * containing statistics about the invocation. The array consists of three elements,
8674     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8675     * and {@code numberOfPackagesFailed}.
8676     */
8677    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8678            final String compilerFilter, boolean bootComplete) {
8679
8680        int numberOfPackagesVisited = 0;
8681        int numberOfPackagesOptimized = 0;
8682        int numberOfPackagesSkipped = 0;
8683        int numberOfPackagesFailed = 0;
8684        final int numberOfPackagesToDexopt = pkgs.size();
8685
8686        for (PackageParser.Package pkg : pkgs) {
8687            numberOfPackagesVisited++;
8688
8689            boolean useProfileForDexopt = false;
8690
8691            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8692                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8693                // that are already compiled.
8694                File profileFile = new File(getPrebuildProfilePath(pkg));
8695                // Copy profile if it exists.
8696                if (profileFile.exists()) {
8697                    try {
8698                        // We could also do this lazily before calling dexopt in
8699                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8700                        // is that we don't have a good way to say "do this only once".
8701                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8702                                pkg.applicationInfo.uid, pkg.packageName)) {
8703                            Log.e(TAG, "Installer failed to copy system profile!");
8704                        } else {
8705                            // Disabled as this causes speed-profile compilation during first boot
8706                            // even if things are already compiled.
8707                            // useProfileForDexopt = true;
8708                        }
8709                    } catch (Exception e) {
8710                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8711                                e);
8712                    }
8713                } else {
8714                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8715                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8716                    // minimize the number off apps being speed-profile compiled during first boot.
8717                    // The other paths will not change the filter.
8718                    if (disabledPs != null && disabledPs.pkg.isStub) {
8719                        // The package is the stub one, remove the stub suffix to get the normal
8720                        // package and APK names.
8721                        String systemProfilePath =
8722                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8723                        profileFile = new File(systemProfilePath);
8724                        // If we have a profile for a compressed APK, copy it to the reference
8725                        // location.
8726                        // Note that copying the profile here will cause it to override the
8727                        // reference profile every OTA even though the existing reference profile
8728                        // may have more data. We can't copy during decompression since the
8729                        // directories are not set up at that point.
8730                        if (profileFile.exists()) {
8731                            try {
8732                                // We could also do this lazily before calling dexopt in
8733                                // PackageDexOptimizer to prevent this happening on first boot. The
8734                                // issue is that we don't have a good way to say "do this only
8735                                // once".
8736                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8737                                        pkg.applicationInfo.uid, pkg.packageName)) {
8738                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8739                                } else {
8740                                    useProfileForDexopt = true;
8741                                }
8742                            } catch (Exception e) {
8743                                Log.e(TAG, "Failed to copy profile " +
8744                                        profileFile.getAbsolutePath() + " ", e);
8745                            }
8746                        }
8747                    }
8748                }
8749            }
8750
8751            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8752                if (DEBUG_DEXOPT) {
8753                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8754                }
8755                numberOfPackagesSkipped++;
8756                continue;
8757            }
8758
8759            if (DEBUG_DEXOPT) {
8760                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8761                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8762            }
8763
8764            if (showDialog) {
8765                try {
8766                    ActivityManager.getService().showBootMessage(
8767                            mContext.getResources().getString(R.string.android_upgrading_apk,
8768                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8769                } catch (RemoteException e) {
8770                }
8771                synchronized (mPackages) {
8772                    mDexOptDialogShown = true;
8773                }
8774            }
8775
8776            String pkgCompilerFilter = compilerFilter;
8777            if (useProfileForDexopt) {
8778                // Use background dexopt mode to try and use the profile. Note that this does not
8779                // guarantee usage of the profile.
8780                pkgCompilerFilter =
8781                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8782                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8783            }
8784
8785            // checkProfiles is false to avoid merging profiles during boot which
8786            // might interfere with background compilation (b/28612421).
8787            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8788            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8789            // trade-off worth doing to save boot time work.
8790            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8791            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8792                    pkg.packageName,
8793                    pkgCompilerFilter,
8794                    dexoptFlags));
8795
8796            switch (primaryDexOptStaus) {
8797                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8798                    numberOfPackagesOptimized++;
8799                    break;
8800                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8801                    numberOfPackagesSkipped++;
8802                    break;
8803                case PackageDexOptimizer.DEX_OPT_FAILED:
8804                    numberOfPackagesFailed++;
8805                    break;
8806                default:
8807                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8808                    break;
8809            }
8810        }
8811
8812        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8813                numberOfPackagesFailed };
8814    }
8815
8816    @Override
8817    public void notifyPackageUse(String packageName, int reason) {
8818        synchronized (mPackages) {
8819            final int callingUid = Binder.getCallingUid();
8820            final int callingUserId = UserHandle.getUserId(callingUid);
8821            if (getInstantAppPackageName(callingUid) != null) {
8822                if (!isCallerSameApp(packageName, callingUid)) {
8823                    return;
8824                }
8825            } else {
8826                if (isInstantApp(packageName, callingUserId)) {
8827                    return;
8828                }
8829            }
8830            notifyPackageUseLocked(packageName, reason);
8831        }
8832    }
8833
8834    private void notifyPackageUseLocked(String packageName, int reason) {
8835        final PackageParser.Package p = mPackages.get(packageName);
8836        if (p == null) {
8837            return;
8838        }
8839        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8840    }
8841
8842    @Override
8843    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8844            List<String> classPaths, String loaderIsa) {
8845        int userId = UserHandle.getCallingUserId();
8846        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8847        if (ai == null) {
8848            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8849                + loadingPackageName + ", user=" + userId);
8850            return;
8851        }
8852        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8853    }
8854
8855    @Override
8856    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8857            IDexModuleRegisterCallback callback) {
8858        int userId = UserHandle.getCallingUserId();
8859        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8860        DexManager.RegisterDexModuleResult result;
8861        if (ai == null) {
8862            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8863                     " calling user. package=" + packageName + ", user=" + userId);
8864            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8865        } else {
8866            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8867        }
8868
8869        if (callback != null) {
8870            mHandler.post(() -> {
8871                try {
8872                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8873                } catch (RemoteException e) {
8874                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8875                }
8876            });
8877        }
8878    }
8879
8880    /**
8881     * Ask the package manager to perform a dex-opt with the given compiler filter.
8882     *
8883     * Note: exposed only for the shell command to allow moving packages explicitly to a
8884     *       definite state.
8885     */
8886    @Override
8887    public boolean performDexOptMode(String packageName,
8888            boolean checkProfiles, String targetCompilerFilter, boolean force,
8889            boolean bootComplete, String splitName) {
8890        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8891                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8892                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8893        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8894                splitName, flags));
8895    }
8896
8897    /**
8898     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8899     * secondary dex files belonging to the given package.
8900     *
8901     * Note: exposed only for the shell command to allow moving packages explicitly to a
8902     *       definite state.
8903     */
8904    @Override
8905    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8906            boolean force) {
8907        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8908                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8909                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8910                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8911        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8912    }
8913
8914    /*package*/ boolean performDexOpt(DexoptOptions options) {
8915        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8916            return false;
8917        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8918            return false;
8919        }
8920
8921        if (options.isDexoptOnlySecondaryDex()) {
8922            return mDexManager.dexoptSecondaryDex(options);
8923        } else {
8924            int dexoptStatus = performDexOptWithStatus(options);
8925            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8926        }
8927    }
8928
8929    /**
8930     * Perform dexopt on the given package and return one of following result:
8931     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8932     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8933     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8934     */
8935    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8936        return performDexOptTraced(options);
8937    }
8938
8939    private int performDexOptTraced(DexoptOptions options) {
8940        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8941        try {
8942            return performDexOptInternal(options);
8943        } finally {
8944            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8945        }
8946    }
8947
8948    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8949    // if the package can now be considered up to date for the given filter.
8950    private int performDexOptInternal(DexoptOptions options) {
8951        PackageParser.Package p;
8952        synchronized (mPackages) {
8953            p = mPackages.get(options.getPackageName());
8954            if (p == null) {
8955                // Package could not be found. Report failure.
8956                return PackageDexOptimizer.DEX_OPT_FAILED;
8957            }
8958            mPackageUsage.maybeWriteAsync(mPackages);
8959            mCompilerStats.maybeWriteAsync();
8960        }
8961        long callingId = Binder.clearCallingIdentity();
8962        try {
8963            synchronized (mInstallLock) {
8964                return performDexOptInternalWithDependenciesLI(p, options);
8965            }
8966        } finally {
8967            Binder.restoreCallingIdentity(callingId);
8968        }
8969    }
8970
8971    public ArraySet<String> getOptimizablePackages() {
8972        ArraySet<String> pkgs = new ArraySet<String>();
8973        synchronized (mPackages) {
8974            for (PackageParser.Package p : mPackages.values()) {
8975                if (PackageDexOptimizer.canOptimizePackage(p)) {
8976                    pkgs.add(p.packageName);
8977                }
8978            }
8979        }
8980        return pkgs;
8981    }
8982
8983    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8984            DexoptOptions options) {
8985        // Select the dex optimizer based on the force parameter.
8986        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8987        //       allocate an object here.
8988        PackageDexOptimizer pdo = options.isForce()
8989                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8990                : mPackageDexOptimizer;
8991
8992        // Dexopt all dependencies first. Note: we ignore the return value and march on
8993        // on errors.
8994        // Note that we are going to call performDexOpt on those libraries as many times as
8995        // they are referenced in packages. When we do a batch of performDexOpt (for example
8996        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8997        // and the first package that uses the library will dexopt it. The
8998        // others will see that the compiled code for the library is up to date.
8999        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9000        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9001        if (!deps.isEmpty()) {
9002            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9003                    options.getCompilerFilter(), options.getSplitName(),
9004                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9005            for (PackageParser.Package depPackage : deps) {
9006                // TODO: Analyze and investigate if we (should) profile libraries.
9007                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9008                        getOrCreateCompilerPackageStats(depPackage),
9009                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9010            }
9011        }
9012        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9013                getOrCreateCompilerPackageStats(p),
9014                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9015    }
9016
9017    /**
9018     * Reconcile the information we have about the secondary dex files belonging to
9019     * {@code packagName} and the actual dex files. For all dex files that were
9020     * deleted, update the internal records and delete the generated oat files.
9021     */
9022    @Override
9023    public void reconcileSecondaryDexFiles(String packageName) {
9024        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9025            return;
9026        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9027            return;
9028        }
9029        mDexManager.reconcileSecondaryDexFiles(packageName);
9030    }
9031
9032    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9033    // a reference there.
9034    /*package*/ DexManager getDexManager() {
9035        return mDexManager;
9036    }
9037
9038    /**
9039     * Execute the background dexopt job immediately.
9040     */
9041    @Override
9042    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9043        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9044            return false;
9045        }
9046        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9047    }
9048
9049    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9050        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9051                || p.usesStaticLibraries != null) {
9052            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9053            Set<String> collectedNames = new HashSet<>();
9054            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9055
9056            retValue.remove(p);
9057
9058            return retValue;
9059        } else {
9060            return Collections.emptyList();
9061        }
9062    }
9063
9064    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9065            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9066        if (!collectedNames.contains(p.packageName)) {
9067            collectedNames.add(p.packageName);
9068            collected.add(p);
9069
9070            if (p.usesLibraries != null) {
9071                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9072                        null, collected, collectedNames);
9073            }
9074            if (p.usesOptionalLibraries != null) {
9075                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9076                        null, collected, collectedNames);
9077            }
9078            if (p.usesStaticLibraries != null) {
9079                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9080                        p.usesStaticLibrariesVersions, collected, collectedNames);
9081            }
9082        }
9083    }
9084
9085    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9086            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9087        final int libNameCount = libs.size();
9088        for (int i = 0; i < libNameCount; i++) {
9089            String libName = libs.get(i);
9090            int version = (versions != null && versions.length == libNameCount)
9091                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9092            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9093            if (libPkg != null) {
9094                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9095            }
9096        }
9097    }
9098
9099    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9100        synchronized (mPackages) {
9101            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9102            if (libEntry != null) {
9103                return mPackages.get(libEntry.apk);
9104            }
9105            return null;
9106        }
9107    }
9108
9109    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9110        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9111        if (versionedLib == null) {
9112            return null;
9113        }
9114        return versionedLib.get(version);
9115    }
9116
9117    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9118        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9119                pkg.staticSharedLibName);
9120        if (versionedLib == null) {
9121            return null;
9122        }
9123        int previousLibVersion = -1;
9124        final int versionCount = versionedLib.size();
9125        for (int i = 0; i < versionCount; i++) {
9126            final int libVersion = versionedLib.keyAt(i);
9127            if (libVersion < pkg.staticSharedLibVersion) {
9128                previousLibVersion = Math.max(previousLibVersion, libVersion);
9129            }
9130        }
9131        if (previousLibVersion >= 0) {
9132            return versionedLib.get(previousLibVersion);
9133        }
9134        return null;
9135    }
9136
9137    public void shutdown() {
9138        mPackageUsage.writeNow(mPackages);
9139        mCompilerStats.writeNow();
9140        mDexManager.writePackageDexUsageNow();
9141    }
9142
9143    @Override
9144    public void dumpProfiles(String packageName) {
9145        PackageParser.Package pkg;
9146        synchronized (mPackages) {
9147            pkg = mPackages.get(packageName);
9148            if (pkg == null) {
9149                throw new IllegalArgumentException("Unknown package: " + packageName);
9150            }
9151        }
9152        /* Only the shell, root, or the app user should be able to dump profiles. */
9153        int callingUid = Binder.getCallingUid();
9154        if (callingUid != Process.SHELL_UID &&
9155            callingUid != Process.ROOT_UID &&
9156            callingUid != pkg.applicationInfo.uid) {
9157            throw new SecurityException("dumpProfiles");
9158        }
9159
9160        synchronized (mInstallLock) {
9161            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9162            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9163            try {
9164                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9165                String codePaths = TextUtils.join(";", allCodePaths);
9166                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9167            } catch (InstallerException e) {
9168                Slog.w(TAG, "Failed to dump profiles", e);
9169            }
9170            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9171        }
9172    }
9173
9174    @Override
9175    public void forceDexOpt(String packageName) {
9176        enforceSystemOrRoot("forceDexOpt");
9177
9178        PackageParser.Package pkg;
9179        synchronized (mPackages) {
9180            pkg = mPackages.get(packageName);
9181            if (pkg == null) {
9182                throw new IllegalArgumentException("Unknown package: " + packageName);
9183            }
9184        }
9185
9186        synchronized (mInstallLock) {
9187            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9188
9189            // Whoever is calling forceDexOpt wants a compiled package.
9190            // Don't use profiles since that may cause compilation to be skipped.
9191            final int res = performDexOptInternalWithDependenciesLI(
9192                    pkg,
9193                    new DexoptOptions(packageName,
9194                            getDefaultCompilerFilter(),
9195                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9196
9197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9198            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9199                throw new IllegalStateException("Failed to dexopt: " + res);
9200            }
9201        }
9202    }
9203
9204    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9205        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9206            Slog.w(TAG, "Unable to update from " + oldPkg.name
9207                    + " to " + newPkg.packageName
9208                    + ": old package not in system partition");
9209            return false;
9210        } else if (mPackages.get(oldPkg.name) != null) {
9211            Slog.w(TAG, "Unable to update from " + oldPkg.name
9212                    + " to " + newPkg.packageName
9213                    + ": old package still exists");
9214            return false;
9215        }
9216        return true;
9217    }
9218
9219    void removeCodePathLI(File codePath) {
9220        if (codePath.isDirectory()) {
9221            try {
9222                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9223            } catch (InstallerException e) {
9224                Slog.w(TAG, "Failed to remove code path", e);
9225            }
9226        } else {
9227            codePath.delete();
9228        }
9229    }
9230
9231    private int[] resolveUserIds(int userId) {
9232        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9233    }
9234
9235    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9236        if (pkg == null) {
9237            Slog.wtf(TAG, "Package was null!", new Throwable());
9238            return;
9239        }
9240        clearAppDataLeafLIF(pkg, userId, flags);
9241        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9242        for (int i = 0; i < childCount; i++) {
9243            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9244        }
9245    }
9246
9247    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9248        final PackageSetting ps;
9249        synchronized (mPackages) {
9250            ps = mSettings.mPackages.get(pkg.packageName);
9251        }
9252        for (int realUserId : resolveUserIds(userId)) {
9253            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9254            try {
9255                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9256                        ceDataInode);
9257            } catch (InstallerException e) {
9258                Slog.w(TAG, String.valueOf(e));
9259            }
9260        }
9261    }
9262
9263    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9264        if (pkg == null) {
9265            Slog.wtf(TAG, "Package was null!", new Throwable());
9266            return;
9267        }
9268        destroyAppDataLeafLIF(pkg, userId, flags);
9269        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9270        for (int i = 0; i < childCount; i++) {
9271            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9272        }
9273    }
9274
9275    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9276        final PackageSetting ps;
9277        synchronized (mPackages) {
9278            ps = mSettings.mPackages.get(pkg.packageName);
9279        }
9280        for (int realUserId : resolveUserIds(userId)) {
9281            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9282            try {
9283                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9284                        ceDataInode);
9285            } catch (InstallerException e) {
9286                Slog.w(TAG, String.valueOf(e));
9287            }
9288            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9289        }
9290    }
9291
9292    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9293        if (pkg == null) {
9294            Slog.wtf(TAG, "Package was null!", new Throwable());
9295            return;
9296        }
9297        destroyAppProfilesLeafLIF(pkg);
9298        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9299        for (int i = 0; i < childCount; i++) {
9300            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9301        }
9302    }
9303
9304    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9305        try {
9306            mInstaller.destroyAppProfiles(pkg.packageName);
9307        } catch (InstallerException e) {
9308            Slog.w(TAG, String.valueOf(e));
9309        }
9310    }
9311
9312    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9313        if (pkg == null) {
9314            Slog.wtf(TAG, "Package was null!", new Throwable());
9315            return;
9316        }
9317        clearAppProfilesLeafLIF(pkg);
9318        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9319        for (int i = 0; i < childCount; i++) {
9320            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9321        }
9322    }
9323
9324    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9325        try {
9326            mInstaller.clearAppProfiles(pkg.packageName);
9327        } catch (InstallerException e) {
9328            Slog.w(TAG, String.valueOf(e));
9329        }
9330    }
9331
9332    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9333            long lastUpdateTime) {
9334        // Set parent install/update time
9335        PackageSetting ps = (PackageSetting) pkg.mExtras;
9336        if (ps != null) {
9337            ps.firstInstallTime = firstInstallTime;
9338            ps.lastUpdateTime = lastUpdateTime;
9339        }
9340        // Set children install/update time
9341        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9342        for (int i = 0; i < childCount; i++) {
9343            PackageParser.Package childPkg = pkg.childPackages.get(i);
9344            ps = (PackageSetting) childPkg.mExtras;
9345            if (ps != null) {
9346                ps.firstInstallTime = firstInstallTime;
9347                ps.lastUpdateTime = lastUpdateTime;
9348            }
9349        }
9350    }
9351
9352    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9353            SharedLibraryEntry file,
9354            PackageParser.Package changingLib) {
9355        if (file.path != null) {
9356            usesLibraryFiles.add(file.path);
9357            return;
9358        }
9359        PackageParser.Package p = mPackages.get(file.apk);
9360        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9361            // If we are doing this while in the middle of updating a library apk,
9362            // then we need to make sure to use that new apk for determining the
9363            // dependencies here.  (We haven't yet finished committing the new apk
9364            // to the package manager state.)
9365            if (p == null || p.packageName.equals(changingLib.packageName)) {
9366                p = changingLib;
9367            }
9368        }
9369        if (p != null) {
9370            usesLibraryFiles.addAll(p.getAllCodePaths());
9371            if (p.usesLibraryFiles != null) {
9372                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9373            }
9374        }
9375    }
9376
9377    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9378            PackageParser.Package changingLib) throws PackageManagerException {
9379        if (pkg == null) {
9380            return;
9381        }
9382        // The collection used here must maintain the order of addition (so
9383        // that libraries are searched in the correct order) and must have no
9384        // duplicates.
9385        Set<String> usesLibraryFiles = null;
9386        if (pkg.usesLibraries != null) {
9387            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9388                    null, null, pkg.packageName, changingLib, true,
9389                    pkg.applicationInfo.targetSdkVersion, null);
9390        }
9391        if (pkg.usesStaticLibraries != null) {
9392            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9393                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9394                    pkg.packageName, changingLib, true,
9395                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9396        }
9397        if (pkg.usesOptionalLibraries != null) {
9398            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9399                    null, null, pkg.packageName, changingLib, false,
9400                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9401        }
9402        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9403            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9404        } else {
9405            pkg.usesLibraryFiles = null;
9406        }
9407    }
9408
9409    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9410            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9411            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9412            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9413            throws PackageManagerException {
9414        final int libCount = requestedLibraries.size();
9415        for (int i = 0; i < libCount; i++) {
9416            final String libName = requestedLibraries.get(i);
9417            final int libVersion = requiredVersions != null ? requiredVersions[i]
9418                    : SharedLibraryInfo.VERSION_UNDEFINED;
9419            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9420            if (libEntry == null) {
9421                if (required) {
9422                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9423                            "Package " + packageName + " requires unavailable shared library "
9424                                    + libName + "; failing!");
9425                } else if (DEBUG_SHARED_LIBRARIES) {
9426                    Slog.i(TAG, "Package " + packageName
9427                            + " desires unavailable shared library "
9428                            + libName + "; ignoring!");
9429                }
9430            } else {
9431                if (requiredVersions != null && requiredCertDigests != null) {
9432                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9433                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9434                            "Package " + packageName + " requires unavailable static shared"
9435                                    + " library " + libName + " version "
9436                                    + libEntry.info.getVersion() + "; failing!");
9437                    }
9438
9439                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9440                    if (libPkg == null) {
9441                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9442                                "Package " + packageName + " requires unavailable static shared"
9443                                        + " library; failing!");
9444                    }
9445
9446                    final String[] expectedCertDigests = requiredCertDigests[i];
9447                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9448                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9449                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9450                            : PackageUtils.computeSignaturesSha256Digests(
9451                                    new Signature[]{libPkg.mSignatures[0]});
9452
9453                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9454                    // target O we don't parse the "additional-certificate" tags similarly
9455                    // how we only consider all certs only for apps targeting O (see above).
9456                    // Therefore, the size check is safe to make.
9457                    if (expectedCertDigests.length != libCertDigests.length) {
9458                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9459                                "Package " + packageName + " requires differently signed" +
9460                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9461                    }
9462
9463                    // Use a predictable order as signature order may vary
9464                    Arrays.sort(libCertDigests);
9465                    Arrays.sort(expectedCertDigests);
9466
9467                    final int certCount = libCertDigests.length;
9468                    for (int j = 0; j < certCount; j++) {
9469                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9470                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9471                                    "Package " + packageName + " requires differently signed" +
9472                                            " static shared library; failing!");
9473                        }
9474                    }
9475                }
9476
9477                if (outUsedLibraries == null) {
9478                    // Use LinkedHashSet to preserve the order of files added to
9479                    // usesLibraryFiles while eliminating duplicates.
9480                    outUsedLibraries = new LinkedHashSet<>();
9481                }
9482                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9483            }
9484        }
9485        return outUsedLibraries;
9486    }
9487
9488    private static boolean hasString(List<String> list, List<String> which) {
9489        if (list == null) {
9490            return false;
9491        }
9492        for (int i=list.size()-1; i>=0; i--) {
9493            for (int j=which.size()-1; j>=0; j--) {
9494                if (which.get(j).equals(list.get(i))) {
9495                    return true;
9496                }
9497            }
9498        }
9499        return false;
9500    }
9501
9502    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9503            PackageParser.Package changingPkg) {
9504        ArrayList<PackageParser.Package> res = null;
9505        for (PackageParser.Package pkg : mPackages.values()) {
9506            if (changingPkg != null
9507                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9508                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9509                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9510                            changingPkg.staticSharedLibName)) {
9511                return null;
9512            }
9513            if (res == null) {
9514                res = new ArrayList<>();
9515            }
9516            res.add(pkg);
9517            try {
9518                updateSharedLibrariesLPr(pkg, changingPkg);
9519            } catch (PackageManagerException e) {
9520                // If a system app update or an app and a required lib missing we
9521                // delete the package and for updated system apps keep the data as
9522                // it is better for the user to reinstall than to be in an limbo
9523                // state. Also libs disappearing under an app should never happen
9524                // - just in case.
9525                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9526                    final int flags = pkg.isUpdatedSystemApp()
9527                            ? PackageManager.DELETE_KEEP_DATA : 0;
9528                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9529                            flags , null, true, null);
9530                }
9531                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9532            }
9533        }
9534        return res;
9535    }
9536
9537    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9538            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9539            @Nullable UserHandle user) throws PackageManagerException {
9540        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9541        // If the package has children and this is the first dive in the function
9542        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9543        // whether all packages (parent and children) would be successfully scanned
9544        // before the actual scan since scanning mutates internal state and we want
9545        // to atomically install the package and its children.
9546        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9547            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9548                scanFlags |= SCAN_CHECK_ONLY;
9549            }
9550        } else {
9551            scanFlags &= ~SCAN_CHECK_ONLY;
9552        }
9553
9554        final PackageParser.Package scannedPkg;
9555        try {
9556            // Scan the parent
9557            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
9558            // Scan the children
9559            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9560            for (int i = 0; i < childCount; i++) {
9561                PackageParser.Package childPkg = pkg.childPackages.get(i);
9562                scanPackageLI(childPkg, parseFlags,
9563                        scanFlags, currentTime, user);
9564            }
9565        } finally {
9566            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9567        }
9568
9569        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9570            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9571        }
9572
9573        return scannedPkg;
9574    }
9575
9576    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
9577            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9578            @Nullable UserHandle user) throws PackageManagerException {
9579        boolean success = false;
9580        try {
9581            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
9582                    currentTime, user);
9583            success = true;
9584            return res;
9585        } finally {
9586            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9587                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9588                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9589                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9590                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9591            }
9592        }
9593    }
9594
9595    /**
9596     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9597     */
9598    private static boolean apkHasCode(String fileName) {
9599        StrictJarFile jarFile = null;
9600        try {
9601            jarFile = new StrictJarFile(fileName,
9602                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9603            return jarFile.findEntry("classes.dex") != null;
9604        } catch (IOException ignore) {
9605        } finally {
9606            try {
9607                if (jarFile != null) {
9608                    jarFile.close();
9609                }
9610            } catch (IOException ignore) {}
9611        }
9612        return false;
9613    }
9614
9615    /**
9616     * Enforces code policy for the package. This ensures that if an APK has
9617     * declared hasCode="true" in its manifest that the APK actually contains
9618     * code.
9619     *
9620     * @throws PackageManagerException If bytecode could not be found when it should exist
9621     */
9622    private static void assertCodePolicy(PackageParser.Package pkg)
9623            throws PackageManagerException {
9624        final boolean shouldHaveCode =
9625                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9626        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9627            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9628                    "Package " + pkg.baseCodePath + " code is missing");
9629        }
9630
9631        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9632            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9633                final boolean splitShouldHaveCode =
9634                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9635                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9636                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9637                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9638                }
9639            }
9640        }
9641    }
9642
9643    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9644            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9645            @Nullable UserHandle user)
9646                    throws PackageManagerException {
9647        if (DEBUG_PACKAGE_SCANNING) {
9648            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9649                Log.d(TAG, "Scanning package " + pkg.packageName);
9650        }
9651
9652        applyPolicy(pkg, parseFlags, scanFlags);
9653
9654        assertPackageIsValid(pkg, parseFlags, scanFlags);
9655
9656        if (Build.IS_DEBUGGABLE &&
9657                pkg.isPrivileged() &&
9658                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
9659            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9660        }
9661
9662        // Initialize package source and resource directories
9663        final File scanFile = new File(pkg.codePath);
9664        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9665        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9666
9667        SharedUserSetting suid = null;
9668        PackageSetting pkgSetting = null;
9669
9670        // Getting the package setting may have a side-effect, so if we
9671        // are only checking if scan would succeed, stash a copy of the
9672        // old setting to restore at the end.
9673        PackageSetting nonMutatedPs = null;
9674
9675        // We keep references to the derived CPU Abis from settings in oder to reuse
9676        // them in the case where we're not upgrading or booting for the first time.
9677        String primaryCpuAbiFromSettings = null;
9678        String secondaryCpuAbiFromSettings = null;
9679
9680        // writer
9681        synchronized (mPackages) {
9682            if (pkg.mSharedUserId != null) {
9683                // SIDE EFFECTS; may potentially allocate a new shared user
9684                suid = mSettings.getSharedUserLPw(
9685                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9686                if (DEBUG_PACKAGE_SCANNING) {
9687                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9688                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9689                                + "): packages=" + suid.packages);
9690                }
9691            }
9692
9693            // Check if we are renaming from an original package name.
9694            PackageSetting origPackage = null;
9695            String realName = null;
9696            if (pkg.mOriginalPackages != null) {
9697                // This package may need to be renamed to a previously
9698                // installed name.  Let's check on that...
9699                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9700                if (pkg.mOriginalPackages.contains(renamed)) {
9701                    // This package had originally been installed as the
9702                    // original name, and we have already taken care of
9703                    // transitioning to the new one.  Just update the new
9704                    // one to continue using the old name.
9705                    realName = pkg.mRealPackage;
9706                    if (!pkg.packageName.equals(renamed)) {
9707                        // Callers into this function may have already taken
9708                        // care of renaming the package; only do it here if
9709                        // it is not already done.
9710                        pkg.setPackageName(renamed);
9711                    }
9712                } else {
9713                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9714                        if ((origPackage = mSettings.getPackageLPr(
9715                                pkg.mOriginalPackages.get(i))) != null) {
9716                            // We do have the package already installed under its
9717                            // original name...  should we use it?
9718                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9719                                // New package is not compatible with original.
9720                                origPackage = null;
9721                                continue;
9722                            } else if (origPackage.sharedUser != null) {
9723                                // Make sure uid is compatible between packages.
9724                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9725                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9726                                            + " to " + pkg.packageName + ": old uid "
9727                                            + origPackage.sharedUser.name
9728                                            + " differs from " + pkg.mSharedUserId);
9729                                    origPackage = null;
9730                                    continue;
9731                                }
9732                                // TODO: Add case when shared user id is added [b/28144775]
9733                            } else {
9734                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9735                                        + pkg.packageName + " to old name " + origPackage.name);
9736                            }
9737                            break;
9738                        }
9739                    }
9740                }
9741            }
9742
9743            if (mTransferedPackages.contains(pkg.packageName)) {
9744                Slog.w(TAG, "Package " + pkg.packageName
9745                        + " was transferred to another, but its .apk remains");
9746            }
9747
9748            // See comments in nonMutatedPs declaration
9749            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9750                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9751                if (foundPs != null) {
9752                    nonMutatedPs = new PackageSetting(foundPs);
9753                }
9754            }
9755
9756            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9757                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9758                if (foundPs != null) {
9759                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9760                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9761                }
9762            }
9763
9764            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9765            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9766                PackageManagerService.reportSettingsProblem(Log.WARN,
9767                        "Package " + pkg.packageName + " shared user changed from "
9768                                + (pkgSetting.sharedUser != null
9769                                        ? pkgSetting.sharedUser.name : "<nothing>")
9770                                + " to "
9771                                + (suid != null ? suid.name : "<nothing>")
9772                                + "; replacing with new");
9773                pkgSetting = null;
9774            }
9775            final PackageSetting oldPkgSetting =
9776                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9777            final PackageSetting disabledPkgSetting =
9778                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9779
9780            String[] usesStaticLibraries = null;
9781            if (pkg.usesStaticLibraries != null) {
9782                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9783                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9784            }
9785
9786            if (pkgSetting == null) {
9787                final String parentPackageName = (pkg.parentPackage != null)
9788                        ? pkg.parentPackage.packageName : null;
9789                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9790                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
9791                // REMOVE SharedUserSetting from method; update in a separate call
9792                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9793                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9794                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9795                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9796                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9797                        true /*allowInstall*/, instantApp, virtualPreload,
9798                        parentPackageName, pkg.getChildPackageNames(),
9799                        UserManagerService.getInstance(), usesStaticLibraries,
9800                        pkg.usesStaticLibrariesVersions);
9801                // SIDE EFFECTS; updates system state; move elsewhere
9802                if (origPackage != null) {
9803                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9804                }
9805                mSettings.addUserToSettingLPw(pkgSetting);
9806            } else {
9807                // REMOVE SharedUserSetting from method; update in a separate call.
9808                //
9809                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9810                // secondaryCpuAbi are not known at this point so we always update them
9811                // to null here, only to reset them at a later point.
9812                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9813                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9814                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9815                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9816                        UserManagerService.getInstance(), usesStaticLibraries,
9817                        pkg.usesStaticLibrariesVersions);
9818            }
9819            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9820            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9821
9822            // SIDE EFFECTS; modifies system state; move elsewhere
9823            if (pkgSetting.origPackage != null) {
9824                // If we are first transitioning from an original package,
9825                // fix up the new package's name now.  We need to do this after
9826                // looking up the package under its new name, so getPackageLP
9827                // can take care of fiddling things correctly.
9828                pkg.setPackageName(origPackage.name);
9829
9830                // File a report about this.
9831                String msg = "New package " + pkgSetting.realName
9832                        + " renamed to replace old package " + pkgSetting.name;
9833                reportSettingsProblem(Log.WARN, msg);
9834
9835                // Make a note of it.
9836                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9837                    mTransferedPackages.add(origPackage.name);
9838                }
9839
9840                // No longer need to retain this.
9841                pkgSetting.origPackage = null;
9842            }
9843
9844            // SIDE EFFECTS; modifies system state; move elsewhere
9845            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9846                // Make a note of it.
9847                mTransferedPackages.add(pkg.packageName);
9848            }
9849
9850            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9851                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9852            }
9853
9854            if ((scanFlags & SCAN_BOOTING) == 0
9855                    && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9856                // Check all shared libraries and map to their actual file path.
9857                // We only do this here for apps not on a system dir, because those
9858                // are the only ones that can fail an install due to this.  We
9859                // will take care of the system apps by updating all of their
9860                // library paths after the scan is done. Also during the initial
9861                // scan don't update any libs as we do this wholesale after all
9862                // apps are scanned to avoid dependency based scanning.
9863                updateSharedLibrariesLPr(pkg, null);
9864            }
9865
9866            if (mFoundPolicyFile) {
9867                SELinuxMMAC.assignSeInfoValue(pkg);
9868            }
9869            pkg.applicationInfo.uid = pkgSetting.appId;
9870            pkg.mExtras = pkgSetting;
9871
9872
9873            // Static shared libs have same package with different versions where
9874            // we internally use a synthetic package name to allow multiple versions
9875            // of the same package, therefore we need to compare signatures against
9876            // the package setting for the latest library version.
9877            PackageSetting signatureCheckPs = pkgSetting;
9878            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9879                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9880                if (libraryEntry != null) {
9881                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9882                }
9883            }
9884
9885            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9886            if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9887                if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9888                    // We just determined the app is signed correctly, so bring
9889                    // over the latest parsed certs.
9890                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9891                } else {
9892                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9893                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9894                                "Package " + pkg.packageName + " upgrade keys do not match the "
9895                                + "previously installed version");
9896                    } else {
9897                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9898                        String msg = "System package " + pkg.packageName
9899                                + " signature changed; retaining data.";
9900                        reportSettingsProblem(Log.WARN, msg);
9901                    }
9902                }
9903            } else {
9904                try {
9905                    final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9906                    final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9907                    final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9908                            compareCompat, compareRecover);
9909                    // The new KeySets will be re-added later in the scanning process.
9910                    if (compatMatch) {
9911                        synchronized (mPackages) {
9912                            ksms.removeAppKeySetDataLPw(pkg.packageName);
9913                        }
9914                    }
9915                    // We just determined the app is signed correctly, so bring
9916                    // over the latest parsed certs.
9917                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9918                } catch (PackageManagerException e) {
9919                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9920                        throw e;
9921                    }
9922                    // The signature has changed, but this package is in the system
9923                    // image...  let's recover!
9924                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9925                    // However...  if this package is part of a shared user, but it
9926                    // doesn't match the signature of the shared user, let's fail.
9927                    // What this means is that you can't change the signatures
9928                    // associated with an overall shared user, which doesn't seem all
9929                    // that unreasonable.
9930                    if (signatureCheckPs.sharedUser != null) {
9931                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9932                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9933                            throw new PackageManagerException(
9934                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9935                                    "Signature mismatch for shared user: "
9936                                            + pkgSetting.sharedUser);
9937                        }
9938                    }
9939                    // File a report about this.
9940                    String msg = "System package " + pkg.packageName
9941                            + " signature changed; retaining data.";
9942                    reportSettingsProblem(Log.WARN, msg);
9943                }
9944            }
9945
9946            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9947                // This package wants to adopt ownership of permissions from
9948                // another package.
9949                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9950                    final String origName = pkg.mAdoptPermissions.get(i);
9951                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9952                    if (orig != null) {
9953                        if (verifyPackageUpdateLPr(orig, pkg)) {
9954                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9955                                    + pkg.packageName);
9956                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9957                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9958                        }
9959                    }
9960                }
9961            }
9962        }
9963
9964        pkg.applicationInfo.processName = fixProcessName(
9965                pkg.applicationInfo.packageName,
9966                pkg.applicationInfo.processName);
9967
9968        if (pkg != mPlatformPackage) {
9969            // Get all of our default paths setup
9970            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9971        }
9972
9973        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9974
9975        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9976            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9977                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9978                final boolean extractNativeLibs = !pkg.isLibrary();
9979                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
9980                        mAppLib32InstallDir);
9981                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9982
9983                // Some system apps still use directory structure for native libraries
9984                // in which case we might end up not detecting abi solely based on apk
9985                // structure. Try to detect abi based on directory structure.
9986                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9987                        pkg.applicationInfo.primaryCpuAbi == null) {
9988                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9989                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9990                }
9991            } else {
9992                // This is not a first boot or an upgrade, don't bother deriving the
9993                // ABI during the scan. Instead, trust the value that was stored in the
9994                // package setting.
9995                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9996                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9997
9998                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9999
10000                if (DEBUG_ABI_SELECTION) {
10001                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10002                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10003                        pkg.applicationInfo.secondaryCpuAbi);
10004                }
10005            }
10006        } else {
10007            if ((scanFlags & SCAN_MOVE) != 0) {
10008                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10009                // but we already have this packages package info in the PackageSetting. We just
10010                // use that and derive the native library path based on the new codepath.
10011                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10012                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10013            }
10014
10015            // Set native library paths again. For moves, the path will be updated based on the
10016            // ABIs we've determined above. For non-moves, the path will be updated based on the
10017            // ABIs we determined during compilation, but the path will depend on the final
10018            // package path (after the rename away from the stage path).
10019            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10020        }
10021
10022        // This is a special case for the "system" package, where the ABI is
10023        // dictated by the zygote configuration (and init.rc). We should keep track
10024        // of this ABI so that we can deal with "normal" applications that run under
10025        // the same UID correctly.
10026        if (mPlatformPackage == pkg) {
10027            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10028                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10029        }
10030
10031        // If there's a mismatch between the abi-override in the package setting
10032        // and the abiOverride specified for the install. Warn about this because we
10033        // would've already compiled the app without taking the package setting into
10034        // account.
10035        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10036            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10037                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10038                        " for package " + pkg.packageName);
10039            }
10040        }
10041
10042        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10043        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10044        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10045
10046        // Copy the derived override back to the parsed package, so that we can
10047        // update the package settings accordingly.
10048        pkg.cpuAbiOverride = cpuAbiOverride;
10049
10050        if (DEBUG_ABI_SELECTION) {
10051            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10052                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10053                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10054        }
10055
10056        // Push the derived path down into PackageSettings so we know what to
10057        // clean up at uninstall time.
10058        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10059
10060        if (DEBUG_ABI_SELECTION) {
10061            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10062                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10063                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10064        }
10065
10066        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10067        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10068            // We don't do this here during boot because we can do it all
10069            // at once after scanning all existing packages.
10070            //
10071            // We also do this *before* we perform dexopt on this package, so that
10072            // we can avoid redundant dexopts, and also to make sure we've got the
10073            // code and package path correct.
10074            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10075        }
10076
10077        if (mFactoryTest && pkg.requestedPermissions.contains(
10078                android.Manifest.permission.FACTORY_TEST)) {
10079            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10080        }
10081
10082        if (isSystemApp(pkg)) {
10083            pkgSetting.isOrphaned = true;
10084        }
10085
10086        // Take care of first install / last update times.
10087        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10088        if (currentTime != 0) {
10089            if (pkgSetting.firstInstallTime == 0) {
10090                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10091            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10092                pkgSetting.lastUpdateTime = currentTime;
10093            }
10094        } else if (pkgSetting.firstInstallTime == 0) {
10095            // We need *something*.  Take time time stamp of the file.
10096            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10097        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10098            if (scanFileTime != pkgSetting.timeStamp) {
10099                // A package on the system image has changed; consider this
10100                // to be an update.
10101                pkgSetting.lastUpdateTime = scanFileTime;
10102            }
10103        }
10104        pkgSetting.setTimeStamp(scanFileTime);
10105
10106        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10107            if (nonMutatedPs != null) {
10108                synchronized (mPackages) {
10109                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10110                }
10111            }
10112        } else {
10113            final int userId = user == null ? 0 : user.getIdentifier();
10114            // Modify state for the given package setting
10115            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10116                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10117            if (pkgSetting.getInstantApp(userId)) {
10118                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10119            }
10120        }
10121        return pkg;
10122    }
10123
10124    /**
10125     * Applies policy to the parsed package based upon the given policy flags.
10126     * Ensures the package is in a good state.
10127     * <p>
10128     * Implementation detail: This method must NOT have any side effect. It would
10129     * ideally be static, but, it requires locks to read system state.
10130     */
10131    private void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10132            final @ScanFlags int scanFlags) {
10133        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10134            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10135            if (pkg.applicationInfo.isDirectBootAware()) {
10136                // we're direct boot aware; set for all components
10137                for (PackageParser.Service s : pkg.services) {
10138                    s.info.encryptionAware = s.info.directBootAware = true;
10139                }
10140                for (PackageParser.Provider p : pkg.providers) {
10141                    p.info.encryptionAware = p.info.directBootAware = true;
10142                }
10143                for (PackageParser.Activity a : pkg.activities) {
10144                    a.info.encryptionAware = a.info.directBootAware = true;
10145                }
10146                for (PackageParser.Activity r : pkg.receivers) {
10147                    r.info.encryptionAware = r.info.directBootAware = true;
10148                }
10149            }
10150            if (compressedFileExists(pkg.codePath)) {
10151                pkg.isStub = true;
10152            }
10153        } else {
10154            // non system apps can't be flagged as core
10155            pkg.coreApp = false;
10156            // clear flags not applicable to regular apps
10157            pkg.applicationInfo.flags &=
10158                    ~ApplicationInfo.FLAG_PERSISTENT;
10159            pkg.applicationInfo.privateFlags &=
10160                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10161            pkg.applicationInfo.privateFlags &=
10162                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10163            // clear protected broadcasts
10164            pkg.protectedBroadcasts = null;
10165            // cap permission priorities
10166            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10167                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10168                    pkg.permissionGroups.get(i).info.priority = 0;
10169                }
10170            }
10171        }
10172        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10173            // ignore export request for single user receivers
10174            if (pkg.receivers != null) {
10175                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10176                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10177                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10178                        receiver.info.exported = false;
10179                    }
10180                }
10181            }
10182            // ignore export request for single user services
10183            if (pkg.services != null) {
10184                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10185                    final PackageParser.Service service = pkg.services.get(i);
10186                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10187                        service.info.exported = false;
10188                    }
10189                }
10190            }
10191            // ignore export request for single user providers
10192            if (pkg.providers != null) {
10193                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10194                    final PackageParser.Provider provider = pkg.providers.get(i);
10195                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10196                        provider.info.exported = false;
10197                    }
10198                }
10199            }
10200        }
10201        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10202
10203        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10204            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10205        }
10206
10207        if ((scanFlags & SCAN_AS_OEM) != 0) {
10208            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10209        }
10210
10211        if (!isSystemApp(pkg)) {
10212            // Only system apps can use these features.
10213            pkg.mOriginalPackages = null;
10214            pkg.mRealPackage = null;
10215            pkg.mAdoptPermissions = null;
10216        }
10217    }
10218
10219    /**
10220     * Asserts the parsed package is valid according to the given policy. If the
10221     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10222     * <p>
10223     * Implementation detail: This method must NOT have any side effects. It would
10224     * ideally be static, but, it requires locks to read system state.
10225     *
10226     * @throws PackageManagerException If the package fails any of the validation checks
10227     */
10228    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10229            final @ScanFlags int scanFlags)
10230                    throws PackageManagerException {
10231        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10232            assertCodePolicy(pkg);
10233        }
10234
10235        if (pkg.applicationInfo.getCodePath() == null ||
10236                pkg.applicationInfo.getResourcePath() == null) {
10237            // Bail out. The resource and code paths haven't been set.
10238            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10239                    "Code and resource paths haven't been set correctly");
10240        }
10241
10242        // Make sure we're not adding any bogus keyset info
10243        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10244        ksms.assertScannedPackageValid(pkg);
10245
10246        synchronized (mPackages) {
10247            // The special "android" package can only be defined once
10248            if (pkg.packageName.equals("android")) {
10249                if (mAndroidApplication != null) {
10250                    Slog.w(TAG, "*************************************************");
10251                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10252                    Slog.w(TAG, " codePath=" + pkg.codePath);
10253                    Slog.w(TAG, "*************************************************");
10254                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10255                            "Core android package being redefined.  Skipping.");
10256                }
10257            }
10258
10259            // A package name must be unique; don't allow duplicates
10260            if (mPackages.containsKey(pkg.packageName)) {
10261                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10262                        "Application package " + pkg.packageName
10263                        + " already installed.  Skipping duplicate.");
10264            }
10265
10266            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10267                // Static libs have a synthetic package name containing the version
10268                // but we still want the base name to be unique.
10269                if (mPackages.containsKey(pkg.manifestPackageName)) {
10270                    throw new PackageManagerException(
10271                            "Duplicate static shared lib provider package");
10272                }
10273
10274                // Static shared libraries should have at least O target SDK
10275                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10276                    throw new PackageManagerException(
10277                            "Packages declaring static-shared libs must target O SDK or higher");
10278                }
10279
10280                // Package declaring static a shared lib cannot be instant apps
10281                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10282                    throw new PackageManagerException(
10283                            "Packages declaring static-shared libs cannot be instant apps");
10284                }
10285
10286                // Package declaring static a shared lib cannot be renamed since the package
10287                // name is synthetic and apps can't code around package manager internals.
10288                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10289                    throw new PackageManagerException(
10290                            "Packages declaring static-shared libs cannot be renamed");
10291                }
10292
10293                // Package declaring static a shared lib cannot declare child packages
10294                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10295                    throw new PackageManagerException(
10296                            "Packages declaring static-shared libs cannot have child packages");
10297                }
10298
10299                // Package declaring static a shared lib cannot declare dynamic libs
10300                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10301                    throw new PackageManagerException(
10302                            "Packages declaring static-shared libs cannot declare dynamic libs");
10303                }
10304
10305                // Package declaring static a shared lib cannot declare shared users
10306                if (pkg.mSharedUserId != null) {
10307                    throw new PackageManagerException(
10308                            "Packages declaring static-shared libs cannot declare shared users");
10309                }
10310
10311                // Static shared libs cannot declare activities
10312                if (!pkg.activities.isEmpty()) {
10313                    throw new PackageManagerException(
10314                            "Static shared libs cannot declare activities");
10315                }
10316
10317                // Static shared libs cannot declare services
10318                if (!pkg.services.isEmpty()) {
10319                    throw new PackageManagerException(
10320                            "Static shared libs cannot declare services");
10321                }
10322
10323                // Static shared libs cannot declare providers
10324                if (!pkg.providers.isEmpty()) {
10325                    throw new PackageManagerException(
10326                            "Static shared libs cannot declare content providers");
10327                }
10328
10329                // Static shared libs cannot declare receivers
10330                if (!pkg.receivers.isEmpty()) {
10331                    throw new PackageManagerException(
10332                            "Static shared libs cannot declare broadcast receivers");
10333                }
10334
10335                // Static shared libs cannot declare permission groups
10336                if (!pkg.permissionGroups.isEmpty()) {
10337                    throw new PackageManagerException(
10338                            "Static shared libs cannot declare permission groups");
10339                }
10340
10341                // Static shared libs cannot declare permissions
10342                if (!pkg.permissions.isEmpty()) {
10343                    throw new PackageManagerException(
10344                            "Static shared libs cannot declare permissions");
10345                }
10346
10347                // Static shared libs cannot declare protected broadcasts
10348                if (pkg.protectedBroadcasts != null) {
10349                    throw new PackageManagerException(
10350                            "Static shared libs cannot declare protected broadcasts");
10351                }
10352
10353                // Static shared libs cannot be overlay targets
10354                if (pkg.mOverlayTarget != null) {
10355                    throw new PackageManagerException(
10356                            "Static shared libs cannot be overlay targets");
10357                }
10358
10359                // The version codes must be ordered as lib versions
10360                int minVersionCode = Integer.MIN_VALUE;
10361                int maxVersionCode = Integer.MAX_VALUE;
10362
10363                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10364                        pkg.staticSharedLibName);
10365                if (versionedLib != null) {
10366                    final int versionCount = versionedLib.size();
10367                    for (int i = 0; i < versionCount; i++) {
10368                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10369                        final int libVersionCode = libInfo.getDeclaringPackage()
10370                                .getVersionCode();
10371                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10372                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10373                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10374                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10375                        } else {
10376                            minVersionCode = maxVersionCode = libVersionCode;
10377                            break;
10378                        }
10379                    }
10380                }
10381                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10382                    throw new PackageManagerException("Static shared"
10383                            + " lib version codes must be ordered as lib versions");
10384                }
10385            }
10386
10387            // Only privileged apps and updated privileged apps can add child packages.
10388            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10389                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10390                    throw new PackageManagerException("Only privileged apps can add child "
10391                            + "packages. Ignoring package " + pkg.packageName);
10392                }
10393                final int childCount = pkg.childPackages.size();
10394                for (int i = 0; i < childCount; i++) {
10395                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10396                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10397                            childPkg.packageName)) {
10398                        throw new PackageManagerException("Can't override child of "
10399                                + "another disabled app. Ignoring package " + pkg.packageName);
10400                    }
10401                }
10402            }
10403
10404            // If we're only installing presumed-existing packages, require that the
10405            // scanned APK is both already known and at the path previously established
10406            // for it.  Previously unknown packages we pick up normally, but if we have an
10407            // a priori expectation about this package's install presence, enforce it.
10408            // With a singular exception for new system packages. When an OTA contains
10409            // a new system package, we allow the codepath to change from a system location
10410            // to the user-installed location. If we don't allow this change, any newer,
10411            // user-installed version of the application will be ignored.
10412            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10413                if (mExpectingBetter.containsKey(pkg.packageName)) {
10414                    logCriticalInfo(Log.WARN,
10415                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10416                } else {
10417                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10418                    if (known != null) {
10419                        if (DEBUG_PACKAGE_SCANNING) {
10420                            Log.d(TAG, "Examining " + pkg.codePath
10421                                    + " and requiring known paths " + known.codePathString
10422                                    + " & " + known.resourcePathString);
10423                        }
10424                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10425                                || !pkg.applicationInfo.getResourcePath().equals(
10426                                        known.resourcePathString)) {
10427                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10428                                    "Application package " + pkg.packageName
10429                                    + " found at " + pkg.applicationInfo.getCodePath()
10430                                    + " but expected at " + known.codePathString
10431                                    + "; ignoring.");
10432                        }
10433                    } else {
10434                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10435                                "Application package " + pkg.packageName
10436                                + " not found; ignoring.");
10437                    }
10438                }
10439            }
10440
10441            // Verify that this new package doesn't have any content providers
10442            // that conflict with existing packages.  Only do this if the
10443            // package isn't already installed, since we don't want to break
10444            // things that are installed.
10445            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10446                final int N = pkg.providers.size();
10447                int i;
10448                for (i=0; i<N; i++) {
10449                    PackageParser.Provider p = pkg.providers.get(i);
10450                    if (p.info.authority != null) {
10451                        String names[] = p.info.authority.split(";");
10452                        for (int j = 0; j < names.length; j++) {
10453                            if (mProvidersByAuthority.containsKey(names[j])) {
10454                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10455                                final String otherPackageName =
10456                                        ((other != null && other.getComponentName() != null) ?
10457                                                other.getComponentName().getPackageName() : "?");
10458                                throw new PackageManagerException(
10459                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10460                                        "Can't install because provider name " + names[j]
10461                                                + " (in package " + pkg.applicationInfo.packageName
10462                                                + ") is already used by " + otherPackageName);
10463                            }
10464                        }
10465                    }
10466                }
10467            }
10468        }
10469    }
10470
10471    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10472            int type, String declaringPackageName, int declaringVersionCode) {
10473        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10474        if (versionedLib == null) {
10475            versionedLib = new SparseArray<>();
10476            mSharedLibraries.put(name, versionedLib);
10477            if (type == SharedLibraryInfo.TYPE_STATIC) {
10478                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10479            }
10480        } else if (versionedLib.indexOfKey(version) >= 0) {
10481            return false;
10482        }
10483        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10484                version, type, declaringPackageName, declaringVersionCode);
10485        versionedLib.put(version, libEntry);
10486        return true;
10487    }
10488
10489    private boolean removeSharedLibraryLPw(String name, int version) {
10490        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10491        if (versionedLib == null) {
10492            return false;
10493        }
10494        final int libIdx = versionedLib.indexOfKey(version);
10495        if (libIdx < 0) {
10496            return false;
10497        }
10498        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10499        versionedLib.remove(version);
10500        if (versionedLib.size() <= 0) {
10501            mSharedLibraries.remove(name);
10502            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10503                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10504                        .getPackageName());
10505            }
10506        }
10507        return true;
10508    }
10509
10510    /**
10511     * Adds a scanned package to the system. When this method is finished, the package will
10512     * be available for query, resolution, etc...
10513     */
10514    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10515            UserHandle user, final @ScanFlags int scanFlags, boolean chatty)
10516                    throws PackageManagerException {
10517        final String pkgName = pkg.packageName;
10518        if (mCustomResolverComponentName != null &&
10519                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10520            setUpCustomResolverActivity(pkg);
10521        }
10522
10523        if (pkg.packageName.equals("android")) {
10524            synchronized (mPackages) {
10525                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10526                    // Set up information for our fall-back user intent resolution activity.
10527                    mPlatformPackage = pkg;
10528                    pkg.mVersionCode = mSdkVersion;
10529                    mAndroidApplication = pkg.applicationInfo;
10530                    if (!mResolverReplaced) {
10531                        mResolveActivity.applicationInfo = mAndroidApplication;
10532                        mResolveActivity.name = ResolverActivity.class.getName();
10533                        mResolveActivity.packageName = mAndroidApplication.packageName;
10534                        mResolveActivity.processName = "system:ui";
10535                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10536                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10537                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10538                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10539                        mResolveActivity.exported = true;
10540                        mResolveActivity.enabled = true;
10541                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10542                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10543                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10544                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10545                                | ActivityInfo.CONFIG_ORIENTATION
10546                                | ActivityInfo.CONFIG_KEYBOARD
10547                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10548                        mResolveInfo.activityInfo = mResolveActivity;
10549                        mResolveInfo.priority = 0;
10550                        mResolveInfo.preferredOrder = 0;
10551                        mResolveInfo.match = 0;
10552                        mResolveComponentName = new ComponentName(
10553                                mAndroidApplication.packageName, mResolveActivity.name);
10554                    }
10555                }
10556            }
10557        }
10558
10559        ArrayList<PackageParser.Package> clientLibPkgs = null;
10560        // writer
10561        synchronized (mPackages) {
10562            boolean hasStaticSharedLibs = false;
10563
10564            // Any app can add new static shared libraries
10565            if (pkg.staticSharedLibName != null) {
10566                // Static shared libs don't allow renaming as they have synthetic package
10567                // names to allow install of multiple versions, so use name from manifest.
10568                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10569                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10570                        pkg.manifestPackageName, pkg.mVersionCode)) {
10571                    hasStaticSharedLibs = true;
10572                } else {
10573                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10574                                + pkg.staticSharedLibName + " already exists; skipping");
10575                }
10576                // Static shared libs cannot be updated once installed since they
10577                // use synthetic package name which includes the version code, so
10578                // not need to update other packages's shared lib dependencies.
10579            }
10580
10581            if (!hasStaticSharedLibs
10582                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10583                // Only system apps can add new dynamic shared libraries.
10584                if (pkg.libraryNames != null) {
10585                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10586                        String name = pkg.libraryNames.get(i);
10587                        boolean allowed = false;
10588                        if (pkg.isUpdatedSystemApp()) {
10589                            // New library entries can only be added through the
10590                            // system image.  This is important to get rid of a lot
10591                            // of nasty edge cases: for example if we allowed a non-
10592                            // system update of the app to add a library, then uninstalling
10593                            // the update would make the library go away, and assumptions
10594                            // we made such as through app install filtering would now
10595                            // have allowed apps on the device which aren't compatible
10596                            // with it.  Better to just have the restriction here, be
10597                            // conservative, and create many fewer cases that can negatively
10598                            // impact the user experience.
10599                            final PackageSetting sysPs = mSettings
10600                                    .getDisabledSystemPkgLPr(pkg.packageName);
10601                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10602                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10603                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10604                                        allowed = true;
10605                                        break;
10606                                    }
10607                                }
10608                            }
10609                        } else {
10610                            allowed = true;
10611                        }
10612                        if (allowed) {
10613                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10614                                    SharedLibraryInfo.VERSION_UNDEFINED,
10615                                    SharedLibraryInfo.TYPE_DYNAMIC,
10616                                    pkg.packageName, pkg.mVersionCode)) {
10617                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10618                                        + name + " already exists; skipping");
10619                            }
10620                        } else {
10621                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10622                                    + name + " that is not declared on system image; skipping");
10623                        }
10624                    }
10625
10626                    if ((scanFlags & SCAN_BOOTING) == 0) {
10627                        // If we are not booting, we need to update any applications
10628                        // that are clients of our shared library.  If we are booting,
10629                        // this will all be done once the scan is complete.
10630                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10631                    }
10632                }
10633            }
10634        }
10635
10636        if ((scanFlags & SCAN_BOOTING) != 0) {
10637            // No apps can run during boot scan, so they don't need to be frozen
10638        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10639            // Caller asked to not kill app, so it's probably not frozen
10640        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10641            // Caller asked us to ignore frozen check for some reason; they
10642            // probably didn't know the package name
10643        } else {
10644            // We're doing major surgery on this package, so it better be frozen
10645            // right now to keep it from launching
10646            checkPackageFrozen(pkgName);
10647        }
10648
10649        // Also need to kill any apps that are dependent on the library.
10650        if (clientLibPkgs != null) {
10651            for (int i=0; i<clientLibPkgs.size(); i++) {
10652                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10653                killApplication(clientPkg.applicationInfo.packageName,
10654                        clientPkg.applicationInfo.uid, "update lib");
10655            }
10656        }
10657
10658        // writer
10659        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10660
10661        synchronized (mPackages) {
10662            // We don't expect installation to fail beyond this point
10663
10664            // Add the new setting to mSettings
10665            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10666            // Add the new setting to mPackages
10667            mPackages.put(pkg.applicationInfo.packageName, pkg);
10668            // Make sure we don't accidentally delete its data.
10669            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10670            while (iter.hasNext()) {
10671                PackageCleanItem item = iter.next();
10672                if (pkgName.equals(item.packageName)) {
10673                    iter.remove();
10674                }
10675            }
10676
10677            // Add the package's KeySets to the global KeySetManagerService
10678            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10679            ksms.addScannedPackageLPw(pkg);
10680
10681            int N = pkg.providers.size();
10682            StringBuilder r = null;
10683            int i;
10684            for (i=0; i<N; i++) {
10685                PackageParser.Provider p = pkg.providers.get(i);
10686                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10687                        p.info.processName);
10688                mProviders.addProvider(p);
10689                p.syncable = p.info.isSyncable;
10690                if (p.info.authority != null) {
10691                    String names[] = p.info.authority.split(";");
10692                    p.info.authority = null;
10693                    for (int j = 0; j < names.length; j++) {
10694                        if (j == 1 && p.syncable) {
10695                            // We only want the first authority for a provider to possibly be
10696                            // syncable, so if we already added this provider using a different
10697                            // authority clear the syncable flag. We copy the provider before
10698                            // changing it because the mProviders object contains a reference
10699                            // to a provider that we don't want to change.
10700                            // Only do this for the second authority since the resulting provider
10701                            // object can be the same for all future authorities for this provider.
10702                            p = new PackageParser.Provider(p);
10703                            p.syncable = false;
10704                        }
10705                        if (!mProvidersByAuthority.containsKey(names[j])) {
10706                            mProvidersByAuthority.put(names[j], p);
10707                            if (p.info.authority == null) {
10708                                p.info.authority = names[j];
10709                            } else {
10710                                p.info.authority = p.info.authority + ";" + names[j];
10711                            }
10712                            if (DEBUG_PACKAGE_SCANNING) {
10713                                if (chatty)
10714                                    Log.d(TAG, "Registered content provider: " + names[j]
10715                                            + ", className = " + p.info.name + ", isSyncable = "
10716                                            + p.info.isSyncable);
10717                            }
10718                        } else {
10719                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10720                            Slog.w(TAG, "Skipping provider name " + names[j] +
10721                                    " (in package " + pkg.applicationInfo.packageName +
10722                                    "): name already used by "
10723                                    + ((other != null && other.getComponentName() != null)
10724                                            ? other.getComponentName().getPackageName() : "?"));
10725                        }
10726                    }
10727                }
10728                if (chatty) {
10729                    if (r == null) {
10730                        r = new StringBuilder(256);
10731                    } else {
10732                        r.append(' ');
10733                    }
10734                    r.append(p.info.name);
10735                }
10736            }
10737            if (r != null) {
10738                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10739            }
10740
10741            N = pkg.services.size();
10742            r = null;
10743            for (i=0; i<N; i++) {
10744                PackageParser.Service s = pkg.services.get(i);
10745                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10746                        s.info.processName);
10747                mServices.addService(s);
10748                if (chatty) {
10749                    if (r == null) {
10750                        r = new StringBuilder(256);
10751                    } else {
10752                        r.append(' ');
10753                    }
10754                    r.append(s.info.name);
10755                }
10756            }
10757            if (r != null) {
10758                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10759            }
10760
10761            N = pkg.receivers.size();
10762            r = null;
10763            for (i=0; i<N; i++) {
10764                PackageParser.Activity a = pkg.receivers.get(i);
10765                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10766                        a.info.processName);
10767                mReceivers.addActivity(a, "receiver");
10768                if (chatty) {
10769                    if (r == null) {
10770                        r = new StringBuilder(256);
10771                    } else {
10772                        r.append(' ');
10773                    }
10774                    r.append(a.info.name);
10775                }
10776            }
10777            if (r != null) {
10778                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10779            }
10780
10781            N = pkg.activities.size();
10782            r = null;
10783            for (i=0; i<N; i++) {
10784                PackageParser.Activity a = pkg.activities.get(i);
10785                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10786                        a.info.processName);
10787                mActivities.addActivity(a, "activity");
10788                if (chatty) {
10789                    if (r == null) {
10790                        r = new StringBuilder(256);
10791                    } else {
10792                        r.append(' ');
10793                    }
10794                    r.append(a.info.name);
10795                }
10796            }
10797            if (r != null) {
10798                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10799            }
10800
10801            // Don't allow ephemeral applications to define new permissions groups.
10802            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10803                Slog.w(TAG, "Permission groups from package " + pkg.packageName
10804                        + " ignored: instant apps cannot define new permission groups.");
10805            } else {
10806                mPermissionManager.addAllPermissionGroups(pkg, chatty);
10807            }
10808
10809            // Don't allow ephemeral applications to define new permissions.
10810            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10811                Slog.w(TAG, "Permissions from package " + pkg.packageName
10812                        + " ignored: instant apps cannot define new permissions.");
10813            } else {
10814                mPermissionManager.addAllPermissions(pkg, chatty);
10815            }
10816
10817            N = pkg.instrumentation.size();
10818            r = null;
10819            for (i=0; i<N; i++) {
10820                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10821                a.info.packageName = pkg.applicationInfo.packageName;
10822                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10823                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10824                a.info.splitNames = pkg.splitNames;
10825                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10826                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10827                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10828                a.info.dataDir = pkg.applicationInfo.dataDir;
10829                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10830                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10831                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10832                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10833                mInstrumentation.put(a.getComponentName(), a);
10834                if (chatty) {
10835                    if (r == null) {
10836                        r = new StringBuilder(256);
10837                    } else {
10838                        r.append(' ');
10839                    }
10840                    r.append(a.info.name);
10841                }
10842            }
10843            if (r != null) {
10844                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10845            }
10846
10847            if (pkg.protectedBroadcasts != null) {
10848                N = pkg.protectedBroadcasts.size();
10849                synchronized (mProtectedBroadcasts) {
10850                    for (i = 0; i < N; i++) {
10851                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10852                    }
10853                }
10854            }
10855        }
10856
10857        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10858    }
10859
10860    /**
10861     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10862     * is derived purely on the basis of the contents of {@code scanFile} and
10863     * {@code cpuAbiOverride}.
10864     *
10865     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10866     */
10867    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10868                                 String cpuAbiOverride, boolean extractLibs,
10869                                 File appLib32InstallDir)
10870            throws PackageManagerException {
10871        // Give ourselves some initial paths; we'll come back for another
10872        // pass once we've determined ABI below.
10873        setNativeLibraryPaths(pkg, appLib32InstallDir);
10874
10875        // We would never need to extract libs for forward-locked and external packages,
10876        // since the container service will do it for us. We shouldn't attempt to
10877        // extract libs from system app when it was not updated.
10878        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10879                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10880            extractLibs = false;
10881        }
10882
10883        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10884        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10885
10886        NativeLibraryHelper.Handle handle = null;
10887        try {
10888            handle = NativeLibraryHelper.Handle.create(pkg);
10889            // TODO(multiArch): This can be null for apps that didn't go through the
10890            // usual installation process. We can calculate it again, like we
10891            // do during install time.
10892            //
10893            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10894            // unnecessary.
10895            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10896
10897            // Null out the abis so that they can be recalculated.
10898            pkg.applicationInfo.primaryCpuAbi = null;
10899            pkg.applicationInfo.secondaryCpuAbi = null;
10900            if (isMultiArch(pkg.applicationInfo)) {
10901                // Warn if we've set an abiOverride for multi-lib packages..
10902                // By definition, we need to copy both 32 and 64 bit libraries for
10903                // such packages.
10904                if (pkg.cpuAbiOverride != null
10905                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10906                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10907                }
10908
10909                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10910                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10911                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10912                    if (extractLibs) {
10913                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10914                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10915                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10916                                useIsaSpecificSubdirs);
10917                    } else {
10918                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10919                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10920                    }
10921                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10922                }
10923
10924                // Shared library native code should be in the APK zip aligned
10925                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
10926                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10927                            "Shared library native lib extraction not supported");
10928                }
10929
10930                maybeThrowExceptionForMultiArchCopy(
10931                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10932
10933                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10934                    if (extractLibs) {
10935                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10936                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10937                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10938                                useIsaSpecificSubdirs);
10939                    } else {
10940                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10941                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10942                    }
10943                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10944                }
10945
10946                maybeThrowExceptionForMultiArchCopy(
10947                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10948
10949                if (abi64 >= 0) {
10950                    // Shared library native libs should be in the APK zip aligned
10951                    if (extractLibs && pkg.isLibrary()) {
10952                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10953                                "Shared library native lib extraction not supported");
10954                    }
10955                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10956                }
10957
10958                if (abi32 >= 0) {
10959                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10960                    if (abi64 >= 0) {
10961                        if (pkg.use32bitAbi) {
10962                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10963                            pkg.applicationInfo.primaryCpuAbi = abi;
10964                        } else {
10965                            pkg.applicationInfo.secondaryCpuAbi = abi;
10966                        }
10967                    } else {
10968                        pkg.applicationInfo.primaryCpuAbi = abi;
10969                    }
10970                }
10971            } else {
10972                String[] abiList = (cpuAbiOverride != null) ?
10973                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10974
10975                // Enable gross and lame hacks for apps that are built with old
10976                // SDK tools. We must scan their APKs for renderscript bitcode and
10977                // not launch them if it's present. Don't bother checking on devices
10978                // that don't have 64 bit support.
10979                boolean needsRenderScriptOverride = false;
10980                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10981                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10982                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10983                    needsRenderScriptOverride = true;
10984                }
10985
10986                final int copyRet;
10987                if (extractLibs) {
10988                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10989                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10990                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10991                } else {
10992                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10993                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10994                }
10995                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10996
10997                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10998                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10999                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11000                }
11001
11002                if (copyRet >= 0) {
11003                    // Shared libraries that have native libs must be multi-architecture
11004                    if (pkg.isLibrary()) {
11005                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11006                                "Shared library with native libs must be multiarch");
11007                    }
11008                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11009                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11010                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11011                } else if (needsRenderScriptOverride) {
11012                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11013                }
11014            }
11015        } catch (IOException ioe) {
11016            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11017        } finally {
11018            IoUtils.closeQuietly(handle);
11019        }
11020
11021        // Now that we've calculated the ABIs and determined if it's an internal app,
11022        // we will go ahead and populate the nativeLibraryPath.
11023        setNativeLibraryPaths(pkg, appLib32InstallDir);
11024    }
11025
11026    /**
11027     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11028     * i.e, so that all packages can be run inside a single process if required.
11029     *
11030     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11031     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11032     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11033     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11034     * updating a package that belongs to a shared user.
11035     *
11036     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11037     * adds unnecessary complexity.
11038     */
11039    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11040            PackageParser.Package scannedPackage) {
11041        String requiredInstructionSet = null;
11042        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11043            requiredInstructionSet = VMRuntime.getInstructionSet(
11044                     scannedPackage.applicationInfo.primaryCpuAbi);
11045        }
11046
11047        PackageSetting requirer = null;
11048        for (PackageSetting ps : packagesForUser) {
11049            // If packagesForUser contains scannedPackage, we skip it. This will happen
11050            // when scannedPackage is an update of an existing package. Without this check,
11051            // we will never be able to change the ABI of any package belonging to a shared
11052            // user, even if it's compatible with other packages.
11053            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11054                if (ps.primaryCpuAbiString == null) {
11055                    continue;
11056                }
11057
11058                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11059                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11060                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11061                    // this but there's not much we can do.
11062                    String errorMessage = "Instruction set mismatch, "
11063                            + ((requirer == null) ? "[caller]" : requirer)
11064                            + " requires " + requiredInstructionSet + " whereas " + ps
11065                            + " requires " + instructionSet;
11066                    Slog.w(TAG, errorMessage);
11067                }
11068
11069                if (requiredInstructionSet == null) {
11070                    requiredInstructionSet = instructionSet;
11071                    requirer = ps;
11072                }
11073            }
11074        }
11075
11076        if (requiredInstructionSet != null) {
11077            String adjustedAbi;
11078            if (requirer != null) {
11079                // requirer != null implies that either scannedPackage was null or that scannedPackage
11080                // did not require an ABI, in which case we have to adjust scannedPackage to match
11081                // the ABI of the set (which is the same as requirer's ABI)
11082                adjustedAbi = requirer.primaryCpuAbiString;
11083                if (scannedPackage != null) {
11084                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11085                }
11086            } else {
11087                // requirer == null implies that we're updating all ABIs in the set to
11088                // match scannedPackage.
11089                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11090            }
11091
11092            for (PackageSetting ps : packagesForUser) {
11093                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11094                    if (ps.primaryCpuAbiString != null) {
11095                        continue;
11096                    }
11097
11098                    ps.primaryCpuAbiString = adjustedAbi;
11099                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11100                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11101                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11102                        if (DEBUG_ABI_SELECTION) {
11103                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11104                                    + " (requirer="
11105                                    + (requirer != null ? requirer.pkg : "null")
11106                                    + ", scannedPackage="
11107                                    + (scannedPackage != null ? scannedPackage : "null")
11108                                    + ")");
11109                        }
11110                        try {
11111                            mInstaller.rmdex(ps.codePathString,
11112                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11113                        } catch (InstallerException ignored) {
11114                        }
11115                    }
11116                }
11117            }
11118        }
11119    }
11120
11121    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11122        synchronized (mPackages) {
11123            mResolverReplaced = true;
11124            // Set up information for custom user intent resolution activity.
11125            mResolveActivity.applicationInfo = pkg.applicationInfo;
11126            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11127            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11128            mResolveActivity.processName = pkg.applicationInfo.packageName;
11129            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11130            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11131                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11132            mResolveActivity.theme = 0;
11133            mResolveActivity.exported = true;
11134            mResolveActivity.enabled = true;
11135            mResolveInfo.activityInfo = mResolveActivity;
11136            mResolveInfo.priority = 0;
11137            mResolveInfo.preferredOrder = 0;
11138            mResolveInfo.match = 0;
11139            mResolveComponentName = mCustomResolverComponentName;
11140            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11141                    mResolveComponentName);
11142        }
11143    }
11144
11145    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11146        if (installerActivity == null) {
11147            if (DEBUG_EPHEMERAL) {
11148                Slog.d(TAG, "Clear ephemeral installer activity");
11149            }
11150            mInstantAppInstallerActivity = null;
11151            return;
11152        }
11153
11154        if (DEBUG_EPHEMERAL) {
11155            Slog.d(TAG, "Set ephemeral installer activity: "
11156                    + installerActivity.getComponentName());
11157        }
11158        // Set up information for ephemeral installer activity
11159        mInstantAppInstallerActivity = installerActivity;
11160        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11161                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11162        mInstantAppInstallerActivity.exported = true;
11163        mInstantAppInstallerActivity.enabled = true;
11164        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11165        mInstantAppInstallerInfo.priority = 0;
11166        mInstantAppInstallerInfo.preferredOrder = 1;
11167        mInstantAppInstallerInfo.isDefault = true;
11168        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11169                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11170    }
11171
11172    private static String calculateBundledApkRoot(final String codePathString) {
11173        final File codePath = new File(codePathString);
11174        final File codeRoot;
11175        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11176            codeRoot = Environment.getRootDirectory();
11177        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11178            codeRoot = Environment.getOemDirectory();
11179        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11180            codeRoot = Environment.getVendorDirectory();
11181        } else {
11182            // Unrecognized code path; take its top real segment as the apk root:
11183            // e.g. /something/app/blah.apk => /something
11184            try {
11185                File f = codePath.getCanonicalFile();
11186                File parent = f.getParentFile();    // non-null because codePath is a file
11187                File tmp;
11188                while ((tmp = parent.getParentFile()) != null) {
11189                    f = parent;
11190                    parent = tmp;
11191                }
11192                codeRoot = f;
11193                Slog.w(TAG, "Unrecognized code path "
11194                        + codePath + " - using " + codeRoot);
11195            } catch (IOException e) {
11196                // Can't canonicalize the code path -- shenanigans?
11197                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11198                return Environment.getRootDirectory().getPath();
11199            }
11200        }
11201        return codeRoot.getPath();
11202    }
11203
11204    /**
11205     * Derive and set the location of native libraries for the given package,
11206     * which varies depending on where and how the package was installed.
11207     */
11208    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11209        final ApplicationInfo info = pkg.applicationInfo;
11210        final String codePath = pkg.codePath;
11211        final File codeFile = new File(codePath);
11212        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11213        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11214
11215        info.nativeLibraryRootDir = null;
11216        info.nativeLibraryRootRequiresIsa = false;
11217        info.nativeLibraryDir = null;
11218        info.secondaryNativeLibraryDir = null;
11219
11220        if (isApkFile(codeFile)) {
11221            // Monolithic install
11222            if (bundledApp) {
11223                // If "/system/lib64/apkname" exists, assume that is the per-package
11224                // native library directory to use; otherwise use "/system/lib/apkname".
11225                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11226                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11227                        getPrimaryInstructionSet(info));
11228
11229                // This is a bundled system app so choose the path based on the ABI.
11230                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11231                // is just the default path.
11232                final String apkName = deriveCodePathName(codePath);
11233                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11234                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11235                        apkName).getAbsolutePath();
11236
11237                if (info.secondaryCpuAbi != null) {
11238                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11239                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11240                            secondaryLibDir, apkName).getAbsolutePath();
11241                }
11242            } else if (asecApp) {
11243                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11244                        .getAbsolutePath();
11245            } else {
11246                final String apkName = deriveCodePathName(codePath);
11247                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11248                        .getAbsolutePath();
11249            }
11250
11251            info.nativeLibraryRootRequiresIsa = false;
11252            info.nativeLibraryDir = info.nativeLibraryRootDir;
11253        } else {
11254            // Cluster install
11255            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11256            info.nativeLibraryRootRequiresIsa = true;
11257
11258            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11259                    getPrimaryInstructionSet(info)).getAbsolutePath();
11260
11261            if (info.secondaryCpuAbi != null) {
11262                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11263                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11264            }
11265        }
11266    }
11267
11268    /**
11269     * Calculate the abis and roots for a bundled app. These can uniquely
11270     * be determined from the contents of the system partition, i.e whether
11271     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11272     * of this information, and instead assume that the system was built
11273     * sensibly.
11274     */
11275    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11276                                           PackageSetting pkgSetting) {
11277        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11278
11279        // If "/system/lib64/apkname" exists, assume that is the per-package
11280        // native library directory to use; otherwise use "/system/lib/apkname".
11281        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11282        setBundledAppAbi(pkg, apkRoot, apkName);
11283        // pkgSetting might be null during rescan following uninstall of updates
11284        // to a bundled app, so accommodate that possibility.  The settings in
11285        // that case will be established later from the parsed package.
11286        //
11287        // If the settings aren't null, sync them up with what we've just derived.
11288        // note that apkRoot isn't stored in the package settings.
11289        if (pkgSetting != null) {
11290            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11291            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11292        }
11293    }
11294
11295    /**
11296     * Deduces the ABI of a bundled app and sets the relevant fields on the
11297     * parsed pkg object.
11298     *
11299     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11300     *        under which system libraries are installed.
11301     * @param apkName the name of the installed package.
11302     */
11303    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11304        final File codeFile = new File(pkg.codePath);
11305
11306        final boolean has64BitLibs;
11307        final boolean has32BitLibs;
11308        if (isApkFile(codeFile)) {
11309            // Monolithic install
11310            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11311            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11312        } else {
11313            // Cluster install
11314            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11315            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11316                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11317                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11318                has64BitLibs = (new File(rootDir, isa)).exists();
11319            } else {
11320                has64BitLibs = false;
11321            }
11322            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11323                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11324                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11325                has32BitLibs = (new File(rootDir, isa)).exists();
11326            } else {
11327                has32BitLibs = false;
11328            }
11329        }
11330
11331        if (has64BitLibs && !has32BitLibs) {
11332            // The package has 64 bit libs, but not 32 bit libs. Its primary
11333            // ABI should be 64 bit. We can safely assume here that the bundled
11334            // native libraries correspond to the most preferred ABI in the list.
11335
11336            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11337            pkg.applicationInfo.secondaryCpuAbi = null;
11338        } else if (has32BitLibs && !has64BitLibs) {
11339            // The package has 32 bit libs but not 64 bit libs. Its primary
11340            // ABI should be 32 bit.
11341
11342            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11343            pkg.applicationInfo.secondaryCpuAbi = null;
11344        } else if (has32BitLibs && has64BitLibs) {
11345            // The application has both 64 and 32 bit bundled libraries. We check
11346            // here that the app declares multiArch support, and warn if it doesn't.
11347            //
11348            // We will be lenient here and record both ABIs. The primary will be the
11349            // ABI that's higher on the list, i.e, a device that's configured to prefer
11350            // 64 bit apps will see a 64 bit primary ABI,
11351
11352            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11353                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11354            }
11355
11356            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11357                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11358                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11359            } else {
11360                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11361                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11362            }
11363        } else {
11364            pkg.applicationInfo.primaryCpuAbi = null;
11365            pkg.applicationInfo.secondaryCpuAbi = null;
11366        }
11367    }
11368
11369    private void killApplication(String pkgName, int appId, String reason) {
11370        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11371    }
11372
11373    private void killApplication(String pkgName, int appId, int userId, String reason) {
11374        // Request the ActivityManager to kill the process(only for existing packages)
11375        // so that we do not end up in a confused state while the user is still using the older
11376        // version of the application while the new one gets installed.
11377        final long token = Binder.clearCallingIdentity();
11378        try {
11379            IActivityManager am = ActivityManager.getService();
11380            if (am != null) {
11381                try {
11382                    am.killApplication(pkgName, appId, userId, reason);
11383                } catch (RemoteException e) {
11384                }
11385            }
11386        } finally {
11387            Binder.restoreCallingIdentity(token);
11388        }
11389    }
11390
11391    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11392        // Remove the parent package setting
11393        PackageSetting ps = (PackageSetting) pkg.mExtras;
11394        if (ps != null) {
11395            removePackageLI(ps, chatty);
11396        }
11397        // Remove the child package setting
11398        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11399        for (int i = 0; i < childCount; i++) {
11400            PackageParser.Package childPkg = pkg.childPackages.get(i);
11401            ps = (PackageSetting) childPkg.mExtras;
11402            if (ps != null) {
11403                removePackageLI(ps, chatty);
11404            }
11405        }
11406    }
11407
11408    void removePackageLI(PackageSetting ps, boolean chatty) {
11409        if (DEBUG_INSTALL) {
11410            if (chatty)
11411                Log.d(TAG, "Removing package " + ps.name);
11412        }
11413
11414        // writer
11415        synchronized (mPackages) {
11416            mPackages.remove(ps.name);
11417            final PackageParser.Package pkg = ps.pkg;
11418            if (pkg != null) {
11419                cleanPackageDataStructuresLILPw(pkg, chatty);
11420            }
11421        }
11422    }
11423
11424    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11425        if (DEBUG_INSTALL) {
11426            if (chatty)
11427                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11428        }
11429
11430        // writer
11431        synchronized (mPackages) {
11432            // Remove the parent package
11433            mPackages.remove(pkg.applicationInfo.packageName);
11434            cleanPackageDataStructuresLILPw(pkg, chatty);
11435
11436            // Remove the child packages
11437            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11438            for (int i = 0; i < childCount; i++) {
11439                PackageParser.Package childPkg = pkg.childPackages.get(i);
11440                mPackages.remove(childPkg.applicationInfo.packageName);
11441                cleanPackageDataStructuresLILPw(childPkg, chatty);
11442            }
11443        }
11444    }
11445
11446    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11447        int N = pkg.providers.size();
11448        StringBuilder r = null;
11449        int i;
11450        for (i=0; i<N; i++) {
11451            PackageParser.Provider p = pkg.providers.get(i);
11452            mProviders.removeProvider(p);
11453            if (p.info.authority == null) {
11454
11455                /* There was another ContentProvider with this authority when
11456                 * this app was installed so this authority is null,
11457                 * Ignore it as we don't have to unregister the provider.
11458                 */
11459                continue;
11460            }
11461            String names[] = p.info.authority.split(";");
11462            for (int j = 0; j < names.length; j++) {
11463                if (mProvidersByAuthority.get(names[j]) == p) {
11464                    mProvidersByAuthority.remove(names[j]);
11465                    if (DEBUG_REMOVE) {
11466                        if (chatty)
11467                            Log.d(TAG, "Unregistered content provider: " + names[j]
11468                                    + ", className = " + p.info.name + ", isSyncable = "
11469                                    + p.info.isSyncable);
11470                    }
11471                }
11472            }
11473            if (DEBUG_REMOVE && chatty) {
11474                if (r == null) {
11475                    r = new StringBuilder(256);
11476                } else {
11477                    r.append(' ');
11478                }
11479                r.append(p.info.name);
11480            }
11481        }
11482        if (r != null) {
11483            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11484        }
11485
11486        N = pkg.services.size();
11487        r = null;
11488        for (i=0; i<N; i++) {
11489            PackageParser.Service s = pkg.services.get(i);
11490            mServices.removeService(s);
11491            if (chatty) {
11492                if (r == null) {
11493                    r = new StringBuilder(256);
11494                } else {
11495                    r.append(' ');
11496                }
11497                r.append(s.info.name);
11498            }
11499        }
11500        if (r != null) {
11501            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11502        }
11503
11504        N = pkg.receivers.size();
11505        r = null;
11506        for (i=0; i<N; i++) {
11507            PackageParser.Activity a = pkg.receivers.get(i);
11508            mReceivers.removeActivity(a, "receiver");
11509            if (DEBUG_REMOVE && chatty) {
11510                if (r == null) {
11511                    r = new StringBuilder(256);
11512                } else {
11513                    r.append(' ');
11514                }
11515                r.append(a.info.name);
11516            }
11517        }
11518        if (r != null) {
11519            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11520        }
11521
11522        N = pkg.activities.size();
11523        r = null;
11524        for (i=0; i<N; i++) {
11525            PackageParser.Activity a = pkg.activities.get(i);
11526            mActivities.removeActivity(a, "activity");
11527            if (DEBUG_REMOVE && chatty) {
11528                if (r == null) {
11529                    r = new StringBuilder(256);
11530                } else {
11531                    r.append(' ');
11532                }
11533                r.append(a.info.name);
11534            }
11535        }
11536        if (r != null) {
11537            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11538        }
11539
11540        mPermissionManager.removeAllPermissions(pkg, chatty);
11541
11542        N = pkg.instrumentation.size();
11543        r = null;
11544        for (i=0; i<N; i++) {
11545            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11546            mInstrumentation.remove(a.getComponentName());
11547            if (DEBUG_REMOVE && chatty) {
11548                if (r == null) {
11549                    r = new StringBuilder(256);
11550                } else {
11551                    r.append(' ');
11552                }
11553                r.append(a.info.name);
11554            }
11555        }
11556        if (r != null) {
11557            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11558        }
11559
11560        r = null;
11561        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11562            // Only system apps can hold shared libraries.
11563            if (pkg.libraryNames != null) {
11564                for (i = 0; i < pkg.libraryNames.size(); i++) {
11565                    String name = pkg.libraryNames.get(i);
11566                    if (removeSharedLibraryLPw(name, 0)) {
11567                        if (DEBUG_REMOVE && chatty) {
11568                            if (r == null) {
11569                                r = new StringBuilder(256);
11570                            } else {
11571                                r.append(' ');
11572                            }
11573                            r.append(name);
11574                        }
11575                    }
11576                }
11577            }
11578        }
11579
11580        r = null;
11581
11582        // Any package can hold static shared libraries.
11583        if (pkg.staticSharedLibName != null) {
11584            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11585                if (DEBUG_REMOVE && chatty) {
11586                    if (r == null) {
11587                        r = new StringBuilder(256);
11588                    } else {
11589                        r.append(' ');
11590                    }
11591                    r.append(pkg.staticSharedLibName);
11592                }
11593            }
11594        }
11595
11596        if (r != null) {
11597            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11598        }
11599    }
11600
11601
11602    final class ActivityIntentResolver
11603            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11604        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11605                boolean defaultOnly, int userId) {
11606            if (!sUserManager.exists(userId)) return null;
11607            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11608            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11609        }
11610
11611        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11612                int userId) {
11613            if (!sUserManager.exists(userId)) return null;
11614            mFlags = flags;
11615            return super.queryIntent(intent, resolvedType,
11616                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11617                    userId);
11618        }
11619
11620        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11621                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11622            if (!sUserManager.exists(userId)) return null;
11623            if (packageActivities == null) {
11624                return null;
11625            }
11626            mFlags = flags;
11627            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11628            final int N = packageActivities.size();
11629            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11630                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11631
11632            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11633            for (int i = 0; i < N; ++i) {
11634                intentFilters = packageActivities.get(i).intents;
11635                if (intentFilters != null && intentFilters.size() > 0) {
11636                    PackageParser.ActivityIntentInfo[] array =
11637                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11638                    intentFilters.toArray(array);
11639                    listCut.add(array);
11640                }
11641            }
11642            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11643        }
11644
11645        /**
11646         * Finds a privileged activity that matches the specified activity names.
11647         */
11648        private PackageParser.Activity findMatchingActivity(
11649                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11650            for (PackageParser.Activity sysActivity : activityList) {
11651                if (sysActivity.info.name.equals(activityInfo.name)) {
11652                    return sysActivity;
11653                }
11654                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11655                    return sysActivity;
11656                }
11657                if (sysActivity.info.targetActivity != null) {
11658                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11659                        return sysActivity;
11660                    }
11661                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11662                        return sysActivity;
11663                    }
11664                }
11665            }
11666            return null;
11667        }
11668
11669        public class IterGenerator<E> {
11670            public Iterator<E> generate(ActivityIntentInfo info) {
11671                return null;
11672            }
11673        }
11674
11675        public class ActionIterGenerator extends IterGenerator<String> {
11676            @Override
11677            public Iterator<String> generate(ActivityIntentInfo info) {
11678                return info.actionsIterator();
11679            }
11680        }
11681
11682        public class CategoriesIterGenerator extends IterGenerator<String> {
11683            @Override
11684            public Iterator<String> generate(ActivityIntentInfo info) {
11685                return info.categoriesIterator();
11686            }
11687        }
11688
11689        public class SchemesIterGenerator extends IterGenerator<String> {
11690            @Override
11691            public Iterator<String> generate(ActivityIntentInfo info) {
11692                return info.schemesIterator();
11693            }
11694        }
11695
11696        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11697            @Override
11698            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11699                return info.authoritiesIterator();
11700            }
11701        }
11702
11703        /**
11704         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11705         * MODIFIED. Do not pass in a list that should not be changed.
11706         */
11707        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11708                IterGenerator<T> generator, Iterator<T> searchIterator) {
11709            // loop through the set of actions; every one must be found in the intent filter
11710            while (searchIterator.hasNext()) {
11711                // we must have at least one filter in the list to consider a match
11712                if (intentList.size() == 0) {
11713                    break;
11714                }
11715
11716                final T searchAction = searchIterator.next();
11717
11718                // loop through the set of intent filters
11719                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11720                while (intentIter.hasNext()) {
11721                    final ActivityIntentInfo intentInfo = intentIter.next();
11722                    boolean selectionFound = false;
11723
11724                    // loop through the intent filter's selection criteria; at least one
11725                    // of them must match the searched criteria
11726                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11727                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11728                        final T intentSelection = intentSelectionIter.next();
11729                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11730                            selectionFound = true;
11731                            break;
11732                        }
11733                    }
11734
11735                    // the selection criteria wasn't found in this filter's set; this filter
11736                    // is not a potential match
11737                    if (!selectionFound) {
11738                        intentIter.remove();
11739                    }
11740                }
11741            }
11742        }
11743
11744        private boolean isProtectedAction(ActivityIntentInfo filter) {
11745            final Iterator<String> actionsIter = filter.actionsIterator();
11746            while (actionsIter != null && actionsIter.hasNext()) {
11747                final String filterAction = actionsIter.next();
11748                if (PROTECTED_ACTIONS.contains(filterAction)) {
11749                    return true;
11750                }
11751            }
11752            return false;
11753        }
11754
11755        /**
11756         * Adjusts the priority of the given intent filter according to policy.
11757         * <p>
11758         * <ul>
11759         * <li>The priority for non privileged applications is capped to '0'</li>
11760         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11761         * <li>The priority for unbundled updates to privileged applications is capped to the
11762         *      priority defined on the system partition</li>
11763         * </ul>
11764         * <p>
11765         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11766         * allowed to obtain any priority on any action.
11767         */
11768        private void adjustPriority(
11769                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11770            // nothing to do; priority is fine as-is
11771            if (intent.getPriority() <= 0) {
11772                return;
11773            }
11774
11775            final ActivityInfo activityInfo = intent.activity.info;
11776            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11777
11778            final boolean privilegedApp =
11779                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11780            if (!privilegedApp) {
11781                // non-privileged applications can never define a priority >0
11782                if (DEBUG_FILTERS) {
11783                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
11784                            + " package: " + applicationInfo.packageName
11785                            + " activity: " + intent.activity.className
11786                            + " origPrio: " + intent.getPriority());
11787                }
11788                intent.setPriority(0);
11789                return;
11790            }
11791
11792            if (systemActivities == null) {
11793                // the system package is not disabled; we're parsing the system partition
11794                if (isProtectedAction(intent)) {
11795                    if (mDeferProtectedFilters) {
11796                        // We can't deal with these just yet. No component should ever obtain a
11797                        // >0 priority for a protected actions, with ONE exception -- the setup
11798                        // wizard. The setup wizard, however, cannot be known until we're able to
11799                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11800                        // until all intent filters have been processed. Chicken, meet egg.
11801                        // Let the filter temporarily have a high priority and rectify the
11802                        // priorities after all system packages have been scanned.
11803                        mProtectedFilters.add(intent);
11804                        if (DEBUG_FILTERS) {
11805                            Slog.i(TAG, "Protected action; save for later;"
11806                                    + " package: " + applicationInfo.packageName
11807                                    + " activity: " + intent.activity.className
11808                                    + " origPrio: " + intent.getPriority());
11809                        }
11810                        return;
11811                    } else {
11812                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11813                            Slog.i(TAG, "No setup wizard;"
11814                                + " All protected intents capped to priority 0");
11815                        }
11816                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11817                            if (DEBUG_FILTERS) {
11818                                Slog.i(TAG, "Found setup wizard;"
11819                                    + " allow priority " + intent.getPriority() + ";"
11820                                    + " package: " + intent.activity.info.packageName
11821                                    + " activity: " + intent.activity.className
11822                                    + " priority: " + intent.getPriority());
11823                            }
11824                            // setup wizard gets whatever it wants
11825                            return;
11826                        }
11827                        if (DEBUG_FILTERS) {
11828                            Slog.i(TAG, "Protected action; cap priority to 0;"
11829                                    + " package: " + intent.activity.info.packageName
11830                                    + " activity: " + intent.activity.className
11831                                    + " origPrio: " + intent.getPriority());
11832                        }
11833                        intent.setPriority(0);
11834                        return;
11835                    }
11836                }
11837                // privileged apps on the system image get whatever priority they request
11838                return;
11839            }
11840
11841            // privileged app unbundled update ... try to find the same activity
11842            final PackageParser.Activity foundActivity =
11843                    findMatchingActivity(systemActivities, activityInfo);
11844            if (foundActivity == null) {
11845                // this is a new activity; it cannot obtain >0 priority
11846                if (DEBUG_FILTERS) {
11847                    Slog.i(TAG, "New activity; cap priority to 0;"
11848                            + " package: " + applicationInfo.packageName
11849                            + " activity: " + intent.activity.className
11850                            + " origPrio: " + intent.getPriority());
11851                }
11852                intent.setPriority(0);
11853                return;
11854            }
11855
11856            // found activity, now check for filter equivalence
11857
11858            // a shallow copy is enough; we modify the list, not its contents
11859            final List<ActivityIntentInfo> intentListCopy =
11860                    new ArrayList<>(foundActivity.intents);
11861            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11862
11863            // find matching action subsets
11864            final Iterator<String> actionsIterator = intent.actionsIterator();
11865            if (actionsIterator != null) {
11866                getIntentListSubset(
11867                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11868                if (intentListCopy.size() == 0) {
11869                    // no more intents to match; we're not equivalent
11870                    if (DEBUG_FILTERS) {
11871                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11872                                + " package: " + applicationInfo.packageName
11873                                + " activity: " + intent.activity.className
11874                                + " origPrio: " + intent.getPriority());
11875                    }
11876                    intent.setPriority(0);
11877                    return;
11878                }
11879            }
11880
11881            // find matching category subsets
11882            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11883            if (categoriesIterator != null) {
11884                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11885                        categoriesIterator);
11886                if (intentListCopy.size() == 0) {
11887                    // no more intents to match; we're not equivalent
11888                    if (DEBUG_FILTERS) {
11889                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11890                                + " package: " + applicationInfo.packageName
11891                                + " activity: " + intent.activity.className
11892                                + " origPrio: " + intent.getPriority());
11893                    }
11894                    intent.setPriority(0);
11895                    return;
11896                }
11897            }
11898
11899            // find matching schemes subsets
11900            final Iterator<String> schemesIterator = intent.schemesIterator();
11901            if (schemesIterator != null) {
11902                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11903                        schemesIterator);
11904                if (intentListCopy.size() == 0) {
11905                    // no more intents to match; we're not equivalent
11906                    if (DEBUG_FILTERS) {
11907                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11908                                + " package: " + applicationInfo.packageName
11909                                + " activity: " + intent.activity.className
11910                                + " origPrio: " + intent.getPriority());
11911                    }
11912                    intent.setPriority(0);
11913                    return;
11914                }
11915            }
11916
11917            // find matching authorities subsets
11918            final Iterator<IntentFilter.AuthorityEntry>
11919                    authoritiesIterator = intent.authoritiesIterator();
11920            if (authoritiesIterator != null) {
11921                getIntentListSubset(intentListCopy,
11922                        new AuthoritiesIterGenerator(),
11923                        authoritiesIterator);
11924                if (intentListCopy.size() == 0) {
11925                    // no more intents to match; we're not equivalent
11926                    if (DEBUG_FILTERS) {
11927                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11928                                + " package: " + applicationInfo.packageName
11929                                + " activity: " + intent.activity.className
11930                                + " origPrio: " + intent.getPriority());
11931                    }
11932                    intent.setPriority(0);
11933                    return;
11934                }
11935            }
11936
11937            // we found matching filter(s); app gets the max priority of all intents
11938            int cappedPriority = 0;
11939            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11940                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11941            }
11942            if (intent.getPriority() > cappedPriority) {
11943                if (DEBUG_FILTERS) {
11944                    Slog.i(TAG, "Found matching filter(s);"
11945                            + " cap priority to " + cappedPriority + ";"
11946                            + " package: " + applicationInfo.packageName
11947                            + " activity: " + intent.activity.className
11948                            + " origPrio: " + intent.getPriority());
11949                }
11950                intent.setPriority(cappedPriority);
11951                return;
11952            }
11953            // all this for nothing; the requested priority was <= what was on the system
11954        }
11955
11956        public final void addActivity(PackageParser.Activity a, String type) {
11957            mActivities.put(a.getComponentName(), a);
11958            if (DEBUG_SHOW_INFO)
11959                Log.v(
11960                TAG, "  " + type + " " +
11961                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11962            if (DEBUG_SHOW_INFO)
11963                Log.v(TAG, "    Class=" + a.info.name);
11964            final int NI = a.intents.size();
11965            for (int j=0; j<NI; j++) {
11966                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11967                if ("activity".equals(type)) {
11968                    final PackageSetting ps =
11969                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11970                    final List<PackageParser.Activity> systemActivities =
11971                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11972                    adjustPriority(systemActivities, intent);
11973                }
11974                if (DEBUG_SHOW_INFO) {
11975                    Log.v(TAG, "    IntentFilter:");
11976                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11977                }
11978                if (!intent.debugCheck()) {
11979                    Log.w(TAG, "==> For Activity " + a.info.name);
11980                }
11981                addFilter(intent);
11982            }
11983        }
11984
11985        public final void removeActivity(PackageParser.Activity a, String type) {
11986            mActivities.remove(a.getComponentName());
11987            if (DEBUG_SHOW_INFO) {
11988                Log.v(TAG, "  " + type + " "
11989                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11990                                : a.info.name) + ":");
11991                Log.v(TAG, "    Class=" + a.info.name);
11992            }
11993            final int NI = a.intents.size();
11994            for (int j=0; j<NI; j++) {
11995                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11996                if (DEBUG_SHOW_INFO) {
11997                    Log.v(TAG, "    IntentFilter:");
11998                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11999                }
12000                removeFilter(intent);
12001            }
12002        }
12003
12004        @Override
12005        protected boolean allowFilterResult(
12006                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12007            ActivityInfo filterAi = filter.activity.info;
12008            for (int i=dest.size()-1; i>=0; i--) {
12009                ActivityInfo destAi = dest.get(i).activityInfo;
12010                if (destAi.name == filterAi.name
12011                        && destAi.packageName == filterAi.packageName) {
12012                    return false;
12013                }
12014            }
12015            return true;
12016        }
12017
12018        @Override
12019        protected ActivityIntentInfo[] newArray(int size) {
12020            return new ActivityIntentInfo[size];
12021        }
12022
12023        @Override
12024        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12025            if (!sUserManager.exists(userId)) return true;
12026            PackageParser.Package p = filter.activity.owner;
12027            if (p != null) {
12028                PackageSetting ps = (PackageSetting)p.mExtras;
12029                if (ps != null) {
12030                    // System apps are never considered stopped for purposes of
12031                    // filtering, because there may be no way for the user to
12032                    // actually re-launch them.
12033                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12034                            && ps.getStopped(userId);
12035                }
12036            }
12037            return false;
12038        }
12039
12040        @Override
12041        protected boolean isPackageForFilter(String packageName,
12042                PackageParser.ActivityIntentInfo info) {
12043            return packageName.equals(info.activity.owner.packageName);
12044        }
12045
12046        @Override
12047        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12048                int match, int userId) {
12049            if (!sUserManager.exists(userId)) return null;
12050            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12051                return null;
12052            }
12053            final PackageParser.Activity activity = info.activity;
12054            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12055            if (ps == null) {
12056                return null;
12057            }
12058            final PackageUserState userState = ps.readUserState(userId);
12059            ActivityInfo ai =
12060                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12061            if (ai == null) {
12062                return null;
12063            }
12064            final boolean matchExplicitlyVisibleOnly =
12065                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12066            final boolean matchVisibleToInstantApp =
12067                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12068            final boolean componentVisible =
12069                    matchVisibleToInstantApp
12070                    && info.isVisibleToInstantApp()
12071                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12072            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12073            // throw out filters that aren't visible to ephemeral apps
12074            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12075                return null;
12076            }
12077            // throw out instant app filters if we're not explicitly requesting them
12078            if (!matchInstantApp && userState.instantApp) {
12079                return null;
12080            }
12081            // throw out instant app filters if updates are available; will trigger
12082            // instant app resolution
12083            if (userState.instantApp && ps.isUpdateAvailable()) {
12084                return null;
12085            }
12086            final ResolveInfo res = new ResolveInfo();
12087            res.activityInfo = ai;
12088            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12089                res.filter = info;
12090            }
12091            if (info != null) {
12092                res.handleAllWebDataURI = info.handleAllWebDataURI();
12093            }
12094            res.priority = info.getPriority();
12095            res.preferredOrder = activity.owner.mPreferredOrder;
12096            //System.out.println("Result: " + res.activityInfo.className +
12097            //                   " = " + res.priority);
12098            res.match = match;
12099            res.isDefault = info.hasDefault;
12100            res.labelRes = info.labelRes;
12101            res.nonLocalizedLabel = info.nonLocalizedLabel;
12102            if (userNeedsBadging(userId)) {
12103                res.noResourceId = true;
12104            } else {
12105                res.icon = info.icon;
12106            }
12107            res.iconResourceId = info.icon;
12108            res.system = res.activityInfo.applicationInfo.isSystemApp();
12109            res.isInstantAppAvailable = userState.instantApp;
12110            return res;
12111        }
12112
12113        @Override
12114        protected void sortResults(List<ResolveInfo> results) {
12115            Collections.sort(results, mResolvePrioritySorter);
12116        }
12117
12118        @Override
12119        protected void dumpFilter(PrintWriter out, String prefix,
12120                PackageParser.ActivityIntentInfo filter) {
12121            out.print(prefix); out.print(
12122                    Integer.toHexString(System.identityHashCode(filter.activity)));
12123                    out.print(' ');
12124                    filter.activity.printComponentShortName(out);
12125                    out.print(" filter ");
12126                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12127        }
12128
12129        @Override
12130        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12131            return filter.activity;
12132        }
12133
12134        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12135            PackageParser.Activity activity = (PackageParser.Activity)label;
12136            out.print(prefix); out.print(
12137                    Integer.toHexString(System.identityHashCode(activity)));
12138                    out.print(' ');
12139                    activity.printComponentShortName(out);
12140            if (count > 1) {
12141                out.print(" ("); out.print(count); out.print(" filters)");
12142            }
12143            out.println();
12144        }
12145
12146        // Keys are String (activity class name), values are Activity.
12147        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12148                = new ArrayMap<ComponentName, PackageParser.Activity>();
12149        private int mFlags;
12150    }
12151
12152    private final class ServiceIntentResolver
12153            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12154        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12155                boolean defaultOnly, int userId) {
12156            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12157            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12158        }
12159
12160        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12161                int userId) {
12162            if (!sUserManager.exists(userId)) return null;
12163            mFlags = flags;
12164            return super.queryIntent(intent, resolvedType,
12165                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12166                    userId);
12167        }
12168
12169        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12170                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12171            if (!sUserManager.exists(userId)) return null;
12172            if (packageServices == null) {
12173                return null;
12174            }
12175            mFlags = flags;
12176            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12177            final int N = packageServices.size();
12178            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12179                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12180
12181            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12182            for (int i = 0; i < N; ++i) {
12183                intentFilters = packageServices.get(i).intents;
12184                if (intentFilters != null && intentFilters.size() > 0) {
12185                    PackageParser.ServiceIntentInfo[] array =
12186                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12187                    intentFilters.toArray(array);
12188                    listCut.add(array);
12189                }
12190            }
12191            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12192        }
12193
12194        public final void addService(PackageParser.Service s) {
12195            mServices.put(s.getComponentName(), s);
12196            if (DEBUG_SHOW_INFO) {
12197                Log.v(TAG, "  "
12198                        + (s.info.nonLocalizedLabel != null
12199                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12200                Log.v(TAG, "    Class=" + s.info.name);
12201            }
12202            final int NI = s.intents.size();
12203            int j;
12204            for (j=0; j<NI; j++) {
12205                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12206                if (DEBUG_SHOW_INFO) {
12207                    Log.v(TAG, "    IntentFilter:");
12208                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12209                }
12210                if (!intent.debugCheck()) {
12211                    Log.w(TAG, "==> For Service " + s.info.name);
12212                }
12213                addFilter(intent);
12214            }
12215        }
12216
12217        public final void removeService(PackageParser.Service s) {
12218            mServices.remove(s.getComponentName());
12219            if (DEBUG_SHOW_INFO) {
12220                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12221                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12222                Log.v(TAG, "    Class=" + s.info.name);
12223            }
12224            final int NI = s.intents.size();
12225            int j;
12226            for (j=0; j<NI; j++) {
12227                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12228                if (DEBUG_SHOW_INFO) {
12229                    Log.v(TAG, "    IntentFilter:");
12230                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12231                }
12232                removeFilter(intent);
12233            }
12234        }
12235
12236        @Override
12237        protected boolean allowFilterResult(
12238                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12239            ServiceInfo filterSi = filter.service.info;
12240            for (int i=dest.size()-1; i>=0; i--) {
12241                ServiceInfo destAi = dest.get(i).serviceInfo;
12242                if (destAi.name == filterSi.name
12243                        && destAi.packageName == filterSi.packageName) {
12244                    return false;
12245                }
12246            }
12247            return true;
12248        }
12249
12250        @Override
12251        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12252            return new PackageParser.ServiceIntentInfo[size];
12253        }
12254
12255        @Override
12256        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12257            if (!sUserManager.exists(userId)) return true;
12258            PackageParser.Package p = filter.service.owner;
12259            if (p != null) {
12260                PackageSetting ps = (PackageSetting)p.mExtras;
12261                if (ps != null) {
12262                    // System apps are never considered stopped for purposes of
12263                    // filtering, because there may be no way for the user to
12264                    // actually re-launch them.
12265                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12266                            && ps.getStopped(userId);
12267                }
12268            }
12269            return false;
12270        }
12271
12272        @Override
12273        protected boolean isPackageForFilter(String packageName,
12274                PackageParser.ServiceIntentInfo info) {
12275            return packageName.equals(info.service.owner.packageName);
12276        }
12277
12278        @Override
12279        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12280                int match, int userId) {
12281            if (!sUserManager.exists(userId)) return null;
12282            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12283            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12284                return null;
12285            }
12286            final PackageParser.Service service = info.service;
12287            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12288            if (ps == null) {
12289                return null;
12290            }
12291            final PackageUserState userState = ps.readUserState(userId);
12292            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12293                    userState, userId);
12294            if (si == null) {
12295                return null;
12296            }
12297            final boolean matchVisibleToInstantApp =
12298                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12299            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12300            // throw out filters that aren't visible to ephemeral apps
12301            if (matchVisibleToInstantApp
12302                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12303                return null;
12304            }
12305            // throw out ephemeral filters if we're not explicitly requesting them
12306            if (!isInstantApp && userState.instantApp) {
12307                return null;
12308            }
12309            // throw out instant app filters if updates are available; will trigger
12310            // instant app resolution
12311            if (userState.instantApp && ps.isUpdateAvailable()) {
12312                return null;
12313            }
12314            final ResolveInfo res = new ResolveInfo();
12315            res.serviceInfo = si;
12316            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12317                res.filter = filter;
12318            }
12319            res.priority = info.getPriority();
12320            res.preferredOrder = service.owner.mPreferredOrder;
12321            res.match = match;
12322            res.isDefault = info.hasDefault;
12323            res.labelRes = info.labelRes;
12324            res.nonLocalizedLabel = info.nonLocalizedLabel;
12325            res.icon = info.icon;
12326            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12327            return res;
12328        }
12329
12330        @Override
12331        protected void sortResults(List<ResolveInfo> results) {
12332            Collections.sort(results, mResolvePrioritySorter);
12333        }
12334
12335        @Override
12336        protected void dumpFilter(PrintWriter out, String prefix,
12337                PackageParser.ServiceIntentInfo filter) {
12338            out.print(prefix); out.print(
12339                    Integer.toHexString(System.identityHashCode(filter.service)));
12340                    out.print(' ');
12341                    filter.service.printComponentShortName(out);
12342                    out.print(" filter ");
12343                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12344        }
12345
12346        @Override
12347        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12348            return filter.service;
12349        }
12350
12351        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12352            PackageParser.Service service = (PackageParser.Service)label;
12353            out.print(prefix); out.print(
12354                    Integer.toHexString(System.identityHashCode(service)));
12355                    out.print(' ');
12356                    service.printComponentShortName(out);
12357            if (count > 1) {
12358                out.print(" ("); out.print(count); out.print(" filters)");
12359            }
12360            out.println();
12361        }
12362
12363//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12364//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12365//            final List<ResolveInfo> retList = Lists.newArrayList();
12366//            while (i.hasNext()) {
12367//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12368//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12369//                    retList.add(resolveInfo);
12370//                }
12371//            }
12372//            return retList;
12373//        }
12374
12375        // Keys are String (activity class name), values are Activity.
12376        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12377                = new ArrayMap<ComponentName, PackageParser.Service>();
12378        private int mFlags;
12379    }
12380
12381    private final class ProviderIntentResolver
12382            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12383        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12384                boolean defaultOnly, int userId) {
12385            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12386            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12387        }
12388
12389        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12390                int userId) {
12391            if (!sUserManager.exists(userId))
12392                return null;
12393            mFlags = flags;
12394            return super.queryIntent(intent, resolvedType,
12395                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12396                    userId);
12397        }
12398
12399        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12400                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12401            if (!sUserManager.exists(userId))
12402                return null;
12403            if (packageProviders == null) {
12404                return null;
12405            }
12406            mFlags = flags;
12407            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12408            final int N = packageProviders.size();
12409            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12410                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12411
12412            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12413            for (int i = 0; i < N; ++i) {
12414                intentFilters = packageProviders.get(i).intents;
12415                if (intentFilters != null && intentFilters.size() > 0) {
12416                    PackageParser.ProviderIntentInfo[] array =
12417                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12418                    intentFilters.toArray(array);
12419                    listCut.add(array);
12420                }
12421            }
12422            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12423        }
12424
12425        public final void addProvider(PackageParser.Provider p) {
12426            if (mProviders.containsKey(p.getComponentName())) {
12427                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12428                return;
12429            }
12430
12431            mProviders.put(p.getComponentName(), p);
12432            if (DEBUG_SHOW_INFO) {
12433                Log.v(TAG, "  "
12434                        + (p.info.nonLocalizedLabel != null
12435                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12436                Log.v(TAG, "    Class=" + p.info.name);
12437            }
12438            final int NI = p.intents.size();
12439            int j;
12440            for (j = 0; j < NI; j++) {
12441                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12442                if (DEBUG_SHOW_INFO) {
12443                    Log.v(TAG, "    IntentFilter:");
12444                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12445                }
12446                if (!intent.debugCheck()) {
12447                    Log.w(TAG, "==> For Provider " + p.info.name);
12448                }
12449                addFilter(intent);
12450            }
12451        }
12452
12453        public final void removeProvider(PackageParser.Provider p) {
12454            mProviders.remove(p.getComponentName());
12455            if (DEBUG_SHOW_INFO) {
12456                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12457                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12458                Log.v(TAG, "    Class=" + p.info.name);
12459            }
12460            final int NI = p.intents.size();
12461            int j;
12462            for (j = 0; j < NI; j++) {
12463                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12464                if (DEBUG_SHOW_INFO) {
12465                    Log.v(TAG, "    IntentFilter:");
12466                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12467                }
12468                removeFilter(intent);
12469            }
12470        }
12471
12472        @Override
12473        protected boolean allowFilterResult(
12474                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12475            ProviderInfo filterPi = filter.provider.info;
12476            for (int i = dest.size() - 1; i >= 0; i--) {
12477                ProviderInfo destPi = dest.get(i).providerInfo;
12478                if (destPi.name == filterPi.name
12479                        && destPi.packageName == filterPi.packageName) {
12480                    return false;
12481                }
12482            }
12483            return true;
12484        }
12485
12486        @Override
12487        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12488            return new PackageParser.ProviderIntentInfo[size];
12489        }
12490
12491        @Override
12492        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12493            if (!sUserManager.exists(userId))
12494                return true;
12495            PackageParser.Package p = filter.provider.owner;
12496            if (p != null) {
12497                PackageSetting ps = (PackageSetting) p.mExtras;
12498                if (ps != null) {
12499                    // System apps are never considered stopped for purposes of
12500                    // filtering, because there may be no way for the user to
12501                    // actually re-launch them.
12502                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12503                            && ps.getStopped(userId);
12504                }
12505            }
12506            return false;
12507        }
12508
12509        @Override
12510        protected boolean isPackageForFilter(String packageName,
12511                PackageParser.ProviderIntentInfo info) {
12512            return packageName.equals(info.provider.owner.packageName);
12513        }
12514
12515        @Override
12516        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12517                int match, int userId) {
12518            if (!sUserManager.exists(userId))
12519                return null;
12520            final PackageParser.ProviderIntentInfo info = filter;
12521            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12522                return null;
12523            }
12524            final PackageParser.Provider provider = info.provider;
12525            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12526            if (ps == null) {
12527                return null;
12528            }
12529            final PackageUserState userState = ps.readUserState(userId);
12530            final boolean matchVisibleToInstantApp =
12531                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12532            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12533            // throw out filters that aren't visible to instant applications
12534            if (matchVisibleToInstantApp
12535                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12536                return null;
12537            }
12538            // throw out instant application filters if we're not explicitly requesting them
12539            if (!isInstantApp && userState.instantApp) {
12540                return null;
12541            }
12542            // throw out instant application filters if updates are available; will trigger
12543            // instant application resolution
12544            if (userState.instantApp && ps.isUpdateAvailable()) {
12545                return null;
12546            }
12547            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12548                    userState, userId);
12549            if (pi == null) {
12550                return null;
12551            }
12552            final ResolveInfo res = new ResolveInfo();
12553            res.providerInfo = pi;
12554            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12555                res.filter = filter;
12556            }
12557            res.priority = info.getPriority();
12558            res.preferredOrder = provider.owner.mPreferredOrder;
12559            res.match = match;
12560            res.isDefault = info.hasDefault;
12561            res.labelRes = info.labelRes;
12562            res.nonLocalizedLabel = info.nonLocalizedLabel;
12563            res.icon = info.icon;
12564            res.system = res.providerInfo.applicationInfo.isSystemApp();
12565            return res;
12566        }
12567
12568        @Override
12569        protected void sortResults(List<ResolveInfo> results) {
12570            Collections.sort(results, mResolvePrioritySorter);
12571        }
12572
12573        @Override
12574        protected void dumpFilter(PrintWriter out, String prefix,
12575                PackageParser.ProviderIntentInfo filter) {
12576            out.print(prefix);
12577            out.print(
12578                    Integer.toHexString(System.identityHashCode(filter.provider)));
12579            out.print(' ');
12580            filter.provider.printComponentShortName(out);
12581            out.print(" filter ");
12582            out.println(Integer.toHexString(System.identityHashCode(filter)));
12583        }
12584
12585        @Override
12586        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12587            return filter.provider;
12588        }
12589
12590        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12591            PackageParser.Provider provider = (PackageParser.Provider)label;
12592            out.print(prefix); out.print(
12593                    Integer.toHexString(System.identityHashCode(provider)));
12594                    out.print(' ');
12595                    provider.printComponentShortName(out);
12596            if (count > 1) {
12597                out.print(" ("); out.print(count); out.print(" filters)");
12598            }
12599            out.println();
12600        }
12601
12602        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12603                = new ArrayMap<ComponentName, PackageParser.Provider>();
12604        private int mFlags;
12605    }
12606
12607    static final class EphemeralIntentResolver
12608            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12609        /**
12610         * The result that has the highest defined order. Ordering applies on a
12611         * per-package basis. Mapping is from package name to Pair of order and
12612         * EphemeralResolveInfo.
12613         * <p>
12614         * NOTE: This is implemented as a field variable for convenience and efficiency.
12615         * By having a field variable, we're able to track filter ordering as soon as
12616         * a non-zero order is defined. Otherwise, multiple loops across the result set
12617         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12618         * this needs to be contained entirely within {@link #filterResults}.
12619         */
12620        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12621
12622        @Override
12623        protected AuxiliaryResolveInfo[] newArray(int size) {
12624            return new AuxiliaryResolveInfo[size];
12625        }
12626
12627        @Override
12628        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12629            return true;
12630        }
12631
12632        @Override
12633        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12634                int userId) {
12635            if (!sUserManager.exists(userId)) {
12636                return null;
12637            }
12638            final String packageName = responseObj.resolveInfo.getPackageName();
12639            final Integer order = responseObj.getOrder();
12640            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12641                    mOrderResult.get(packageName);
12642            // ordering is enabled and this item's order isn't high enough
12643            if (lastOrderResult != null && lastOrderResult.first >= order) {
12644                return null;
12645            }
12646            final InstantAppResolveInfo res = responseObj.resolveInfo;
12647            if (order > 0) {
12648                // non-zero order, enable ordering
12649                mOrderResult.put(packageName, new Pair<>(order, res));
12650            }
12651            return responseObj;
12652        }
12653
12654        @Override
12655        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12656            // only do work if ordering is enabled [most of the time it won't be]
12657            if (mOrderResult.size() == 0) {
12658                return;
12659            }
12660            int resultSize = results.size();
12661            for (int i = 0; i < resultSize; i++) {
12662                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12663                final String packageName = info.getPackageName();
12664                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12665                if (savedInfo == null) {
12666                    // package doesn't having ordering
12667                    continue;
12668                }
12669                if (savedInfo.second == info) {
12670                    // circled back to the highest ordered item; remove from order list
12671                    mOrderResult.remove(packageName);
12672                    if (mOrderResult.size() == 0) {
12673                        // no more ordered items
12674                        break;
12675                    }
12676                    continue;
12677                }
12678                // item has a worse order, remove it from the result list
12679                results.remove(i);
12680                resultSize--;
12681                i--;
12682            }
12683        }
12684    }
12685
12686    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12687            new Comparator<ResolveInfo>() {
12688        public int compare(ResolveInfo r1, ResolveInfo r2) {
12689            int v1 = r1.priority;
12690            int v2 = r2.priority;
12691            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12692            if (v1 != v2) {
12693                return (v1 > v2) ? -1 : 1;
12694            }
12695            v1 = r1.preferredOrder;
12696            v2 = r2.preferredOrder;
12697            if (v1 != v2) {
12698                return (v1 > v2) ? -1 : 1;
12699            }
12700            if (r1.isDefault != r2.isDefault) {
12701                return r1.isDefault ? -1 : 1;
12702            }
12703            v1 = r1.match;
12704            v2 = r2.match;
12705            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12706            if (v1 != v2) {
12707                return (v1 > v2) ? -1 : 1;
12708            }
12709            if (r1.system != r2.system) {
12710                return r1.system ? -1 : 1;
12711            }
12712            if (r1.activityInfo != null) {
12713                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12714            }
12715            if (r1.serviceInfo != null) {
12716                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12717            }
12718            if (r1.providerInfo != null) {
12719                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12720            }
12721            return 0;
12722        }
12723    };
12724
12725    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12726            new Comparator<ProviderInfo>() {
12727        public int compare(ProviderInfo p1, ProviderInfo p2) {
12728            final int v1 = p1.initOrder;
12729            final int v2 = p2.initOrder;
12730            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12731        }
12732    };
12733
12734    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12735            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12736            final int[] userIds) {
12737        mHandler.post(new Runnable() {
12738            @Override
12739            public void run() {
12740                try {
12741                    final IActivityManager am = ActivityManager.getService();
12742                    if (am == null) return;
12743                    final int[] resolvedUserIds;
12744                    if (userIds == null) {
12745                        resolvedUserIds = am.getRunningUserIds();
12746                    } else {
12747                        resolvedUserIds = userIds;
12748                    }
12749                    for (int id : resolvedUserIds) {
12750                        final Intent intent = new Intent(action,
12751                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12752                        if (extras != null) {
12753                            intent.putExtras(extras);
12754                        }
12755                        if (targetPkg != null) {
12756                            intent.setPackage(targetPkg);
12757                        }
12758                        // Modify the UID when posting to other users
12759                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12760                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12761                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12762                            intent.putExtra(Intent.EXTRA_UID, uid);
12763                        }
12764                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12765                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12766                        if (DEBUG_BROADCASTS) {
12767                            RuntimeException here = new RuntimeException("here");
12768                            here.fillInStackTrace();
12769                            Slog.d(TAG, "Sending to user " + id + ": "
12770                                    + intent.toShortString(false, true, false, false)
12771                                    + " " + intent.getExtras(), here);
12772                        }
12773                        am.broadcastIntent(null, intent, null, finishedReceiver,
12774                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12775                                null, finishedReceiver != null, false, id);
12776                    }
12777                } catch (RemoteException ex) {
12778                }
12779            }
12780        });
12781    }
12782
12783    /**
12784     * Check if the external storage media is available. This is true if there
12785     * is a mounted external storage medium or if the external storage is
12786     * emulated.
12787     */
12788    private boolean isExternalMediaAvailable() {
12789        return mMediaMounted || Environment.isExternalStorageEmulated();
12790    }
12791
12792    @Override
12793    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12794        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
12795            return null;
12796        }
12797        // writer
12798        synchronized (mPackages) {
12799            if (!isExternalMediaAvailable()) {
12800                // If the external storage is no longer mounted at this point,
12801                // the caller may not have been able to delete all of this
12802                // packages files and can not delete any more.  Bail.
12803                return null;
12804            }
12805            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12806            if (lastPackage != null) {
12807                pkgs.remove(lastPackage);
12808            }
12809            if (pkgs.size() > 0) {
12810                return pkgs.get(0);
12811            }
12812        }
12813        return null;
12814    }
12815
12816    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12817        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12818                userId, andCode ? 1 : 0, packageName);
12819        if (mSystemReady) {
12820            msg.sendToTarget();
12821        } else {
12822            if (mPostSystemReadyMessages == null) {
12823                mPostSystemReadyMessages = new ArrayList<>();
12824            }
12825            mPostSystemReadyMessages.add(msg);
12826        }
12827    }
12828
12829    void startCleaningPackages() {
12830        // reader
12831        if (!isExternalMediaAvailable()) {
12832            return;
12833        }
12834        synchronized (mPackages) {
12835            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12836                return;
12837            }
12838        }
12839        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12840        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12841        IActivityManager am = ActivityManager.getService();
12842        if (am != null) {
12843            int dcsUid = -1;
12844            synchronized (mPackages) {
12845                if (!mDefaultContainerWhitelisted) {
12846                    mDefaultContainerWhitelisted = true;
12847                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
12848                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
12849                }
12850            }
12851            try {
12852                if (dcsUid > 0) {
12853                    am.backgroundWhitelistUid(dcsUid);
12854                }
12855                am.startService(null, intent, null, false, mContext.getOpPackageName(),
12856                        UserHandle.USER_SYSTEM);
12857            } catch (RemoteException e) {
12858            }
12859        }
12860    }
12861
12862    @Override
12863    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12864            int installFlags, String installerPackageName, int userId) {
12865        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12866
12867        final int callingUid = Binder.getCallingUid();
12868        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
12869                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12870
12871        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12872            try {
12873                if (observer != null) {
12874                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12875                }
12876            } catch (RemoteException re) {
12877            }
12878            return;
12879        }
12880
12881        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12882            installFlags |= PackageManager.INSTALL_FROM_ADB;
12883
12884        } else {
12885            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12886            // about installerPackageName.
12887
12888            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12889            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12890        }
12891
12892        UserHandle user;
12893        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12894            user = UserHandle.ALL;
12895        } else {
12896            user = new UserHandle(userId);
12897        }
12898
12899        // Only system components can circumvent runtime permissions when installing.
12900        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12901                && mContext.checkCallingOrSelfPermission(Manifest.permission
12902                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12903            throw new SecurityException("You need the "
12904                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12905                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12906        }
12907
12908        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12909                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12910            throw new IllegalArgumentException(
12911                    "New installs into ASEC containers no longer supported");
12912        }
12913
12914        final File originFile = new File(originPath);
12915        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12916
12917        final Message msg = mHandler.obtainMessage(INIT_COPY);
12918        final VerificationInfo verificationInfo = new VerificationInfo(
12919                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12920        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12921                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12922                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12923                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12924        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12925        msg.obj = params;
12926
12927        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12928                System.identityHashCode(msg.obj));
12929        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12930                System.identityHashCode(msg.obj));
12931
12932        mHandler.sendMessage(msg);
12933    }
12934
12935
12936    /**
12937     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12938     * it is acting on behalf on an enterprise or the user).
12939     *
12940     * Note that the ordering of the conditionals in this method is important. The checks we perform
12941     * are as follows, in this order:
12942     *
12943     * 1) If the install is being performed by a system app, we can trust the app to have set the
12944     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12945     *    what it is.
12946     * 2) If the install is being performed by a device or profile owner app, the install reason
12947     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12948     *    set the install reason correctly. If the app targets an older SDK version where install
12949     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12950     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12951     * 3) In all other cases, the install is being performed by a regular app that is neither part
12952     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12953     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12954     *    set to enterprise policy and if so, change it to unknown instead.
12955     */
12956    private int fixUpInstallReason(String installerPackageName, int installerUid,
12957            int installReason) {
12958        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12959                == PERMISSION_GRANTED) {
12960            // If the install is being performed by a system app, we trust that app to have set the
12961            // install reason correctly.
12962            return installReason;
12963        }
12964
12965        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12966            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12967        if (dpm != null) {
12968            ComponentName owner = null;
12969            try {
12970                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12971                if (owner == null) {
12972                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12973                }
12974            } catch (RemoteException e) {
12975            }
12976            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12977                // If the install is being performed by a device or profile owner, the install
12978                // reason should be enterprise policy.
12979                return PackageManager.INSTALL_REASON_POLICY;
12980            }
12981        }
12982
12983        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12984            // If the install is being performed by a regular app (i.e. neither system app nor
12985            // device or profile owner), we have no reason to believe that the app is acting on
12986            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12987            // change it to unknown instead.
12988            return PackageManager.INSTALL_REASON_UNKNOWN;
12989        }
12990
12991        // If the install is being performed by a regular app and the install reason was set to any
12992        // value but enterprise policy, leave the install reason unchanged.
12993        return installReason;
12994    }
12995
12996    void installStage(String packageName, File stagedDir,
12997            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12998            String installerPackageName, int installerUid, UserHandle user,
12999            Certificate[][] certificates) {
13000        if (DEBUG_EPHEMERAL) {
13001            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13002                Slog.d(TAG, "Ephemeral install of " + packageName);
13003            }
13004        }
13005        final VerificationInfo verificationInfo = new VerificationInfo(
13006                sessionParams.originatingUri, sessionParams.referrerUri,
13007                sessionParams.originatingUid, installerUid);
13008
13009        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13010
13011        final Message msg = mHandler.obtainMessage(INIT_COPY);
13012        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13013                sessionParams.installReason);
13014        final InstallParams params = new InstallParams(origin, null, observer,
13015                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13016                verificationInfo, user, sessionParams.abiOverride,
13017                sessionParams.grantedRuntimePermissions, certificates, installReason);
13018        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13019        msg.obj = params;
13020
13021        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13022                System.identityHashCode(msg.obj));
13023        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13024                System.identityHashCode(msg.obj));
13025
13026        mHandler.sendMessage(msg);
13027    }
13028
13029    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13030            int userId) {
13031        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13032        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13033                false /*startReceiver*/, pkgSetting.appId, userId);
13034
13035        // Send a session commit broadcast
13036        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13037        info.installReason = pkgSetting.getInstallReason(userId);
13038        info.appPackageName = packageName;
13039        sendSessionCommitBroadcast(info, userId);
13040    }
13041
13042    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13043            boolean includeStopped, int appId, int... userIds) {
13044        if (ArrayUtils.isEmpty(userIds)) {
13045            return;
13046        }
13047        Bundle extras = new Bundle(1);
13048        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13049        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13050
13051        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13052                packageName, extras, 0, null, null, userIds);
13053        if (sendBootCompleted) {
13054            mHandler.post(() -> {
13055                        for (int userId : userIds) {
13056                            sendBootCompletedBroadcastToSystemApp(
13057                                    packageName, includeStopped, userId);
13058                        }
13059                    }
13060            );
13061        }
13062    }
13063
13064    /**
13065     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13066     * automatically without needing an explicit launch.
13067     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13068     */
13069    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13070            int userId) {
13071        // If user is not running, the app didn't miss any broadcast
13072        if (!mUserManagerInternal.isUserRunning(userId)) {
13073            return;
13074        }
13075        final IActivityManager am = ActivityManager.getService();
13076        try {
13077            // Deliver LOCKED_BOOT_COMPLETED first
13078            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13079                    .setPackage(packageName);
13080            if (includeStopped) {
13081                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13082            }
13083            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13084            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13085                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13086
13087            // Deliver BOOT_COMPLETED only if user is unlocked
13088            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13089                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13090                if (includeStopped) {
13091                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13092                }
13093                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13094                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13095            }
13096        } catch (RemoteException e) {
13097            throw e.rethrowFromSystemServer();
13098        }
13099    }
13100
13101    @Override
13102    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13103            int userId) {
13104        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13105        PackageSetting pkgSetting;
13106        final int callingUid = Binder.getCallingUid();
13107        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13108                true /* requireFullPermission */, true /* checkShell */,
13109                "setApplicationHiddenSetting for user " + userId);
13110
13111        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13112            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13113            return false;
13114        }
13115
13116        long callingId = Binder.clearCallingIdentity();
13117        try {
13118            boolean sendAdded = false;
13119            boolean sendRemoved = false;
13120            // writer
13121            synchronized (mPackages) {
13122                pkgSetting = mSettings.mPackages.get(packageName);
13123                if (pkgSetting == null) {
13124                    return false;
13125                }
13126                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13127                    return false;
13128                }
13129                // Do not allow "android" is being disabled
13130                if ("android".equals(packageName)) {
13131                    Slog.w(TAG, "Cannot hide package: android");
13132                    return false;
13133                }
13134                // Cannot hide static shared libs as they are considered
13135                // a part of the using app (emulating static linking). Also
13136                // static libs are installed always on internal storage.
13137                PackageParser.Package pkg = mPackages.get(packageName);
13138                if (pkg != null && pkg.staticSharedLibName != null) {
13139                    Slog.w(TAG, "Cannot hide package: " + packageName
13140                            + " providing static shared library: "
13141                            + pkg.staticSharedLibName);
13142                    return false;
13143                }
13144                // Only allow protected packages to hide themselves.
13145                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13146                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13147                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13148                    return false;
13149                }
13150
13151                if (pkgSetting.getHidden(userId) != hidden) {
13152                    pkgSetting.setHidden(hidden, userId);
13153                    mSettings.writePackageRestrictionsLPr(userId);
13154                    if (hidden) {
13155                        sendRemoved = true;
13156                    } else {
13157                        sendAdded = true;
13158                    }
13159                }
13160            }
13161            if (sendAdded) {
13162                sendPackageAddedForUser(packageName, pkgSetting, userId);
13163                return true;
13164            }
13165            if (sendRemoved) {
13166                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13167                        "hiding pkg");
13168                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13169                return true;
13170            }
13171        } finally {
13172            Binder.restoreCallingIdentity(callingId);
13173        }
13174        return false;
13175    }
13176
13177    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13178            int userId) {
13179        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13180        info.removedPackage = packageName;
13181        info.installerPackageName = pkgSetting.installerPackageName;
13182        info.removedUsers = new int[] {userId};
13183        info.broadcastUsers = new int[] {userId};
13184        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13185        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13186    }
13187
13188    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13189        if (pkgList.length > 0) {
13190            Bundle extras = new Bundle(1);
13191            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13192
13193            sendPackageBroadcast(
13194                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13195                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13196                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13197                    new int[] {userId});
13198        }
13199    }
13200
13201    /**
13202     * Returns true if application is not found or there was an error. Otherwise it returns
13203     * the hidden state of the package for the given user.
13204     */
13205    @Override
13206    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13207        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13208        final int callingUid = Binder.getCallingUid();
13209        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13210                true /* requireFullPermission */, false /* checkShell */,
13211                "getApplicationHidden for user " + userId);
13212        PackageSetting ps;
13213        long callingId = Binder.clearCallingIdentity();
13214        try {
13215            // writer
13216            synchronized (mPackages) {
13217                ps = mSettings.mPackages.get(packageName);
13218                if (ps == null) {
13219                    return true;
13220                }
13221                if (filterAppAccessLPr(ps, callingUid, userId)) {
13222                    return true;
13223                }
13224                return ps.getHidden(userId);
13225            }
13226        } finally {
13227            Binder.restoreCallingIdentity(callingId);
13228        }
13229    }
13230
13231    /**
13232     * @hide
13233     */
13234    @Override
13235    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13236            int installReason) {
13237        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13238                null);
13239        PackageSetting pkgSetting;
13240        final int callingUid = Binder.getCallingUid();
13241        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13242                true /* requireFullPermission */, true /* checkShell */,
13243                "installExistingPackage for user " + userId);
13244        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13245            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13246        }
13247
13248        long callingId = Binder.clearCallingIdentity();
13249        try {
13250            boolean installed = false;
13251            final boolean instantApp =
13252                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13253            final boolean fullApp =
13254                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13255
13256            // writer
13257            synchronized (mPackages) {
13258                pkgSetting = mSettings.mPackages.get(packageName);
13259                if (pkgSetting == null) {
13260                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13261                }
13262                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13263                    // only allow the existing package to be used if it's installed as a full
13264                    // application for at least one user
13265                    boolean installAllowed = false;
13266                    for (int checkUserId : sUserManager.getUserIds()) {
13267                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13268                        if (installAllowed) {
13269                            break;
13270                        }
13271                    }
13272                    if (!installAllowed) {
13273                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13274                    }
13275                }
13276                if (!pkgSetting.getInstalled(userId)) {
13277                    pkgSetting.setInstalled(true, userId);
13278                    pkgSetting.setHidden(false, userId);
13279                    pkgSetting.setInstallReason(installReason, userId);
13280                    mSettings.writePackageRestrictionsLPr(userId);
13281                    mSettings.writeKernelMappingLPr(pkgSetting);
13282                    installed = true;
13283                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13284                    // upgrade app from instant to full; we don't allow app downgrade
13285                    installed = true;
13286                }
13287                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13288            }
13289
13290            if (installed) {
13291                if (pkgSetting.pkg != null) {
13292                    synchronized (mInstallLock) {
13293                        // We don't need to freeze for a brand new install
13294                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13295                    }
13296                }
13297                sendPackageAddedForUser(packageName, pkgSetting, userId);
13298                synchronized (mPackages) {
13299                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13300                }
13301            }
13302        } finally {
13303            Binder.restoreCallingIdentity(callingId);
13304        }
13305
13306        return PackageManager.INSTALL_SUCCEEDED;
13307    }
13308
13309    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13310            boolean instantApp, boolean fullApp) {
13311        // no state specified; do nothing
13312        if (!instantApp && !fullApp) {
13313            return;
13314        }
13315        if (userId != UserHandle.USER_ALL) {
13316            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13317                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13318            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13319                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13320            }
13321        } else {
13322            for (int currentUserId : sUserManager.getUserIds()) {
13323                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13324                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13325                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13326                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13327                }
13328            }
13329        }
13330    }
13331
13332    boolean isUserRestricted(int userId, String restrictionKey) {
13333        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13334        if (restrictions.getBoolean(restrictionKey, false)) {
13335            Log.w(TAG, "User is restricted: " + restrictionKey);
13336            return true;
13337        }
13338        return false;
13339    }
13340
13341    @Override
13342    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13343            int userId) {
13344        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13345        final int callingUid = Binder.getCallingUid();
13346        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13347                true /* requireFullPermission */, true /* checkShell */,
13348                "setPackagesSuspended for user " + userId);
13349
13350        if (ArrayUtils.isEmpty(packageNames)) {
13351            return packageNames;
13352        }
13353
13354        // List of package names for whom the suspended state has changed.
13355        List<String> changedPackages = new ArrayList<>(packageNames.length);
13356        // List of package names for whom the suspended state is not set as requested in this
13357        // method.
13358        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13359        long callingId = Binder.clearCallingIdentity();
13360        try {
13361            for (int i = 0; i < packageNames.length; i++) {
13362                String packageName = packageNames[i];
13363                boolean changed = false;
13364                final int appId;
13365                synchronized (mPackages) {
13366                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13367                    if (pkgSetting == null
13368                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13369                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13370                                + "\". Skipping suspending/un-suspending.");
13371                        unactionedPackages.add(packageName);
13372                        continue;
13373                    }
13374                    appId = pkgSetting.appId;
13375                    if (pkgSetting.getSuspended(userId) != suspended) {
13376                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13377                            unactionedPackages.add(packageName);
13378                            continue;
13379                        }
13380                        pkgSetting.setSuspended(suspended, userId);
13381                        mSettings.writePackageRestrictionsLPr(userId);
13382                        changed = true;
13383                        changedPackages.add(packageName);
13384                    }
13385                }
13386
13387                if (changed && suspended) {
13388                    killApplication(packageName, UserHandle.getUid(userId, appId),
13389                            "suspending package");
13390                }
13391            }
13392        } finally {
13393            Binder.restoreCallingIdentity(callingId);
13394        }
13395
13396        if (!changedPackages.isEmpty()) {
13397            sendPackagesSuspendedForUser(changedPackages.toArray(
13398                    new String[changedPackages.size()]), userId, suspended);
13399        }
13400
13401        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13402    }
13403
13404    @Override
13405    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13406        final int callingUid = Binder.getCallingUid();
13407        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13408                true /* requireFullPermission */, false /* checkShell */,
13409                "isPackageSuspendedForUser for user " + userId);
13410        synchronized (mPackages) {
13411            final PackageSetting ps = mSettings.mPackages.get(packageName);
13412            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13413                throw new IllegalArgumentException("Unknown target package: " + packageName);
13414            }
13415            return ps.getSuspended(userId);
13416        }
13417    }
13418
13419    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13420        if (isPackageDeviceAdmin(packageName, userId)) {
13421            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13422                    + "\": has an active device admin");
13423            return false;
13424        }
13425
13426        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13427        if (packageName.equals(activeLauncherPackageName)) {
13428            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13429                    + "\": contains the active launcher");
13430            return false;
13431        }
13432
13433        if (packageName.equals(mRequiredInstallerPackage)) {
13434            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13435                    + "\": required for package installation");
13436            return false;
13437        }
13438
13439        if (packageName.equals(mRequiredUninstallerPackage)) {
13440            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13441                    + "\": required for package uninstallation");
13442            return false;
13443        }
13444
13445        if (packageName.equals(mRequiredVerifierPackage)) {
13446            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13447                    + "\": required for package verification");
13448            return false;
13449        }
13450
13451        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13452            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13453                    + "\": is the default dialer");
13454            return false;
13455        }
13456
13457        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13458            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13459                    + "\": protected package");
13460            return false;
13461        }
13462
13463        // Cannot suspend static shared libs as they are considered
13464        // a part of the using app (emulating static linking). Also
13465        // static libs are installed always on internal storage.
13466        PackageParser.Package pkg = mPackages.get(packageName);
13467        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13468            Slog.w(TAG, "Cannot suspend package: " + packageName
13469                    + " providing static shared library: "
13470                    + pkg.staticSharedLibName);
13471            return false;
13472        }
13473
13474        return true;
13475    }
13476
13477    private String getActiveLauncherPackageName(int userId) {
13478        Intent intent = new Intent(Intent.ACTION_MAIN);
13479        intent.addCategory(Intent.CATEGORY_HOME);
13480        ResolveInfo resolveInfo = resolveIntent(
13481                intent,
13482                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13483                PackageManager.MATCH_DEFAULT_ONLY,
13484                userId);
13485
13486        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13487    }
13488
13489    private String getDefaultDialerPackageName(int userId) {
13490        synchronized (mPackages) {
13491            return mSettings.getDefaultDialerPackageNameLPw(userId);
13492        }
13493    }
13494
13495    @Override
13496    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13497        mContext.enforceCallingOrSelfPermission(
13498                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13499                "Only package verification agents can verify applications");
13500
13501        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13502        final PackageVerificationResponse response = new PackageVerificationResponse(
13503                verificationCode, Binder.getCallingUid());
13504        msg.arg1 = id;
13505        msg.obj = response;
13506        mHandler.sendMessage(msg);
13507    }
13508
13509    @Override
13510    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13511            long millisecondsToDelay) {
13512        mContext.enforceCallingOrSelfPermission(
13513                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13514                "Only package verification agents can extend verification timeouts");
13515
13516        final PackageVerificationState state = mPendingVerification.get(id);
13517        final PackageVerificationResponse response = new PackageVerificationResponse(
13518                verificationCodeAtTimeout, Binder.getCallingUid());
13519
13520        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13521            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13522        }
13523        if (millisecondsToDelay < 0) {
13524            millisecondsToDelay = 0;
13525        }
13526        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13527                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13528            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13529        }
13530
13531        if ((state != null) && !state.timeoutExtended()) {
13532            state.extendTimeout();
13533
13534            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13535            msg.arg1 = id;
13536            msg.obj = response;
13537            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13538        }
13539    }
13540
13541    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13542            int verificationCode, UserHandle user) {
13543        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13544        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13545        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13546        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13547        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13548
13549        mContext.sendBroadcastAsUser(intent, user,
13550                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13551    }
13552
13553    private ComponentName matchComponentForVerifier(String packageName,
13554            List<ResolveInfo> receivers) {
13555        ActivityInfo targetReceiver = null;
13556
13557        final int NR = receivers.size();
13558        for (int i = 0; i < NR; i++) {
13559            final ResolveInfo info = receivers.get(i);
13560            if (info.activityInfo == null) {
13561                continue;
13562            }
13563
13564            if (packageName.equals(info.activityInfo.packageName)) {
13565                targetReceiver = info.activityInfo;
13566                break;
13567            }
13568        }
13569
13570        if (targetReceiver == null) {
13571            return null;
13572        }
13573
13574        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13575    }
13576
13577    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13578            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13579        if (pkgInfo.verifiers.length == 0) {
13580            return null;
13581        }
13582
13583        final int N = pkgInfo.verifiers.length;
13584        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13585        for (int i = 0; i < N; i++) {
13586            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13587
13588            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13589                    receivers);
13590            if (comp == null) {
13591                continue;
13592            }
13593
13594            final int verifierUid = getUidForVerifier(verifierInfo);
13595            if (verifierUid == -1) {
13596                continue;
13597            }
13598
13599            if (DEBUG_VERIFY) {
13600                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13601                        + " with the correct signature");
13602            }
13603            sufficientVerifiers.add(comp);
13604            verificationState.addSufficientVerifier(verifierUid);
13605        }
13606
13607        return sufficientVerifiers;
13608    }
13609
13610    private int getUidForVerifier(VerifierInfo verifierInfo) {
13611        synchronized (mPackages) {
13612            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13613            if (pkg == null) {
13614                return -1;
13615            } else if (pkg.mSignatures.length != 1) {
13616                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13617                        + " has more than one signature; ignoring");
13618                return -1;
13619            }
13620
13621            /*
13622             * If the public key of the package's signature does not match
13623             * our expected public key, then this is a different package and
13624             * we should skip.
13625             */
13626
13627            final byte[] expectedPublicKey;
13628            try {
13629                final Signature verifierSig = pkg.mSignatures[0];
13630                final PublicKey publicKey = verifierSig.getPublicKey();
13631                expectedPublicKey = publicKey.getEncoded();
13632            } catch (CertificateException e) {
13633                return -1;
13634            }
13635
13636            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13637
13638            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13639                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13640                        + " does not have the expected public key; ignoring");
13641                return -1;
13642            }
13643
13644            return pkg.applicationInfo.uid;
13645        }
13646    }
13647
13648    @Override
13649    public void finishPackageInstall(int token, boolean didLaunch) {
13650        enforceSystemOrRoot("Only the system is allowed to finish installs");
13651
13652        if (DEBUG_INSTALL) {
13653            Slog.v(TAG, "BM finishing package install for " + token);
13654        }
13655        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13656
13657        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13658        mHandler.sendMessage(msg);
13659    }
13660
13661    /**
13662     * Get the verification agent timeout.  Used for both the APK verifier and the
13663     * intent filter verifier.
13664     *
13665     * @return verification timeout in milliseconds
13666     */
13667    private long getVerificationTimeout() {
13668        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13669                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13670                DEFAULT_VERIFICATION_TIMEOUT);
13671    }
13672
13673    /**
13674     * Get the default verification agent response code.
13675     *
13676     * @return default verification response code
13677     */
13678    private int getDefaultVerificationResponse(UserHandle user) {
13679        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13680            return PackageManager.VERIFICATION_REJECT;
13681        }
13682        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13683                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13684                DEFAULT_VERIFICATION_RESPONSE);
13685    }
13686
13687    /**
13688     * Check whether or not package verification has been enabled.
13689     *
13690     * @return true if verification should be performed
13691     */
13692    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13693        if (!DEFAULT_VERIFY_ENABLE) {
13694            return false;
13695        }
13696
13697        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13698
13699        // Check if installing from ADB
13700        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13701            // Do not run verification in a test harness environment
13702            if (ActivityManager.isRunningInTestHarness()) {
13703                return false;
13704            }
13705            if (ensureVerifyAppsEnabled) {
13706                return true;
13707            }
13708            // Check if the developer does not want package verification for ADB installs
13709            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13710                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13711                return false;
13712            }
13713        } else {
13714            // only when not installed from ADB, skip verification for instant apps when
13715            // the installer and verifier are the same.
13716            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13717                if (mInstantAppInstallerActivity != null
13718                        && mInstantAppInstallerActivity.packageName.equals(
13719                                mRequiredVerifierPackage)) {
13720                    try {
13721                        mContext.getSystemService(AppOpsManager.class)
13722                                .checkPackage(installerUid, mRequiredVerifierPackage);
13723                        if (DEBUG_VERIFY) {
13724                            Slog.i(TAG, "disable verification for instant app");
13725                        }
13726                        return false;
13727                    } catch (SecurityException ignore) { }
13728                }
13729            }
13730        }
13731
13732        if (ensureVerifyAppsEnabled) {
13733            return true;
13734        }
13735
13736        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13737                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13738    }
13739
13740    @Override
13741    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13742            throws RemoteException {
13743        mContext.enforceCallingOrSelfPermission(
13744                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13745                "Only intentfilter verification agents can verify applications");
13746
13747        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13748        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13749                Binder.getCallingUid(), verificationCode, failedDomains);
13750        msg.arg1 = id;
13751        msg.obj = response;
13752        mHandler.sendMessage(msg);
13753    }
13754
13755    @Override
13756    public int getIntentVerificationStatus(String packageName, int userId) {
13757        final int callingUid = Binder.getCallingUid();
13758        if (UserHandle.getUserId(callingUid) != userId) {
13759            mContext.enforceCallingOrSelfPermission(
13760                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13761                    "getIntentVerificationStatus" + userId);
13762        }
13763        if (getInstantAppPackageName(callingUid) != null) {
13764            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13765        }
13766        synchronized (mPackages) {
13767            final PackageSetting ps = mSettings.mPackages.get(packageName);
13768            if (ps == null
13769                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13770                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13771            }
13772            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13773        }
13774    }
13775
13776    @Override
13777    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13778        mContext.enforceCallingOrSelfPermission(
13779                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13780
13781        boolean result = false;
13782        synchronized (mPackages) {
13783            final PackageSetting ps = mSettings.mPackages.get(packageName);
13784            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13785                return false;
13786            }
13787            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13788        }
13789        if (result) {
13790            scheduleWritePackageRestrictionsLocked(userId);
13791        }
13792        return result;
13793    }
13794
13795    @Override
13796    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13797            String packageName) {
13798        final int callingUid = Binder.getCallingUid();
13799        if (getInstantAppPackageName(callingUid) != null) {
13800            return ParceledListSlice.emptyList();
13801        }
13802        synchronized (mPackages) {
13803            final PackageSetting ps = mSettings.mPackages.get(packageName);
13804            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13805                return ParceledListSlice.emptyList();
13806            }
13807            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13808        }
13809    }
13810
13811    @Override
13812    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13813        if (TextUtils.isEmpty(packageName)) {
13814            return ParceledListSlice.emptyList();
13815        }
13816        final int callingUid = Binder.getCallingUid();
13817        final int callingUserId = UserHandle.getUserId(callingUid);
13818        synchronized (mPackages) {
13819            PackageParser.Package pkg = mPackages.get(packageName);
13820            if (pkg == null || pkg.activities == null) {
13821                return ParceledListSlice.emptyList();
13822            }
13823            if (pkg.mExtras == null) {
13824                return ParceledListSlice.emptyList();
13825            }
13826            final PackageSetting ps = (PackageSetting) pkg.mExtras;
13827            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
13828                return ParceledListSlice.emptyList();
13829            }
13830            final int count = pkg.activities.size();
13831            ArrayList<IntentFilter> result = new ArrayList<>();
13832            for (int n=0; n<count; n++) {
13833                PackageParser.Activity activity = pkg.activities.get(n);
13834                if (activity.intents != null && activity.intents.size() > 0) {
13835                    result.addAll(activity.intents);
13836                }
13837            }
13838            return new ParceledListSlice<>(result);
13839        }
13840    }
13841
13842    @Override
13843    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13844        mContext.enforceCallingOrSelfPermission(
13845                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13846        if (UserHandle.getCallingUserId() != userId) {
13847            mContext.enforceCallingOrSelfPermission(
13848                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13849        }
13850
13851        synchronized (mPackages) {
13852            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13853            if (packageName != null) {
13854                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
13855                        packageName, userId);
13856            }
13857            return result;
13858        }
13859    }
13860
13861    @Override
13862    public String getDefaultBrowserPackageName(int userId) {
13863        if (UserHandle.getCallingUserId() != userId) {
13864            mContext.enforceCallingOrSelfPermission(
13865                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13866        }
13867        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13868            return null;
13869        }
13870        synchronized (mPackages) {
13871            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13872        }
13873    }
13874
13875    /**
13876     * Get the "allow unknown sources" setting.
13877     *
13878     * @return the current "allow unknown sources" setting
13879     */
13880    private int getUnknownSourcesSettings() {
13881        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13882                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13883                -1);
13884    }
13885
13886    @Override
13887    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13888        final int callingUid = Binder.getCallingUid();
13889        if (getInstantAppPackageName(callingUid) != null) {
13890            return;
13891        }
13892        // writer
13893        synchronized (mPackages) {
13894            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13895            if (targetPackageSetting == null
13896                    || filterAppAccessLPr(
13897                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
13898                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13899            }
13900
13901            PackageSetting installerPackageSetting;
13902            if (installerPackageName != null) {
13903                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13904                if (installerPackageSetting == null) {
13905                    throw new IllegalArgumentException("Unknown installer package: "
13906                            + installerPackageName);
13907                }
13908            } else {
13909                installerPackageSetting = null;
13910            }
13911
13912            Signature[] callerSignature;
13913            Object obj = mSettings.getUserIdLPr(callingUid);
13914            if (obj != null) {
13915                if (obj instanceof SharedUserSetting) {
13916                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13917                } else if (obj instanceof PackageSetting) {
13918                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13919                } else {
13920                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
13921                }
13922            } else {
13923                throw new SecurityException("Unknown calling UID: " + callingUid);
13924            }
13925
13926            // Verify: can't set installerPackageName to a package that is
13927            // not signed with the same cert as the caller.
13928            if (installerPackageSetting != null) {
13929                if (compareSignatures(callerSignature,
13930                        installerPackageSetting.signatures.mSignatures)
13931                        != PackageManager.SIGNATURE_MATCH) {
13932                    throw new SecurityException(
13933                            "Caller does not have same cert as new installer package "
13934                            + installerPackageName);
13935                }
13936            }
13937
13938            // Verify: if target already has an installer package, it must
13939            // be signed with the same cert as the caller.
13940            if (targetPackageSetting.installerPackageName != null) {
13941                PackageSetting setting = mSettings.mPackages.get(
13942                        targetPackageSetting.installerPackageName);
13943                // If the currently set package isn't valid, then it's always
13944                // okay to change it.
13945                if (setting != null) {
13946                    if (compareSignatures(callerSignature,
13947                            setting.signatures.mSignatures)
13948                            != PackageManager.SIGNATURE_MATCH) {
13949                        throw new SecurityException(
13950                                "Caller does not have same cert as old installer package "
13951                                + targetPackageSetting.installerPackageName);
13952                    }
13953                }
13954            }
13955
13956            // Okay!
13957            targetPackageSetting.installerPackageName = installerPackageName;
13958            if (installerPackageName != null) {
13959                mSettings.mInstallerPackages.add(installerPackageName);
13960            }
13961            scheduleWriteSettingsLocked();
13962        }
13963    }
13964
13965    @Override
13966    public void setApplicationCategoryHint(String packageName, int categoryHint,
13967            String callerPackageName) {
13968        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13969            throw new SecurityException("Instant applications don't have access to this method");
13970        }
13971        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13972                callerPackageName);
13973        synchronized (mPackages) {
13974            PackageSetting ps = mSettings.mPackages.get(packageName);
13975            if (ps == null) {
13976                throw new IllegalArgumentException("Unknown target package " + packageName);
13977            }
13978            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13979                throw new IllegalArgumentException("Unknown target package " + packageName);
13980            }
13981            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13982                throw new IllegalArgumentException("Calling package " + callerPackageName
13983                        + " is not installer for " + packageName);
13984            }
13985
13986            if (ps.categoryHint != categoryHint) {
13987                ps.categoryHint = categoryHint;
13988                scheduleWriteSettingsLocked();
13989            }
13990        }
13991    }
13992
13993    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13994        // Queue up an async operation since the package installation may take a little while.
13995        mHandler.post(new Runnable() {
13996            public void run() {
13997                mHandler.removeCallbacks(this);
13998                 // Result object to be returned
13999                PackageInstalledInfo res = new PackageInstalledInfo();
14000                res.setReturnCode(currentStatus);
14001                res.uid = -1;
14002                res.pkg = null;
14003                res.removedInfo = null;
14004                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14005                    args.doPreInstall(res.returnCode);
14006                    synchronized (mInstallLock) {
14007                        installPackageTracedLI(args, res);
14008                    }
14009                    args.doPostInstall(res.returnCode, res.uid);
14010                }
14011
14012                // A restore should be performed at this point if (a) the install
14013                // succeeded, (b) the operation is not an update, and (c) the new
14014                // package has not opted out of backup participation.
14015                final boolean update = res.removedInfo != null
14016                        && res.removedInfo.removedPackage != null;
14017                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14018                boolean doRestore = !update
14019                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14020
14021                // Set up the post-install work request bookkeeping.  This will be used
14022                // and cleaned up by the post-install event handling regardless of whether
14023                // there's a restore pass performed.  Token values are >= 1.
14024                int token;
14025                if (mNextInstallToken < 0) mNextInstallToken = 1;
14026                token = mNextInstallToken++;
14027
14028                PostInstallData data = new PostInstallData(args, res);
14029                mRunningInstalls.put(token, data);
14030                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14031
14032                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14033                    // Pass responsibility to the Backup Manager.  It will perform a
14034                    // restore if appropriate, then pass responsibility back to the
14035                    // Package Manager to run the post-install observer callbacks
14036                    // and broadcasts.
14037                    IBackupManager bm = IBackupManager.Stub.asInterface(
14038                            ServiceManager.getService(Context.BACKUP_SERVICE));
14039                    if (bm != null) {
14040                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14041                                + " to BM for possible restore");
14042                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14043                        try {
14044                            // TODO: http://b/22388012
14045                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14046                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14047                            } else {
14048                                doRestore = false;
14049                            }
14050                        } catch (RemoteException e) {
14051                            // can't happen; the backup manager is local
14052                        } catch (Exception e) {
14053                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14054                            doRestore = false;
14055                        }
14056                    } else {
14057                        Slog.e(TAG, "Backup Manager not found!");
14058                        doRestore = false;
14059                    }
14060                }
14061
14062                if (!doRestore) {
14063                    // No restore possible, or the Backup Manager was mysteriously not
14064                    // available -- just fire the post-install work request directly.
14065                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14066
14067                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14068
14069                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14070                    mHandler.sendMessage(msg);
14071                }
14072            }
14073        });
14074    }
14075
14076    /**
14077     * Callback from PackageSettings whenever an app is first transitioned out of the
14078     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14079     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14080     * here whether the app is the target of an ongoing install, and only send the
14081     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14082     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14083     * handling.
14084     */
14085    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14086        // Serialize this with the rest of the install-process message chain.  In the
14087        // restore-at-install case, this Runnable will necessarily run before the
14088        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14089        // are coherent.  In the non-restore case, the app has already completed install
14090        // and been launched through some other means, so it is not in a problematic
14091        // state for observers to see the FIRST_LAUNCH signal.
14092        mHandler.post(new Runnable() {
14093            @Override
14094            public void run() {
14095                for (int i = 0; i < mRunningInstalls.size(); i++) {
14096                    final PostInstallData data = mRunningInstalls.valueAt(i);
14097                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14098                        continue;
14099                    }
14100                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14101                        // right package; but is it for the right user?
14102                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14103                            if (userId == data.res.newUsers[uIndex]) {
14104                                if (DEBUG_BACKUP) {
14105                                    Slog.i(TAG, "Package " + pkgName
14106                                            + " being restored so deferring FIRST_LAUNCH");
14107                                }
14108                                return;
14109                            }
14110                        }
14111                    }
14112                }
14113                // didn't find it, so not being restored
14114                if (DEBUG_BACKUP) {
14115                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14116                }
14117                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14118            }
14119        });
14120    }
14121
14122    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14123        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14124                installerPkg, null, userIds);
14125    }
14126
14127    private abstract class HandlerParams {
14128        private static final int MAX_RETRIES = 4;
14129
14130        /**
14131         * Number of times startCopy() has been attempted and had a non-fatal
14132         * error.
14133         */
14134        private int mRetries = 0;
14135
14136        /** User handle for the user requesting the information or installation. */
14137        private final UserHandle mUser;
14138        String traceMethod;
14139        int traceCookie;
14140
14141        HandlerParams(UserHandle user) {
14142            mUser = user;
14143        }
14144
14145        UserHandle getUser() {
14146            return mUser;
14147        }
14148
14149        HandlerParams setTraceMethod(String traceMethod) {
14150            this.traceMethod = traceMethod;
14151            return this;
14152        }
14153
14154        HandlerParams setTraceCookie(int traceCookie) {
14155            this.traceCookie = traceCookie;
14156            return this;
14157        }
14158
14159        final boolean startCopy() {
14160            boolean res;
14161            try {
14162                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14163
14164                if (++mRetries > MAX_RETRIES) {
14165                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14166                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14167                    handleServiceError();
14168                    return false;
14169                } else {
14170                    handleStartCopy();
14171                    res = true;
14172                }
14173            } catch (RemoteException e) {
14174                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14175                mHandler.sendEmptyMessage(MCS_RECONNECT);
14176                res = false;
14177            }
14178            handleReturnCode();
14179            return res;
14180        }
14181
14182        final void serviceError() {
14183            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14184            handleServiceError();
14185            handleReturnCode();
14186        }
14187
14188        abstract void handleStartCopy() throws RemoteException;
14189        abstract void handleServiceError();
14190        abstract void handleReturnCode();
14191    }
14192
14193    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14194        for (File path : paths) {
14195            try {
14196                mcs.clearDirectory(path.getAbsolutePath());
14197            } catch (RemoteException e) {
14198            }
14199        }
14200    }
14201
14202    static class OriginInfo {
14203        /**
14204         * Location where install is coming from, before it has been
14205         * copied/renamed into place. This could be a single monolithic APK
14206         * file, or a cluster directory. This location may be untrusted.
14207         */
14208        final File file;
14209
14210        /**
14211         * Flag indicating that {@link #file} or {@link #cid} has already been
14212         * staged, meaning downstream users don't need to defensively copy the
14213         * contents.
14214         */
14215        final boolean staged;
14216
14217        /**
14218         * Flag indicating that {@link #file} or {@link #cid} is an already
14219         * installed app that is being moved.
14220         */
14221        final boolean existing;
14222
14223        final String resolvedPath;
14224        final File resolvedFile;
14225
14226        static OriginInfo fromNothing() {
14227            return new OriginInfo(null, false, false);
14228        }
14229
14230        static OriginInfo fromUntrustedFile(File file) {
14231            return new OriginInfo(file, false, false);
14232        }
14233
14234        static OriginInfo fromExistingFile(File file) {
14235            return new OriginInfo(file, false, true);
14236        }
14237
14238        static OriginInfo fromStagedFile(File file) {
14239            return new OriginInfo(file, true, false);
14240        }
14241
14242        private OriginInfo(File file, boolean staged, boolean existing) {
14243            this.file = file;
14244            this.staged = staged;
14245            this.existing = existing;
14246
14247            if (file != null) {
14248                resolvedPath = file.getAbsolutePath();
14249                resolvedFile = file;
14250            } else {
14251                resolvedPath = null;
14252                resolvedFile = null;
14253            }
14254        }
14255    }
14256
14257    static class MoveInfo {
14258        final int moveId;
14259        final String fromUuid;
14260        final String toUuid;
14261        final String packageName;
14262        final String dataAppName;
14263        final int appId;
14264        final String seinfo;
14265        final int targetSdkVersion;
14266
14267        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14268                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14269            this.moveId = moveId;
14270            this.fromUuid = fromUuid;
14271            this.toUuid = toUuid;
14272            this.packageName = packageName;
14273            this.dataAppName = dataAppName;
14274            this.appId = appId;
14275            this.seinfo = seinfo;
14276            this.targetSdkVersion = targetSdkVersion;
14277        }
14278    }
14279
14280    static class VerificationInfo {
14281        /** A constant used to indicate that a uid value is not present. */
14282        public static final int NO_UID = -1;
14283
14284        /** URI referencing where the package was downloaded from. */
14285        final Uri originatingUri;
14286
14287        /** HTTP referrer URI associated with the originatingURI. */
14288        final Uri referrer;
14289
14290        /** UID of the application that the install request originated from. */
14291        final int originatingUid;
14292
14293        /** UID of application requesting the install */
14294        final int installerUid;
14295
14296        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14297            this.originatingUri = originatingUri;
14298            this.referrer = referrer;
14299            this.originatingUid = originatingUid;
14300            this.installerUid = installerUid;
14301        }
14302    }
14303
14304    class InstallParams extends HandlerParams {
14305        final OriginInfo origin;
14306        final MoveInfo move;
14307        final IPackageInstallObserver2 observer;
14308        int installFlags;
14309        final String installerPackageName;
14310        final String volumeUuid;
14311        private InstallArgs mArgs;
14312        private int mRet;
14313        final String packageAbiOverride;
14314        final String[] grantedRuntimePermissions;
14315        final VerificationInfo verificationInfo;
14316        final Certificate[][] certificates;
14317        final int installReason;
14318
14319        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14320                int installFlags, String installerPackageName, String volumeUuid,
14321                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14322                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14323            super(user);
14324            this.origin = origin;
14325            this.move = move;
14326            this.observer = observer;
14327            this.installFlags = installFlags;
14328            this.installerPackageName = installerPackageName;
14329            this.volumeUuid = volumeUuid;
14330            this.verificationInfo = verificationInfo;
14331            this.packageAbiOverride = packageAbiOverride;
14332            this.grantedRuntimePermissions = grantedPermissions;
14333            this.certificates = certificates;
14334            this.installReason = installReason;
14335        }
14336
14337        @Override
14338        public String toString() {
14339            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14340                    + " file=" + origin.file + "}";
14341        }
14342
14343        private int installLocationPolicy(PackageInfoLite pkgLite) {
14344            String packageName = pkgLite.packageName;
14345            int installLocation = pkgLite.installLocation;
14346            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14347            // reader
14348            synchronized (mPackages) {
14349                // Currently installed package which the new package is attempting to replace or
14350                // null if no such package is installed.
14351                PackageParser.Package installedPkg = mPackages.get(packageName);
14352                // Package which currently owns the data which the new package will own if installed.
14353                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14354                // will be null whereas dataOwnerPkg will contain information about the package
14355                // which was uninstalled while keeping its data.
14356                PackageParser.Package dataOwnerPkg = installedPkg;
14357                if (dataOwnerPkg  == null) {
14358                    PackageSetting ps = mSettings.mPackages.get(packageName);
14359                    if (ps != null) {
14360                        dataOwnerPkg = ps.pkg;
14361                    }
14362                }
14363
14364                if (dataOwnerPkg != null) {
14365                    // If installed, the package will get access to data left on the device by its
14366                    // predecessor. As a security measure, this is permited only if this is not a
14367                    // version downgrade or if the predecessor package is marked as debuggable and
14368                    // a downgrade is explicitly requested.
14369                    //
14370                    // On debuggable platform builds, downgrades are permitted even for
14371                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14372                    // not offer security guarantees and thus it's OK to disable some security
14373                    // mechanisms to make debugging/testing easier on those builds. However, even on
14374                    // debuggable builds downgrades of packages are permitted only if requested via
14375                    // installFlags. This is because we aim to keep the behavior of debuggable
14376                    // platform builds as close as possible to the behavior of non-debuggable
14377                    // platform builds.
14378                    final boolean downgradeRequested =
14379                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14380                    final boolean packageDebuggable =
14381                                (dataOwnerPkg.applicationInfo.flags
14382                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14383                    final boolean downgradePermitted =
14384                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14385                    if (!downgradePermitted) {
14386                        try {
14387                            checkDowngrade(dataOwnerPkg, pkgLite);
14388                        } catch (PackageManagerException e) {
14389                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14390                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14391                        }
14392                    }
14393                }
14394
14395                if (installedPkg != null) {
14396                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14397                        // Check for updated system application.
14398                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14399                            if (onSd) {
14400                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14401                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14402                            }
14403                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14404                        } else {
14405                            if (onSd) {
14406                                // Install flag overrides everything.
14407                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14408                            }
14409                            // If current upgrade specifies particular preference
14410                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14411                                // Application explicitly specified internal.
14412                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14413                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14414                                // App explictly prefers external. Let policy decide
14415                            } else {
14416                                // Prefer previous location
14417                                if (isExternal(installedPkg)) {
14418                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14419                                }
14420                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14421                            }
14422                        }
14423                    } else {
14424                        // Invalid install. Return error code
14425                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14426                    }
14427                }
14428            }
14429            // All the special cases have been taken care of.
14430            // Return result based on recommended install location.
14431            if (onSd) {
14432                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14433            }
14434            return pkgLite.recommendedInstallLocation;
14435        }
14436
14437        /*
14438         * Invoke remote method to get package information and install
14439         * location values. Override install location based on default
14440         * policy if needed and then create install arguments based
14441         * on the install location.
14442         */
14443        public void handleStartCopy() throws RemoteException {
14444            int ret = PackageManager.INSTALL_SUCCEEDED;
14445
14446            // If we're already staged, we've firmly committed to an install location
14447            if (origin.staged) {
14448                if (origin.file != null) {
14449                    installFlags |= PackageManager.INSTALL_INTERNAL;
14450                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14451                } else {
14452                    throw new IllegalStateException("Invalid stage location");
14453                }
14454            }
14455
14456            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14457            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14458            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14459            PackageInfoLite pkgLite = null;
14460
14461            if (onInt && onSd) {
14462                // Check if both bits are set.
14463                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14464                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14465            } else if (onSd && ephemeral) {
14466                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14467                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14468            } else {
14469                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14470                        packageAbiOverride);
14471
14472                if (DEBUG_EPHEMERAL && ephemeral) {
14473                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14474                }
14475
14476                /*
14477                 * If we have too little free space, try to free cache
14478                 * before giving up.
14479                 */
14480                if (!origin.staged && pkgLite.recommendedInstallLocation
14481                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14482                    // TODO: focus freeing disk space on the target device
14483                    final StorageManager storage = StorageManager.from(mContext);
14484                    final long lowThreshold = storage.getStorageLowBytes(
14485                            Environment.getDataDirectory());
14486
14487                    final long sizeBytes = mContainerService.calculateInstalledSize(
14488                            origin.resolvedPath, packageAbiOverride);
14489
14490                    try {
14491                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14492                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14493                                installFlags, packageAbiOverride);
14494                    } catch (InstallerException e) {
14495                        Slog.w(TAG, "Failed to free cache", e);
14496                    }
14497
14498                    /*
14499                     * The cache free must have deleted the file we
14500                     * downloaded to install.
14501                     *
14502                     * TODO: fix the "freeCache" call to not delete
14503                     *       the file we care about.
14504                     */
14505                    if (pkgLite.recommendedInstallLocation
14506                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14507                        pkgLite.recommendedInstallLocation
14508                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14509                    }
14510                }
14511            }
14512
14513            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14514                int loc = pkgLite.recommendedInstallLocation;
14515                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14516                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14517                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14518                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14519                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14520                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14521                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14522                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14523                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14524                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14525                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14526                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14527                } else {
14528                    // Override with defaults if needed.
14529                    loc = installLocationPolicy(pkgLite);
14530                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14531                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14532                    } else if (!onSd && !onInt) {
14533                        // Override install location with flags
14534                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14535                            // Set the flag to install on external media.
14536                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14537                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14538                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14539                            if (DEBUG_EPHEMERAL) {
14540                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14541                            }
14542                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14543                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14544                                    |PackageManager.INSTALL_INTERNAL);
14545                        } else {
14546                            // Make sure the flag for installing on external
14547                            // media is unset
14548                            installFlags |= PackageManager.INSTALL_INTERNAL;
14549                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14550                        }
14551                    }
14552                }
14553            }
14554
14555            final InstallArgs args = createInstallArgs(this);
14556            mArgs = args;
14557
14558            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14559                // TODO: http://b/22976637
14560                // Apps installed for "all" users use the device owner to verify the app
14561                UserHandle verifierUser = getUser();
14562                if (verifierUser == UserHandle.ALL) {
14563                    verifierUser = UserHandle.SYSTEM;
14564                }
14565
14566                /*
14567                 * Determine if we have any installed package verifiers. If we
14568                 * do, then we'll defer to them to verify the packages.
14569                 */
14570                final int requiredUid = mRequiredVerifierPackage == null ? -1
14571                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14572                                verifierUser.getIdentifier());
14573                final int installerUid =
14574                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14575                if (!origin.existing && requiredUid != -1
14576                        && isVerificationEnabled(
14577                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14578                    final Intent verification = new Intent(
14579                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14580                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14581                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14582                            PACKAGE_MIME_TYPE);
14583                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14584
14585                    // Query all live verifiers based on current user state
14586                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14587                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14588                            false /*allowDynamicSplits*/);
14589
14590                    if (DEBUG_VERIFY) {
14591                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14592                                + verification.toString() + " with " + pkgLite.verifiers.length
14593                                + " optional verifiers");
14594                    }
14595
14596                    final int verificationId = mPendingVerificationToken++;
14597
14598                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14599
14600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14601                            installerPackageName);
14602
14603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14604                            installFlags);
14605
14606                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14607                            pkgLite.packageName);
14608
14609                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14610                            pkgLite.versionCode);
14611
14612                    if (verificationInfo != null) {
14613                        if (verificationInfo.originatingUri != null) {
14614                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14615                                    verificationInfo.originatingUri);
14616                        }
14617                        if (verificationInfo.referrer != null) {
14618                            verification.putExtra(Intent.EXTRA_REFERRER,
14619                                    verificationInfo.referrer);
14620                        }
14621                        if (verificationInfo.originatingUid >= 0) {
14622                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14623                                    verificationInfo.originatingUid);
14624                        }
14625                        if (verificationInfo.installerUid >= 0) {
14626                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14627                                    verificationInfo.installerUid);
14628                        }
14629                    }
14630
14631                    final PackageVerificationState verificationState = new PackageVerificationState(
14632                            requiredUid, args);
14633
14634                    mPendingVerification.append(verificationId, verificationState);
14635
14636                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14637                            receivers, verificationState);
14638
14639                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14640                    final long idleDuration = getVerificationTimeout();
14641
14642                    /*
14643                     * If any sufficient verifiers were listed in the package
14644                     * manifest, attempt to ask them.
14645                     */
14646                    if (sufficientVerifiers != null) {
14647                        final int N = sufficientVerifiers.size();
14648                        if (N == 0) {
14649                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14650                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14651                        } else {
14652                            for (int i = 0; i < N; i++) {
14653                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14654                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14655                                        verifierComponent.getPackageName(), idleDuration,
14656                                        verifierUser.getIdentifier(), false, "package verifier");
14657
14658                                final Intent sufficientIntent = new Intent(verification);
14659                                sufficientIntent.setComponent(verifierComponent);
14660                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14661                            }
14662                        }
14663                    }
14664
14665                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14666                            mRequiredVerifierPackage, receivers);
14667                    if (ret == PackageManager.INSTALL_SUCCEEDED
14668                            && mRequiredVerifierPackage != null) {
14669                        Trace.asyncTraceBegin(
14670                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14671                        /*
14672                         * Send the intent to the required verification agent,
14673                         * but only start the verification timeout after the
14674                         * target BroadcastReceivers have run.
14675                         */
14676                        verification.setComponent(requiredVerifierComponent);
14677                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14678                                mRequiredVerifierPackage, idleDuration,
14679                                verifierUser.getIdentifier(), false, "package verifier");
14680                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14681                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14682                                new BroadcastReceiver() {
14683                                    @Override
14684                                    public void onReceive(Context context, Intent intent) {
14685                                        final Message msg = mHandler
14686                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14687                                        msg.arg1 = verificationId;
14688                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14689                                    }
14690                                }, null, 0, null, null);
14691
14692                        /*
14693                         * We don't want the copy to proceed until verification
14694                         * succeeds, so null out this field.
14695                         */
14696                        mArgs = null;
14697                    }
14698                } else {
14699                    /*
14700                     * No package verification is enabled, so immediately start
14701                     * the remote call to initiate copy using temporary file.
14702                     */
14703                    ret = args.copyApk(mContainerService, true);
14704                }
14705            }
14706
14707            mRet = ret;
14708        }
14709
14710        @Override
14711        void handleReturnCode() {
14712            // If mArgs is null, then MCS couldn't be reached. When it
14713            // reconnects, it will try again to install. At that point, this
14714            // will succeed.
14715            if (mArgs != null) {
14716                processPendingInstall(mArgs, mRet);
14717            }
14718        }
14719
14720        @Override
14721        void handleServiceError() {
14722            mArgs = createInstallArgs(this);
14723            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14724        }
14725    }
14726
14727    private InstallArgs createInstallArgs(InstallParams params) {
14728        if (params.move != null) {
14729            return new MoveInstallArgs(params);
14730        } else {
14731            return new FileInstallArgs(params);
14732        }
14733    }
14734
14735    /**
14736     * Create args that describe an existing installed package. Typically used
14737     * when cleaning up old installs, or used as a move source.
14738     */
14739    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14740            String resourcePath, String[] instructionSets) {
14741        return new FileInstallArgs(codePath, resourcePath, instructionSets);
14742    }
14743
14744    static abstract class InstallArgs {
14745        /** @see InstallParams#origin */
14746        final OriginInfo origin;
14747        /** @see InstallParams#move */
14748        final MoveInfo move;
14749
14750        final IPackageInstallObserver2 observer;
14751        // Always refers to PackageManager flags only
14752        final int installFlags;
14753        final String installerPackageName;
14754        final String volumeUuid;
14755        final UserHandle user;
14756        final String abiOverride;
14757        final String[] installGrantPermissions;
14758        /** If non-null, drop an async trace when the install completes */
14759        final String traceMethod;
14760        final int traceCookie;
14761        final Certificate[][] certificates;
14762        final int installReason;
14763
14764        // The list of instruction sets supported by this app. This is currently
14765        // only used during the rmdex() phase to clean up resources. We can get rid of this
14766        // if we move dex files under the common app path.
14767        /* nullable */ String[] instructionSets;
14768
14769        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14770                int installFlags, String installerPackageName, String volumeUuid,
14771                UserHandle user, String[] instructionSets,
14772                String abiOverride, String[] installGrantPermissions,
14773                String traceMethod, int traceCookie, Certificate[][] certificates,
14774                int installReason) {
14775            this.origin = origin;
14776            this.move = move;
14777            this.installFlags = installFlags;
14778            this.observer = observer;
14779            this.installerPackageName = installerPackageName;
14780            this.volumeUuid = volumeUuid;
14781            this.user = user;
14782            this.instructionSets = instructionSets;
14783            this.abiOverride = abiOverride;
14784            this.installGrantPermissions = installGrantPermissions;
14785            this.traceMethod = traceMethod;
14786            this.traceCookie = traceCookie;
14787            this.certificates = certificates;
14788            this.installReason = installReason;
14789        }
14790
14791        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14792        abstract int doPreInstall(int status);
14793
14794        /**
14795         * Rename package into final resting place. All paths on the given
14796         * scanned package should be updated to reflect the rename.
14797         */
14798        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14799        abstract int doPostInstall(int status, int uid);
14800
14801        /** @see PackageSettingBase#codePathString */
14802        abstract String getCodePath();
14803        /** @see PackageSettingBase#resourcePathString */
14804        abstract String getResourcePath();
14805
14806        // Need installer lock especially for dex file removal.
14807        abstract void cleanUpResourcesLI();
14808        abstract boolean doPostDeleteLI(boolean delete);
14809
14810        /**
14811         * Called before the source arguments are copied. This is used mostly
14812         * for MoveParams when it needs to read the source file to put it in the
14813         * destination.
14814         */
14815        int doPreCopy() {
14816            return PackageManager.INSTALL_SUCCEEDED;
14817        }
14818
14819        /**
14820         * Called after the source arguments are copied. This is used mostly for
14821         * MoveParams when it needs to read the source file to put it in the
14822         * destination.
14823         */
14824        int doPostCopy(int uid) {
14825            return PackageManager.INSTALL_SUCCEEDED;
14826        }
14827
14828        protected boolean isFwdLocked() {
14829            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14830        }
14831
14832        protected boolean isExternalAsec() {
14833            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14834        }
14835
14836        protected boolean isEphemeral() {
14837            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14838        }
14839
14840        UserHandle getUser() {
14841            return user;
14842        }
14843    }
14844
14845    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14846        if (!allCodePaths.isEmpty()) {
14847            if (instructionSets == null) {
14848                throw new IllegalStateException("instructionSet == null");
14849            }
14850            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14851            for (String codePath : allCodePaths) {
14852                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14853                    try {
14854                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14855                    } catch (InstallerException ignored) {
14856                    }
14857                }
14858            }
14859        }
14860    }
14861
14862    /**
14863     * Logic to handle installation of non-ASEC applications, including copying
14864     * and renaming logic.
14865     */
14866    class FileInstallArgs extends InstallArgs {
14867        private File codeFile;
14868        private File resourceFile;
14869
14870        // Example topology:
14871        // /data/app/com.example/base.apk
14872        // /data/app/com.example/split_foo.apk
14873        // /data/app/com.example/lib/arm/libfoo.so
14874        // /data/app/com.example/lib/arm64/libfoo.so
14875        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14876
14877        /** New install */
14878        FileInstallArgs(InstallParams params) {
14879            super(params.origin, params.move, params.observer, params.installFlags,
14880                    params.installerPackageName, params.volumeUuid,
14881                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14882                    params.grantedRuntimePermissions,
14883                    params.traceMethod, params.traceCookie, params.certificates,
14884                    params.installReason);
14885            if (isFwdLocked()) {
14886                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14887            }
14888        }
14889
14890        /** Existing install */
14891        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14892            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14893                    null, null, null, 0, null /*certificates*/,
14894                    PackageManager.INSTALL_REASON_UNKNOWN);
14895            this.codeFile = (codePath != null) ? new File(codePath) : null;
14896            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14897        }
14898
14899        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14900            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14901            try {
14902                return doCopyApk(imcs, temp);
14903            } finally {
14904                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14905            }
14906        }
14907
14908        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14909            if (origin.staged) {
14910                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14911                codeFile = origin.file;
14912                resourceFile = origin.file;
14913                return PackageManager.INSTALL_SUCCEEDED;
14914            }
14915
14916            try {
14917                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14918                final File tempDir =
14919                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14920                codeFile = tempDir;
14921                resourceFile = tempDir;
14922            } catch (IOException e) {
14923                Slog.w(TAG, "Failed to create copy file: " + e);
14924                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14925            }
14926
14927            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14928                @Override
14929                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14930                    if (!FileUtils.isValidExtFilename(name)) {
14931                        throw new IllegalArgumentException("Invalid filename: " + name);
14932                    }
14933                    try {
14934                        final File file = new File(codeFile, name);
14935                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14936                                O_RDWR | O_CREAT, 0644);
14937                        Os.chmod(file.getAbsolutePath(), 0644);
14938                        return new ParcelFileDescriptor(fd);
14939                    } catch (ErrnoException e) {
14940                        throw new RemoteException("Failed to open: " + e.getMessage());
14941                    }
14942                }
14943            };
14944
14945            int ret = PackageManager.INSTALL_SUCCEEDED;
14946            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14947            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14948                Slog.e(TAG, "Failed to copy package");
14949                return ret;
14950            }
14951
14952            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14953            NativeLibraryHelper.Handle handle = null;
14954            try {
14955                handle = NativeLibraryHelper.Handle.create(codeFile);
14956                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14957                        abiOverride);
14958            } catch (IOException e) {
14959                Slog.e(TAG, "Copying native libraries failed", e);
14960                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14961            } finally {
14962                IoUtils.closeQuietly(handle);
14963            }
14964
14965            return ret;
14966        }
14967
14968        int doPreInstall(int status) {
14969            if (status != PackageManager.INSTALL_SUCCEEDED) {
14970                cleanUp();
14971            }
14972            return status;
14973        }
14974
14975        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14976            if (status != PackageManager.INSTALL_SUCCEEDED) {
14977                cleanUp();
14978                return false;
14979            }
14980
14981            final File targetDir = codeFile.getParentFile();
14982            final File beforeCodeFile = codeFile;
14983            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14984
14985            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14986            try {
14987                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14988            } catch (ErrnoException e) {
14989                Slog.w(TAG, "Failed to rename", e);
14990                return false;
14991            }
14992
14993            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14994                Slog.w(TAG, "Failed to restorecon");
14995                return false;
14996            }
14997
14998            // Reflect the rename internally
14999            codeFile = afterCodeFile;
15000            resourceFile = afterCodeFile;
15001
15002            // Reflect the rename in scanned details
15003            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15004            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15005                    afterCodeFile, pkg.baseCodePath));
15006            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15007                    afterCodeFile, pkg.splitCodePaths));
15008
15009            // Reflect the rename in app info
15010            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15011            pkg.setApplicationInfoCodePath(pkg.codePath);
15012            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15013            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15014            pkg.setApplicationInfoResourcePath(pkg.codePath);
15015            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15016            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15017
15018            return true;
15019        }
15020
15021        int doPostInstall(int status, int uid) {
15022            if (status != PackageManager.INSTALL_SUCCEEDED) {
15023                cleanUp();
15024            }
15025            return status;
15026        }
15027
15028        @Override
15029        String getCodePath() {
15030            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15031        }
15032
15033        @Override
15034        String getResourcePath() {
15035            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15036        }
15037
15038        private boolean cleanUp() {
15039            if (codeFile == null || !codeFile.exists()) {
15040                return false;
15041            }
15042
15043            removeCodePathLI(codeFile);
15044
15045            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15046                resourceFile.delete();
15047            }
15048
15049            return true;
15050        }
15051
15052        void cleanUpResourcesLI() {
15053            // Try enumerating all code paths before deleting
15054            List<String> allCodePaths = Collections.EMPTY_LIST;
15055            if (codeFile != null && codeFile.exists()) {
15056                try {
15057                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15058                    allCodePaths = pkg.getAllCodePaths();
15059                } catch (PackageParserException e) {
15060                    // Ignored; we tried our best
15061                }
15062            }
15063
15064            cleanUp();
15065            removeDexFiles(allCodePaths, instructionSets);
15066        }
15067
15068        boolean doPostDeleteLI(boolean delete) {
15069            // XXX err, shouldn't we respect the delete flag?
15070            cleanUpResourcesLI();
15071            return true;
15072        }
15073    }
15074
15075    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15076            PackageManagerException {
15077        if (copyRet < 0) {
15078            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15079                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15080                throw new PackageManagerException(copyRet, message);
15081            }
15082        }
15083    }
15084
15085    /**
15086     * Extract the StorageManagerService "container ID" from the full code path of an
15087     * .apk.
15088     */
15089    static String cidFromCodePath(String fullCodePath) {
15090        int eidx = fullCodePath.lastIndexOf("/");
15091        String subStr1 = fullCodePath.substring(0, eidx);
15092        int sidx = subStr1.lastIndexOf("/");
15093        return subStr1.substring(sidx+1, eidx);
15094    }
15095
15096    /**
15097     * Logic to handle movement of existing installed applications.
15098     */
15099    class MoveInstallArgs extends InstallArgs {
15100        private File codeFile;
15101        private File resourceFile;
15102
15103        /** New install */
15104        MoveInstallArgs(InstallParams params) {
15105            super(params.origin, params.move, params.observer, params.installFlags,
15106                    params.installerPackageName, params.volumeUuid,
15107                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15108                    params.grantedRuntimePermissions,
15109                    params.traceMethod, params.traceCookie, params.certificates,
15110                    params.installReason);
15111        }
15112
15113        int copyApk(IMediaContainerService imcs, boolean temp) {
15114            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15115                    + move.fromUuid + " to " + move.toUuid);
15116            synchronized (mInstaller) {
15117                try {
15118                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15119                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15120                } catch (InstallerException e) {
15121                    Slog.w(TAG, "Failed to move app", e);
15122                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15123                }
15124            }
15125
15126            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15127            resourceFile = codeFile;
15128            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15129
15130            return PackageManager.INSTALL_SUCCEEDED;
15131        }
15132
15133        int doPreInstall(int status) {
15134            if (status != PackageManager.INSTALL_SUCCEEDED) {
15135                cleanUp(move.toUuid);
15136            }
15137            return status;
15138        }
15139
15140        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15141            if (status != PackageManager.INSTALL_SUCCEEDED) {
15142                cleanUp(move.toUuid);
15143                return false;
15144            }
15145
15146            // Reflect the move in app info
15147            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15148            pkg.setApplicationInfoCodePath(pkg.codePath);
15149            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15150            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15151            pkg.setApplicationInfoResourcePath(pkg.codePath);
15152            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15153            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15154
15155            return true;
15156        }
15157
15158        int doPostInstall(int status, int uid) {
15159            if (status == PackageManager.INSTALL_SUCCEEDED) {
15160                cleanUp(move.fromUuid);
15161            } else {
15162                cleanUp(move.toUuid);
15163            }
15164            return status;
15165        }
15166
15167        @Override
15168        String getCodePath() {
15169            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15170        }
15171
15172        @Override
15173        String getResourcePath() {
15174            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15175        }
15176
15177        private boolean cleanUp(String volumeUuid) {
15178            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15179                    move.dataAppName);
15180            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15181            final int[] userIds = sUserManager.getUserIds();
15182            synchronized (mInstallLock) {
15183                // Clean up both app data and code
15184                // All package moves are frozen until finished
15185                for (int userId : userIds) {
15186                    try {
15187                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15188                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15189                    } catch (InstallerException e) {
15190                        Slog.w(TAG, String.valueOf(e));
15191                    }
15192                }
15193                removeCodePathLI(codeFile);
15194            }
15195            return true;
15196        }
15197
15198        void cleanUpResourcesLI() {
15199            throw new UnsupportedOperationException();
15200        }
15201
15202        boolean doPostDeleteLI(boolean delete) {
15203            throw new UnsupportedOperationException();
15204        }
15205    }
15206
15207    static String getAsecPackageName(String packageCid) {
15208        int idx = packageCid.lastIndexOf("-");
15209        if (idx == -1) {
15210            return packageCid;
15211        }
15212        return packageCid.substring(0, idx);
15213    }
15214
15215    // Utility method used to create code paths based on package name and available index.
15216    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15217        String idxStr = "";
15218        int idx = 1;
15219        // Fall back to default value of idx=1 if prefix is not
15220        // part of oldCodePath
15221        if (oldCodePath != null) {
15222            String subStr = oldCodePath;
15223            // Drop the suffix right away
15224            if (suffix != null && subStr.endsWith(suffix)) {
15225                subStr = subStr.substring(0, subStr.length() - suffix.length());
15226            }
15227            // If oldCodePath already contains prefix find out the
15228            // ending index to either increment or decrement.
15229            int sidx = subStr.lastIndexOf(prefix);
15230            if (sidx != -1) {
15231                subStr = subStr.substring(sidx + prefix.length());
15232                if (subStr != null) {
15233                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15234                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15235                    }
15236                    try {
15237                        idx = Integer.parseInt(subStr);
15238                        if (idx <= 1) {
15239                            idx++;
15240                        } else {
15241                            idx--;
15242                        }
15243                    } catch(NumberFormatException e) {
15244                    }
15245                }
15246            }
15247        }
15248        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15249        return prefix + idxStr;
15250    }
15251
15252    private File getNextCodePath(File targetDir, String packageName) {
15253        File result;
15254        SecureRandom random = new SecureRandom();
15255        byte[] bytes = new byte[16];
15256        do {
15257            random.nextBytes(bytes);
15258            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15259            result = new File(targetDir, packageName + "-" + suffix);
15260        } while (result.exists());
15261        return result;
15262    }
15263
15264    // Utility method that returns the relative package path with respect
15265    // to the installation directory. Like say for /data/data/com.test-1.apk
15266    // string com.test-1 is returned.
15267    static String deriveCodePathName(String codePath) {
15268        if (codePath == null) {
15269            return null;
15270        }
15271        final File codeFile = new File(codePath);
15272        final String name = codeFile.getName();
15273        if (codeFile.isDirectory()) {
15274            return name;
15275        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15276            final int lastDot = name.lastIndexOf('.');
15277            return name.substring(0, lastDot);
15278        } else {
15279            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15280            return null;
15281        }
15282    }
15283
15284    static class PackageInstalledInfo {
15285        String name;
15286        int uid;
15287        // The set of users that originally had this package installed.
15288        int[] origUsers;
15289        // The set of users that now have this package installed.
15290        int[] newUsers;
15291        PackageParser.Package pkg;
15292        int returnCode;
15293        String returnMsg;
15294        String installerPackageName;
15295        PackageRemovedInfo removedInfo;
15296        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15297
15298        public void setError(int code, String msg) {
15299            setReturnCode(code);
15300            setReturnMessage(msg);
15301            Slog.w(TAG, msg);
15302        }
15303
15304        public void setError(String msg, PackageParserException e) {
15305            setReturnCode(e.error);
15306            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15307            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15308            for (int i = 0; i < childCount; i++) {
15309                addedChildPackages.valueAt(i).setError(msg, e);
15310            }
15311            Slog.w(TAG, msg, e);
15312        }
15313
15314        public void setError(String msg, PackageManagerException e) {
15315            returnCode = e.error;
15316            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15317            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15318            for (int i = 0; i < childCount; i++) {
15319                addedChildPackages.valueAt(i).setError(msg, e);
15320            }
15321            Slog.w(TAG, msg, e);
15322        }
15323
15324        public void setReturnCode(int returnCode) {
15325            this.returnCode = returnCode;
15326            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15327            for (int i = 0; i < childCount; i++) {
15328                addedChildPackages.valueAt(i).returnCode = returnCode;
15329            }
15330        }
15331
15332        private void setReturnMessage(String returnMsg) {
15333            this.returnMsg = returnMsg;
15334            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15335            for (int i = 0; i < childCount; i++) {
15336                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15337            }
15338        }
15339
15340        // In some error cases we want to convey more info back to the observer
15341        String origPackage;
15342        String origPermission;
15343    }
15344
15345    /*
15346     * Install a non-existing package.
15347     */
15348    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15349            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15350            String volumeUuid, PackageInstalledInfo res, int installReason) {
15351        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15352
15353        // Remember this for later, in case we need to rollback this install
15354        String pkgName = pkg.packageName;
15355
15356        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15357
15358        synchronized(mPackages) {
15359            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15360            if (renamedPackage != null) {
15361                // A package with the same name is already installed, though
15362                // it has been renamed to an older name.  The package we
15363                // are trying to install should be installed as an update to
15364                // the existing one, but that has not been requested, so bail.
15365                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15366                        + " without first uninstalling package running as "
15367                        + renamedPackage);
15368                return;
15369            }
15370            if (mPackages.containsKey(pkgName)) {
15371                // Don't allow installation over an existing package with the same name.
15372                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15373                        + " without first uninstalling.");
15374                return;
15375            }
15376        }
15377
15378        try {
15379            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15380                    System.currentTimeMillis(), user);
15381
15382            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15383
15384            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15385                prepareAppDataAfterInstallLIF(newPackage);
15386
15387            } else {
15388                // Remove package from internal structures, but keep around any
15389                // data that might have already existed
15390                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15391                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15392            }
15393        } catch (PackageManagerException e) {
15394            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15395        }
15396
15397        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15398    }
15399
15400    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15401        try (DigestInputStream digestStream =
15402                new DigestInputStream(new FileInputStream(file), digest)) {
15403            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15404        }
15405    }
15406
15407    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15408            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15409            PackageInstalledInfo res, int installReason) {
15410        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15411
15412        final PackageParser.Package oldPackage;
15413        final PackageSetting ps;
15414        final String pkgName = pkg.packageName;
15415        final int[] allUsers;
15416        final int[] installedUsers;
15417
15418        synchronized(mPackages) {
15419            oldPackage = mPackages.get(pkgName);
15420            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15421
15422            // don't allow upgrade to target a release SDK from a pre-release SDK
15423            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15424                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15425            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15426                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15427            if (oldTargetsPreRelease
15428                    && !newTargetsPreRelease
15429                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15430                Slog.w(TAG, "Can't install package targeting released sdk");
15431                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15432                return;
15433            }
15434
15435            ps = mSettings.mPackages.get(pkgName);
15436
15437            // verify signatures are valid
15438            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15439            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15440                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15441                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15442                            "New package not signed by keys specified by upgrade-keysets: "
15443                                    + pkgName);
15444                    return;
15445                }
15446            } else {
15447                // default to original signature matching
15448                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15449                        != PackageManager.SIGNATURE_MATCH) {
15450                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15451                            "New package has a different signature: " + pkgName);
15452                    return;
15453                }
15454            }
15455
15456            // don't allow a system upgrade unless the upgrade hash matches
15457            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15458                byte[] digestBytes = null;
15459                try {
15460                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15461                    updateDigest(digest, new File(pkg.baseCodePath));
15462                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15463                        for (String path : pkg.splitCodePaths) {
15464                            updateDigest(digest, new File(path));
15465                        }
15466                    }
15467                    digestBytes = digest.digest();
15468                } catch (NoSuchAlgorithmException | IOException e) {
15469                    res.setError(INSTALL_FAILED_INVALID_APK,
15470                            "Could not compute hash: " + pkgName);
15471                    return;
15472                }
15473                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15474                    res.setError(INSTALL_FAILED_INVALID_APK,
15475                            "New package fails restrict-update check: " + pkgName);
15476                    return;
15477                }
15478                // retain upgrade restriction
15479                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15480            }
15481
15482            // Check for shared user id changes
15483            String invalidPackageName =
15484                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15485            if (invalidPackageName != null) {
15486                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15487                        "Package " + invalidPackageName + " tried to change user "
15488                                + oldPackage.mSharedUserId);
15489                return;
15490            }
15491
15492            // In case of rollback, remember per-user/profile install state
15493            allUsers = sUserManager.getUserIds();
15494            installedUsers = ps.queryInstalledUsers(allUsers, true);
15495
15496            // don't allow an upgrade from full to ephemeral
15497            if (isInstantApp) {
15498                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15499                    for (int currentUser : allUsers) {
15500                        if (!ps.getInstantApp(currentUser)) {
15501                            // can't downgrade from full to instant
15502                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15503                                    + " for user: " + currentUser);
15504                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15505                            return;
15506                        }
15507                    }
15508                } else if (!ps.getInstantApp(user.getIdentifier())) {
15509                    // can't downgrade from full to instant
15510                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15511                            + " for user: " + user.getIdentifier());
15512                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15513                    return;
15514                }
15515            }
15516        }
15517
15518        // Update what is removed
15519        res.removedInfo = new PackageRemovedInfo(this);
15520        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15521        res.removedInfo.removedPackage = oldPackage.packageName;
15522        res.removedInfo.installerPackageName = ps.installerPackageName;
15523        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15524        res.removedInfo.isUpdate = true;
15525        res.removedInfo.origUsers = installedUsers;
15526        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15527        for (int i = 0; i < installedUsers.length; i++) {
15528            final int userId = installedUsers[i];
15529            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15530        }
15531
15532        final int childCount = (oldPackage.childPackages != null)
15533                ? oldPackage.childPackages.size() : 0;
15534        for (int i = 0; i < childCount; i++) {
15535            boolean childPackageUpdated = false;
15536            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15537            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15538            if (res.addedChildPackages != null) {
15539                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15540                if (childRes != null) {
15541                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15542                    childRes.removedInfo.removedPackage = childPkg.packageName;
15543                    if (childPs != null) {
15544                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15545                    }
15546                    childRes.removedInfo.isUpdate = true;
15547                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15548                    childPackageUpdated = true;
15549                }
15550            }
15551            if (!childPackageUpdated) {
15552                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15553                childRemovedRes.removedPackage = childPkg.packageName;
15554                if (childPs != null) {
15555                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15556                }
15557                childRemovedRes.isUpdate = false;
15558                childRemovedRes.dataRemoved = true;
15559                synchronized (mPackages) {
15560                    if (childPs != null) {
15561                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15562                    }
15563                }
15564                if (res.removedInfo.removedChildPackages == null) {
15565                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15566                }
15567                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15568            }
15569        }
15570
15571        boolean sysPkg = (isSystemApp(oldPackage));
15572        if (sysPkg) {
15573            // Set the system/privileged/oem flags as needed
15574            final boolean privileged =
15575                    (oldPackage.applicationInfo.privateFlags
15576                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15577            final boolean oem =
15578                    (oldPackage.applicationInfo.privateFlags
15579                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15580            final @ParseFlags int systemParseFlags = parseFlags;
15581            final @ScanFlags int systemScanFlags = scanFlags
15582                    | SCAN_AS_SYSTEM
15583                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15584                    | (oem ? SCAN_AS_OEM : 0);
15585
15586            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15587                    user, allUsers, installerPackageName, res, installReason);
15588        } else {
15589            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15590                    user, allUsers, installerPackageName, res, installReason);
15591        }
15592    }
15593
15594    @Override
15595    public List<String> getPreviousCodePaths(String packageName) {
15596        final int callingUid = Binder.getCallingUid();
15597        final List<String> result = new ArrayList<>();
15598        if (getInstantAppPackageName(callingUid) != null) {
15599            return result;
15600        }
15601        final PackageSetting ps = mSettings.mPackages.get(packageName);
15602        if (ps != null
15603                && ps.oldCodePaths != null
15604                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15605            result.addAll(ps.oldCodePaths);
15606        }
15607        return result;
15608    }
15609
15610    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15611            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15612            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15613            String installerPackageName, PackageInstalledInfo res, int installReason) {
15614        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15615                + deletedPackage);
15616
15617        String pkgName = deletedPackage.packageName;
15618        boolean deletedPkg = true;
15619        boolean addedPkg = false;
15620        boolean updatedSettings = false;
15621        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15622        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15623                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15624
15625        final long origUpdateTime = (pkg.mExtras != null)
15626                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15627
15628        // First delete the existing package while retaining the data directory
15629        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15630                res.removedInfo, true, pkg)) {
15631            // If the existing package wasn't successfully deleted
15632            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15633            deletedPkg = false;
15634        } else {
15635            // Successfully deleted the old package; proceed with replace.
15636
15637            // If deleted package lived in a container, give users a chance to
15638            // relinquish resources before killing.
15639            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15640                if (DEBUG_INSTALL) {
15641                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15642                }
15643                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15644                final ArrayList<String> pkgList = new ArrayList<String>(1);
15645                pkgList.add(deletedPackage.applicationInfo.packageName);
15646                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15647            }
15648
15649            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15650                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15651            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15652
15653            try {
15654                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15655                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15656                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15657                        installReason);
15658
15659                // Update the in-memory copy of the previous code paths.
15660                PackageSetting ps = mSettings.mPackages.get(pkgName);
15661                if (!killApp) {
15662                    if (ps.oldCodePaths == null) {
15663                        ps.oldCodePaths = new ArraySet<>();
15664                    }
15665                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15666                    if (deletedPackage.splitCodePaths != null) {
15667                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15668                    }
15669                } else {
15670                    ps.oldCodePaths = null;
15671                }
15672                if (ps.childPackageNames != null) {
15673                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15674                        final String childPkgName = ps.childPackageNames.get(i);
15675                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15676                        childPs.oldCodePaths = ps.oldCodePaths;
15677                    }
15678                }
15679                // set instant app status, but, only if it's explicitly specified
15680                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15681                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15682                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15683                prepareAppDataAfterInstallLIF(newPackage);
15684                addedPkg = true;
15685                mDexManager.notifyPackageUpdated(newPackage.packageName,
15686                        newPackage.baseCodePath, newPackage.splitCodePaths);
15687            } catch (PackageManagerException e) {
15688                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15689            }
15690        }
15691
15692        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15693            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15694
15695            // Revert all internal state mutations and added folders for the failed install
15696            if (addedPkg) {
15697                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15698                        res.removedInfo, true, null);
15699            }
15700
15701            // Restore the old package
15702            if (deletedPkg) {
15703                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15704                File restoreFile = new File(deletedPackage.codePath);
15705                // Parse old package
15706                boolean oldExternal = isExternal(deletedPackage);
15707                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15708                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15709                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15710                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15711                try {
15712                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15713                            null);
15714                } catch (PackageManagerException e) {
15715                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15716                            + e.getMessage());
15717                    return;
15718                }
15719
15720                synchronized (mPackages) {
15721                    // Ensure the installer package name up to date
15722                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15723
15724                    // Update permissions for restored package
15725                    mPermissionManager.updatePermissions(
15726                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15727                            mPermissionCallback);
15728
15729                    mSettings.writeLPr();
15730                }
15731
15732                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15733            }
15734        } else {
15735            synchronized (mPackages) {
15736                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15737                if (ps != null) {
15738                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15739                    if (res.removedInfo.removedChildPackages != null) {
15740                        final int childCount = res.removedInfo.removedChildPackages.size();
15741                        // Iterate in reverse as we may modify the collection
15742                        for (int i = childCount - 1; i >= 0; i--) {
15743                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15744                            if (res.addedChildPackages.containsKey(childPackageName)) {
15745                                res.removedInfo.removedChildPackages.removeAt(i);
15746                            } else {
15747                                PackageRemovedInfo childInfo = res.removedInfo
15748                                        .removedChildPackages.valueAt(i);
15749                                childInfo.removedForAllUsers = mPackages.get(
15750                                        childInfo.removedPackage) == null;
15751                            }
15752                        }
15753                    }
15754                }
15755            }
15756        }
15757    }
15758
15759    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15760            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15761            final @ScanFlags int scanFlags, UserHandle user,
15762            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15763            int installReason) {
15764        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15765                + ", old=" + deletedPackage);
15766
15767        final boolean disabledSystem;
15768
15769        // Remove existing system package
15770        removePackageLI(deletedPackage, true);
15771
15772        synchronized (mPackages) {
15773            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15774        }
15775        if (!disabledSystem) {
15776            // We didn't need to disable the .apk as a current system package,
15777            // which means we are replacing another update that is already
15778            // installed.  We need to make sure to delete the older one's .apk.
15779            res.removedInfo.args = createInstallArgsForExisting(0,
15780                    deletedPackage.applicationInfo.getCodePath(),
15781                    deletedPackage.applicationInfo.getResourcePath(),
15782                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15783        } else {
15784            res.removedInfo.args = null;
15785        }
15786
15787        // Successfully disabled the old package. Now proceed with re-installation
15788        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15789                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15790        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15791
15792        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15793        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15794                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15795
15796        PackageParser.Package newPackage = null;
15797        try {
15798            // Add the package to the internal data structures
15799            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
15800
15801            // Set the update and install times
15802            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15803            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15804                    System.currentTimeMillis());
15805
15806            // Update the package dynamic state if succeeded
15807            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15808                // Now that the install succeeded make sure we remove data
15809                // directories for any child package the update removed.
15810                final int deletedChildCount = (deletedPackage.childPackages != null)
15811                        ? deletedPackage.childPackages.size() : 0;
15812                final int newChildCount = (newPackage.childPackages != null)
15813                        ? newPackage.childPackages.size() : 0;
15814                for (int i = 0; i < deletedChildCount; i++) {
15815                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15816                    boolean childPackageDeleted = true;
15817                    for (int j = 0; j < newChildCount; j++) {
15818                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15819                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15820                            childPackageDeleted = false;
15821                            break;
15822                        }
15823                    }
15824                    if (childPackageDeleted) {
15825                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15826                                deletedChildPkg.packageName);
15827                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15828                            PackageRemovedInfo removedChildRes = res.removedInfo
15829                                    .removedChildPackages.get(deletedChildPkg.packageName);
15830                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15831                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15832                        }
15833                    }
15834                }
15835
15836                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15837                        installReason);
15838                prepareAppDataAfterInstallLIF(newPackage);
15839
15840                mDexManager.notifyPackageUpdated(newPackage.packageName,
15841                            newPackage.baseCodePath, newPackage.splitCodePaths);
15842            }
15843        } catch (PackageManagerException e) {
15844            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15845            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15846        }
15847
15848        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15849            // Re installation failed. Restore old information
15850            // Remove new pkg information
15851            if (newPackage != null) {
15852                removeInstalledPackageLI(newPackage, true);
15853            }
15854            // Add back the old system package
15855            try {
15856                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15857            } catch (PackageManagerException e) {
15858                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15859            }
15860
15861            synchronized (mPackages) {
15862                if (disabledSystem) {
15863                    enableSystemPackageLPw(deletedPackage);
15864                }
15865
15866                // Ensure the installer package name up to date
15867                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15868
15869                // Update permissions for restored package
15870                mPermissionManager.updatePermissions(
15871                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15872                        mPermissionCallback);
15873
15874                mSettings.writeLPr();
15875            }
15876
15877            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15878                    + " after failed upgrade");
15879        }
15880    }
15881
15882    /**
15883     * Checks whether the parent or any of the child packages have a change shared
15884     * user. For a package to be a valid update the shred users of the parent and
15885     * the children should match. We may later support changing child shared users.
15886     * @param oldPkg The updated package.
15887     * @param newPkg The update package.
15888     * @return The shared user that change between the versions.
15889     */
15890    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15891            PackageParser.Package newPkg) {
15892        // Check parent shared user
15893        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15894            return newPkg.packageName;
15895        }
15896        // Check child shared users
15897        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15898        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15899        for (int i = 0; i < newChildCount; i++) {
15900            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15901            // If this child was present, did it have the same shared user?
15902            for (int j = 0; j < oldChildCount; j++) {
15903                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15904                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15905                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15906                    return newChildPkg.packageName;
15907                }
15908            }
15909        }
15910        return null;
15911    }
15912
15913    private void removeNativeBinariesLI(PackageSetting ps) {
15914        // Remove the lib path for the parent package
15915        if (ps != null) {
15916            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15917            // Remove the lib path for the child packages
15918            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15919            for (int i = 0; i < childCount; i++) {
15920                PackageSetting childPs = null;
15921                synchronized (mPackages) {
15922                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15923                }
15924                if (childPs != null) {
15925                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15926                            .legacyNativeLibraryPathString);
15927                }
15928            }
15929        }
15930    }
15931
15932    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15933        // Enable the parent package
15934        mSettings.enableSystemPackageLPw(pkg.packageName);
15935        // Enable the child packages
15936        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15937        for (int i = 0; i < childCount; i++) {
15938            PackageParser.Package childPkg = pkg.childPackages.get(i);
15939            mSettings.enableSystemPackageLPw(childPkg.packageName);
15940        }
15941    }
15942
15943    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15944            PackageParser.Package newPkg) {
15945        // Disable the parent package (parent always replaced)
15946        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15947        // Disable the child packages
15948        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15949        for (int i = 0; i < childCount; i++) {
15950            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15951            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15952            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15953        }
15954        return disabled;
15955    }
15956
15957    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15958            String installerPackageName) {
15959        // Enable the parent package
15960        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15961        // Enable the child packages
15962        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15963        for (int i = 0; i < childCount; i++) {
15964            PackageParser.Package childPkg = pkg.childPackages.get(i);
15965            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15966        }
15967    }
15968
15969    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15970            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15971        // Update the parent package setting
15972        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15973                res, user, installReason);
15974        // Update the child packages setting
15975        final int childCount = (newPackage.childPackages != null)
15976                ? newPackage.childPackages.size() : 0;
15977        for (int i = 0; i < childCount; i++) {
15978            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15979            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15980            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15981                    childRes.origUsers, childRes, user, installReason);
15982        }
15983    }
15984
15985    private void updateSettingsInternalLI(PackageParser.Package pkg,
15986            String installerPackageName, int[] allUsers, int[] installedForUsers,
15987            PackageInstalledInfo res, UserHandle user, int installReason) {
15988        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15989
15990        String pkgName = pkg.packageName;
15991        synchronized (mPackages) {
15992            //write settings. the installStatus will be incomplete at this stage.
15993            //note that the new package setting would have already been
15994            //added to mPackages. It hasn't been persisted yet.
15995            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15996            // TODO: Remove this write? It's also written at the end of this method
15997            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15998            mSettings.writeLPr();
15999            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16000        }
16001
16002        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16003        synchronized (mPackages) {
16004// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16005            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16006                    mPermissionCallback);
16007            // For system-bundled packages, we assume that installing an upgraded version
16008            // of the package implies that the user actually wants to run that new code,
16009            // so we enable the package.
16010            PackageSetting ps = mSettings.mPackages.get(pkgName);
16011            final int userId = user.getIdentifier();
16012            if (ps != null) {
16013                if (isSystemApp(pkg)) {
16014                    if (DEBUG_INSTALL) {
16015                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16016                    }
16017                    // Enable system package for requested users
16018                    if (res.origUsers != null) {
16019                        for (int origUserId : res.origUsers) {
16020                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16021                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16022                                        origUserId, installerPackageName);
16023                            }
16024                        }
16025                    }
16026                    // Also convey the prior install/uninstall state
16027                    if (allUsers != null && installedForUsers != null) {
16028                        for (int currentUserId : allUsers) {
16029                            final boolean installed = ArrayUtils.contains(
16030                                    installedForUsers, currentUserId);
16031                            if (DEBUG_INSTALL) {
16032                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16033                            }
16034                            ps.setInstalled(installed, currentUserId);
16035                        }
16036                        // these install state changes will be persisted in the
16037                        // upcoming call to mSettings.writeLPr().
16038                    }
16039                }
16040                // It's implied that when a user requests installation, they want the app to be
16041                // installed and enabled.
16042                if (userId != UserHandle.USER_ALL) {
16043                    ps.setInstalled(true, userId);
16044                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16045                }
16046
16047                // When replacing an existing package, preserve the original install reason for all
16048                // users that had the package installed before.
16049                final Set<Integer> previousUserIds = new ArraySet<>();
16050                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16051                    final int installReasonCount = res.removedInfo.installReasons.size();
16052                    for (int i = 0; i < installReasonCount; i++) {
16053                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16054                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16055                        ps.setInstallReason(previousInstallReason, previousUserId);
16056                        previousUserIds.add(previousUserId);
16057                    }
16058                }
16059
16060                // Set install reason for users that are having the package newly installed.
16061                if (userId == UserHandle.USER_ALL) {
16062                    for (int currentUserId : sUserManager.getUserIds()) {
16063                        if (!previousUserIds.contains(currentUserId)) {
16064                            ps.setInstallReason(installReason, currentUserId);
16065                        }
16066                    }
16067                } else if (!previousUserIds.contains(userId)) {
16068                    ps.setInstallReason(installReason, userId);
16069                }
16070                mSettings.writeKernelMappingLPr(ps);
16071            }
16072            res.name = pkgName;
16073            res.uid = pkg.applicationInfo.uid;
16074            res.pkg = pkg;
16075            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16076            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16077            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16078            //to update install status
16079            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16080            mSettings.writeLPr();
16081            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16082        }
16083
16084        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16085    }
16086
16087    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16088        try {
16089            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16090            installPackageLI(args, res);
16091        } finally {
16092            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16093        }
16094    }
16095
16096    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16097        final int installFlags = args.installFlags;
16098        final String installerPackageName = args.installerPackageName;
16099        final String volumeUuid = args.volumeUuid;
16100        final File tmpPackageFile = new File(args.getCodePath());
16101        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16102        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16103                || (args.volumeUuid != null));
16104        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16105        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16106        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16107        final boolean virtualPreload =
16108                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16109        boolean replace = false;
16110        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16111        if (args.move != null) {
16112            // moving a complete application; perform an initial scan on the new install location
16113            scanFlags |= SCAN_INITIAL;
16114        }
16115        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16116            scanFlags |= SCAN_DONT_KILL_APP;
16117        }
16118        if (instantApp) {
16119            scanFlags |= SCAN_AS_INSTANT_APP;
16120        }
16121        if (fullApp) {
16122            scanFlags |= SCAN_AS_FULL_APP;
16123        }
16124        if (virtualPreload) {
16125            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16126        }
16127
16128        // Result object to be returned
16129        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16130        res.installerPackageName = installerPackageName;
16131
16132        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16133
16134        // Sanity check
16135        if (instantApp && (forwardLocked || onExternal)) {
16136            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16137                    + " external=" + onExternal);
16138            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16139            return;
16140        }
16141
16142        // Retrieve PackageSettings and parse package
16143        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16144                | PackageParser.PARSE_ENFORCE_CODE
16145                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16146                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16147                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16148                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16149        PackageParser pp = new PackageParser();
16150        pp.setSeparateProcesses(mSeparateProcesses);
16151        pp.setDisplayMetrics(mMetrics);
16152        pp.setCallback(mPackageParserCallback);
16153
16154        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16155        final PackageParser.Package pkg;
16156        try {
16157            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16158        } catch (PackageParserException e) {
16159            res.setError("Failed parse during installPackageLI", e);
16160            return;
16161        } finally {
16162            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16163        }
16164
16165        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16166        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16167            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16168            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16169                    "Instant app package must target O");
16170            return;
16171        }
16172        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16173            Slog.w(TAG, "Instant app package " + pkg.packageName
16174                    + " does not target targetSandboxVersion 2");
16175            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16176                    "Instant app package must use targetSanboxVersion 2");
16177            return;
16178        }
16179
16180        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16181            // Static shared libraries have synthetic package names
16182            renameStaticSharedLibraryPackage(pkg);
16183
16184            // No static shared libs on external storage
16185            if (onExternal) {
16186                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16187                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16188                        "Packages declaring static-shared libs cannot be updated");
16189                return;
16190            }
16191        }
16192
16193        // If we are installing a clustered package add results for the children
16194        if (pkg.childPackages != null) {
16195            synchronized (mPackages) {
16196                final int childCount = pkg.childPackages.size();
16197                for (int i = 0; i < childCount; i++) {
16198                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16199                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16200                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16201                    childRes.pkg = childPkg;
16202                    childRes.name = childPkg.packageName;
16203                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16204                    if (childPs != null) {
16205                        childRes.origUsers = childPs.queryInstalledUsers(
16206                                sUserManager.getUserIds(), true);
16207                    }
16208                    if ((mPackages.containsKey(childPkg.packageName))) {
16209                        childRes.removedInfo = new PackageRemovedInfo(this);
16210                        childRes.removedInfo.removedPackage = childPkg.packageName;
16211                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16212                    }
16213                    if (res.addedChildPackages == null) {
16214                        res.addedChildPackages = new ArrayMap<>();
16215                    }
16216                    res.addedChildPackages.put(childPkg.packageName, childRes);
16217                }
16218            }
16219        }
16220
16221        // If package doesn't declare API override, mark that we have an install
16222        // time CPU ABI override.
16223        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16224            pkg.cpuAbiOverride = args.abiOverride;
16225        }
16226
16227        String pkgName = res.name = pkg.packageName;
16228        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16229            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16230                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16231                return;
16232            }
16233        }
16234
16235        try {
16236            // either use what we've been given or parse directly from the APK
16237            if (args.certificates != null) {
16238                try {
16239                    PackageParser.populateCertificates(pkg, args.certificates);
16240                } catch (PackageParserException e) {
16241                    // there was something wrong with the certificates we were given;
16242                    // try to pull them from the APK
16243                    PackageParser.collectCertificates(pkg, parseFlags);
16244                }
16245            } else {
16246                PackageParser.collectCertificates(pkg, parseFlags);
16247            }
16248        } catch (PackageParserException e) {
16249            res.setError("Failed collect during installPackageLI", e);
16250            return;
16251        }
16252
16253        // Get rid of all references to package scan path via parser.
16254        pp = null;
16255        String oldCodePath = null;
16256        boolean systemApp = false;
16257        synchronized (mPackages) {
16258            // Check if installing already existing package
16259            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16260                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16261                if (pkg.mOriginalPackages != null
16262                        && pkg.mOriginalPackages.contains(oldName)
16263                        && mPackages.containsKey(oldName)) {
16264                    // This package is derived from an original package,
16265                    // and this device has been updating from that original
16266                    // name.  We must continue using the original name, so
16267                    // rename the new package here.
16268                    pkg.setPackageName(oldName);
16269                    pkgName = pkg.packageName;
16270                    replace = true;
16271                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16272                            + oldName + " pkgName=" + pkgName);
16273                } else if (mPackages.containsKey(pkgName)) {
16274                    // This package, under its official name, already exists
16275                    // on the device; we should replace it.
16276                    replace = true;
16277                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16278                }
16279
16280                // Child packages are installed through the parent package
16281                if (pkg.parentPackage != null) {
16282                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16283                            "Package " + pkg.packageName + " is child of package "
16284                                    + pkg.parentPackage.parentPackage + ". Child packages "
16285                                    + "can be updated only through the parent package.");
16286                    return;
16287                }
16288
16289                if (replace) {
16290                    // Prevent apps opting out from runtime permissions
16291                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16292                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16293                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16294                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16295                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16296                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16297                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16298                                        + " doesn't support runtime permissions but the old"
16299                                        + " target SDK " + oldTargetSdk + " does.");
16300                        return;
16301                    }
16302                    // Prevent apps from downgrading their targetSandbox.
16303                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16304                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16305                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16306                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16307                                "Package " + pkg.packageName + " new target sandbox "
16308                                + newTargetSandbox + " is incompatible with the previous value of"
16309                                + oldTargetSandbox + ".");
16310                        return;
16311                    }
16312
16313                    // Prevent installing of child packages
16314                    if (oldPackage.parentPackage != null) {
16315                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16316                                "Package " + pkg.packageName + " is child of package "
16317                                        + oldPackage.parentPackage + ". Child packages "
16318                                        + "can be updated only through the parent package.");
16319                        return;
16320                    }
16321                }
16322            }
16323
16324            PackageSetting ps = mSettings.mPackages.get(pkgName);
16325            if (ps != null) {
16326                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16327
16328                // Static shared libs have same package with different versions where
16329                // we internally use a synthetic package name to allow multiple versions
16330                // of the same package, therefore we need to compare signatures against
16331                // the package setting for the latest library version.
16332                PackageSetting signatureCheckPs = ps;
16333                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16334                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16335                    if (libraryEntry != null) {
16336                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16337                    }
16338                }
16339
16340                // Quick sanity check that we're signed correctly if updating;
16341                // we'll check this again later when scanning, but we want to
16342                // bail early here before tripping over redefined permissions.
16343                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16344                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16345                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16346                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16347                                + pkg.packageName + " upgrade keys do not match the "
16348                                + "previously installed version");
16349                        return;
16350                    }
16351                } else {
16352                    try {
16353                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16354                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16355                        final boolean compatMatch = verifySignatures(
16356                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16357                        // The new KeySets will be re-added later in the scanning process.
16358                        if (compatMatch) {
16359                            synchronized (mPackages) {
16360                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16361                            }
16362                        }
16363                    } catch (PackageManagerException e) {
16364                        res.setError(e.error, e.getMessage());
16365                        return;
16366                    }
16367                }
16368
16369                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16370                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16371                    systemApp = (ps.pkg.applicationInfo.flags &
16372                            ApplicationInfo.FLAG_SYSTEM) != 0;
16373                }
16374                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16375            }
16376
16377            int N = pkg.permissions.size();
16378            for (int i = N-1; i >= 0; i--) {
16379                final PackageParser.Permission perm = pkg.permissions.get(i);
16380                final BasePermission bp =
16381                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16382
16383                // Don't allow anyone but the system to define ephemeral permissions.
16384                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16385                        && !systemApp) {
16386                    Slog.w(TAG, "Non-System package " + pkg.packageName
16387                            + " attempting to delcare ephemeral permission "
16388                            + perm.info.name + "; Removing ephemeral.");
16389                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16390                }
16391
16392                // Check whether the newly-scanned package wants to define an already-defined perm
16393                if (bp != null) {
16394                    // If the defining package is signed with our cert, it's okay.  This
16395                    // also includes the "updating the same package" case, of course.
16396                    // "updating same package" could also involve key-rotation.
16397                    final boolean sigsOk;
16398                    final String sourcePackageName = bp.getSourcePackageName();
16399                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16400                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16401                    if (sourcePackageName.equals(pkg.packageName)
16402                            && (ksms.shouldCheckUpgradeKeySetLocked(
16403                                    sourcePackageSetting, scanFlags))) {
16404                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16405                    } else {
16406                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16407                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16408                    }
16409                    if (!sigsOk) {
16410                        // If the owning package is the system itself, we log but allow
16411                        // install to proceed; we fail the install on all other permission
16412                        // redefinitions.
16413                        if (!sourcePackageName.equals("android")) {
16414                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16415                                    + pkg.packageName + " attempting to redeclare permission "
16416                                    + perm.info.name + " already owned by " + sourcePackageName);
16417                            res.origPermission = perm.info.name;
16418                            res.origPackage = sourcePackageName;
16419                            return;
16420                        } else {
16421                            Slog.w(TAG, "Package " + pkg.packageName
16422                                    + " attempting to redeclare system permission "
16423                                    + perm.info.name + "; ignoring new declaration");
16424                            pkg.permissions.remove(i);
16425                        }
16426                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16427                        // Prevent apps to change protection level to dangerous from any other
16428                        // type as this would allow a privilege escalation where an app adds a
16429                        // normal/signature permission in other app's group and later redefines
16430                        // it as dangerous leading to the group auto-grant.
16431                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16432                                == PermissionInfo.PROTECTION_DANGEROUS) {
16433                            if (bp != null && !bp.isRuntime()) {
16434                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16435                                        + "non-runtime permission " + perm.info.name
16436                                        + " to runtime; keeping old protection level");
16437                                perm.info.protectionLevel = bp.getProtectionLevel();
16438                            }
16439                        }
16440                    }
16441                }
16442            }
16443        }
16444
16445        if (systemApp) {
16446            if (onExternal) {
16447                // Abort update; system app can't be replaced with app on sdcard
16448                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16449                        "Cannot install updates to system apps on sdcard");
16450                return;
16451            } else if (instantApp) {
16452                // Abort update; system app can't be replaced with an instant app
16453                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16454                        "Cannot update a system app with an instant app");
16455                return;
16456            }
16457        }
16458
16459        if (args.move != null) {
16460            // We did an in-place move, so dex is ready to roll
16461            scanFlags |= SCAN_NO_DEX;
16462            scanFlags |= SCAN_MOVE;
16463
16464            synchronized (mPackages) {
16465                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16466                if (ps == null) {
16467                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16468                            "Missing settings for moved package " + pkgName);
16469                }
16470
16471                // We moved the entire application as-is, so bring over the
16472                // previously derived ABI information.
16473                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16474                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16475            }
16476
16477        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16478            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16479            scanFlags |= SCAN_NO_DEX;
16480
16481            try {
16482                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16483                    args.abiOverride : pkg.cpuAbiOverride);
16484                final boolean extractNativeLibs = !pkg.isLibrary();
16485                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16486                        extractNativeLibs, mAppLib32InstallDir);
16487            } catch (PackageManagerException pme) {
16488                Slog.e(TAG, "Error deriving application ABI", pme);
16489                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16490                return;
16491            }
16492
16493            // Shared libraries for the package need to be updated.
16494            synchronized (mPackages) {
16495                try {
16496                    updateSharedLibrariesLPr(pkg, null);
16497                } catch (PackageManagerException e) {
16498                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16499                }
16500            }
16501        }
16502
16503        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16504            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16505            return;
16506        }
16507
16508        // Verify if we need to dexopt the app.
16509        //
16510        // NOTE: it is *important* to call dexopt after doRename which will sync the
16511        // package data from PackageParser.Package and its corresponding ApplicationInfo.
16512        //
16513        // We only need to dexopt if the package meets ALL of the following conditions:
16514        //   1) it is not forward locked.
16515        //   2) it is not on on an external ASEC container.
16516        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16517        //
16518        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16519        // complete, so we skip this step during installation. Instead, we'll take extra time
16520        // the first time the instant app starts. It's preferred to do it this way to provide
16521        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16522        // middle of running an instant app. The default behaviour can be overridden
16523        // via gservices.
16524        final boolean performDexopt = !forwardLocked
16525            && !pkg.applicationInfo.isExternalAsec()
16526            && (!instantApp || Global.getInt(mContext.getContentResolver(),
16527                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16528
16529        if (performDexopt) {
16530            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16531            // Do not run PackageDexOptimizer through the local performDexOpt
16532            // method because `pkg` may not be in `mPackages` yet.
16533            //
16534            // Also, don't fail application installs if the dexopt step fails.
16535            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16536                REASON_INSTALL,
16537                DexoptOptions.DEXOPT_BOOT_COMPLETE);
16538            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16539                null /* instructionSets */,
16540                getOrCreateCompilerPackageStats(pkg),
16541                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16542                dexoptOptions);
16543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16544        }
16545
16546        // Notify BackgroundDexOptService that the package has been changed.
16547        // If this is an update of a package which used to fail to compile,
16548        // BackgroundDexOptService will remove it from its blacklist.
16549        // TODO: Layering violation
16550        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16551
16552        if (!instantApp) {
16553            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16554        } else {
16555            if (DEBUG_DOMAIN_VERIFICATION) {
16556                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16557            }
16558        }
16559
16560        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16561                "installPackageLI")) {
16562            if (replace) {
16563                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16564                    // Static libs have a synthetic package name containing the version
16565                    // and cannot be updated as an update would get a new package name,
16566                    // unless this is the exact same version code which is useful for
16567                    // development.
16568                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16569                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16570                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16571                                + "static-shared libs cannot be updated");
16572                        return;
16573                    }
16574                }
16575                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16576                        installerPackageName, res, args.installReason);
16577            } else {
16578                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16579                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16580            }
16581        }
16582
16583        synchronized (mPackages) {
16584            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16585            if (ps != null) {
16586                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16587                ps.setUpdateAvailable(false /*updateAvailable*/);
16588            }
16589
16590            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16591            for (int i = 0; i < childCount; i++) {
16592                PackageParser.Package childPkg = pkg.childPackages.get(i);
16593                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16594                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16595                if (childPs != null) {
16596                    childRes.newUsers = childPs.queryInstalledUsers(
16597                            sUserManager.getUserIds(), true);
16598                }
16599            }
16600
16601            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16602                updateSequenceNumberLP(ps, res.newUsers);
16603                updateInstantAppInstallerLocked(pkgName);
16604            }
16605        }
16606    }
16607
16608    private void startIntentFilterVerifications(int userId, boolean replacing,
16609            PackageParser.Package pkg) {
16610        if (mIntentFilterVerifierComponent == null) {
16611            Slog.w(TAG, "No IntentFilter verification will not be done as "
16612                    + "there is no IntentFilterVerifier available!");
16613            return;
16614        }
16615
16616        final int verifierUid = getPackageUid(
16617                mIntentFilterVerifierComponent.getPackageName(),
16618                MATCH_DEBUG_TRIAGED_MISSING,
16619                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16620
16621        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16622        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16623        mHandler.sendMessage(msg);
16624
16625        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16626        for (int i = 0; i < childCount; i++) {
16627            PackageParser.Package childPkg = pkg.childPackages.get(i);
16628            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16629            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16630            mHandler.sendMessage(msg);
16631        }
16632    }
16633
16634    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16635            PackageParser.Package pkg) {
16636        int size = pkg.activities.size();
16637        if (size == 0) {
16638            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16639                    "No activity, so no need to verify any IntentFilter!");
16640            return;
16641        }
16642
16643        final boolean hasDomainURLs = hasDomainURLs(pkg);
16644        if (!hasDomainURLs) {
16645            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16646                    "No domain URLs, so no need to verify any IntentFilter!");
16647            return;
16648        }
16649
16650        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16651                + " if any IntentFilter from the " + size
16652                + " Activities needs verification ...");
16653
16654        int count = 0;
16655        final String packageName = pkg.packageName;
16656
16657        synchronized (mPackages) {
16658            // If this is a new install and we see that we've already run verification for this
16659            // package, we have nothing to do: it means the state was restored from backup.
16660            if (!replacing) {
16661                IntentFilterVerificationInfo ivi =
16662                        mSettings.getIntentFilterVerificationLPr(packageName);
16663                if (ivi != null) {
16664                    if (DEBUG_DOMAIN_VERIFICATION) {
16665                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16666                                + ivi.getStatusString());
16667                    }
16668                    return;
16669                }
16670            }
16671
16672            // If any filters need to be verified, then all need to be.
16673            boolean needToVerify = false;
16674            for (PackageParser.Activity a : pkg.activities) {
16675                for (ActivityIntentInfo filter : a.intents) {
16676                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16677                        if (DEBUG_DOMAIN_VERIFICATION) {
16678                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16679                        }
16680                        needToVerify = true;
16681                        break;
16682                    }
16683                }
16684            }
16685
16686            if (needToVerify) {
16687                final int verificationId = mIntentFilterVerificationToken++;
16688                for (PackageParser.Activity a : pkg.activities) {
16689                    for (ActivityIntentInfo filter : a.intents) {
16690                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16691                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16692                                    "Verification needed for IntentFilter:" + filter.toString());
16693                            mIntentFilterVerifier.addOneIntentFilterVerification(
16694                                    verifierUid, userId, verificationId, filter, packageName);
16695                            count++;
16696                        }
16697                    }
16698                }
16699            }
16700        }
16701
16702        if (count > 0) {
16703            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16704                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16705                    +  " for userId:" + userId);
16706            mIntentFilterVerifier.startVerifications(userId);
16707        } else {
16708            if (DEBUG_DOMAIN_VERIFICATION) {
16709                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16710            }
16711        }
16712    }
16713
16714    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16715        final ComponentName cn  = filter.activity.getComponentName();
16716        final String packageName = cn.getPackageName();
16717
16718        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16719                packageName);
16720        if (ivi == null) {
16721            return true;
16722        }
16723        int status = ivi.getStatus();
16724        switch (status) {
16725            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16726            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16727                return true;
16728
16729            default:
16730                // Nothing to do
16731                return false;
16732        }
16733    }
16734
16735    private static boolean isMultiArch(ApplicationInfo info) {
16736        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16737    }
16738
16739    private static boolean isExternal(PackageParser.Package pkg) {
16740        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16741    }
16742
16743    private static boolean isExternal(PackageSetting ps) {
16744        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16745    }
16746
16747    private static boolean isSystemApp(PackageParser.Package pkg) {
16748        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16749    }
16750
16751    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16752        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16753    }
16754
16755    private static boolean isOemApp(PackageParser.Package pkg) {
16756        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16757    }
16758
16759    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16760        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16761    }
16762
16763    private static boolean isSystemApp(PackageSetting ps) {
16764        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16765    }
16766
16767    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16768        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16769    }
16770
16771    private int packageFlagsToInstallFlags(PackageSetting ps) {
16772        int installFlags = 0;
16773        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16774            // This existing package was an external ASEC install when we have
16775            // the external flag without a UUID
16776            installFlags |= PackageManager.INSTALL_EXTERNAL;
16777        }
16778        if (ps.isForwardLocked()) {
16779            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16780        }
16781        return installFlags;
16782    }
16783
16784    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16785        if (isExternal(pkg)) {
16786            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16787                return mSettings.getExternalVersion();
16788            } else {
16789                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16790            }
16791        } else {
16792            return mSettings.getInternalVersion();
16793        }
16794    }
16795
16796    private void deleteTempPackageFiles() {
16797        final FilenameFilter filter = new FilenameFilter() {
16798            public boolean accept(File dir, String name) {
16799                return name.startsWith("vmdl") && name.endsWith(".tmp");
16800            }
16801        };
16802        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16803            file.delete();
16804        }
16805    }
16806
16807    @Override
16808    public void deletePackageAsUser(String packageName, int versionCode,
16809            IPackageDeleteObserver observer, int userId, int flags) {
16810        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
16811                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
16812    }
16813
16814    @Override
16815    public void deletePackageVersioned(VersionedPackage versionedPackage,
16816            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16817        final int callingUid = Binder.getCallingUid();
16818        mContext.enforceCallingOrSelfPermission(
16819                android.Manifest.permission.DELETE_PACKAGES, null);
16820        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
16821        Preconditions.checkNotNull(versionedPackage);
16822        Preconditions.checkNotNull(observer);
16823        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
16824                PackageManager.VERSION_CODE_HIGHEST,
16825                Integer.MAX_VALUE, "versionCode must be >= -1");
16826
16827        final String packageName = versionedPackage.getPackageName();
16828        final int versionCode = versionedPackage.getVersionCode();
16829        final String internalPackageName;
16830        synchronized (mPackages) {
16831            // Normalize package name to handle renamed packages and static libs
16832            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
16833                    versionedPackage.getVersionCode());
16834        }
16835
16836        final int uid = Binder.getCallingUid();
16837        if (!isOrphaned(internalPackageName)
16838                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
16839            try {
16840                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16841                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16842                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16843                observer.onUserActionRequired(intent);
16844            } catch (RemoteException re) {
16845            }
16846            return;
16847        }
16848        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16849        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16850        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16851            mContext.enforceCallingOrSelfPermission(
16852                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16853                    "deletePackage for user " + userId);
16854        }
16855
16856        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16857            try {
16858                observer.onPackageDeleted(packageName,
16859                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16860            } catch (RemoteException re) {
16861            }
16862            return;
16863        }
16864
16865        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
16866            try {
16867                observer.onPackageDeleted(packageName,
16868                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16869            } catch (RemoteException re) {
16870            }
16871            return;
16872        }
16873
16874        if (DEBUG_REMOVE) {
16875            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
16876                    + " deleteAllUsers: " + deleteAllUsers + " version="
16877                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
16878                    ? "VERSION_CODE_HIGHEST" : versionCode));
16879        }
16880        // Queue up an async operation since the package deletion may take a little while.
16881        mHandler.post(new Runnable() {
16882            public void run() {
16883                mHandler.removeCallbacks(this);
16884                int returnCode;
16885                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
16886                boolean doDeletePackage = true;
16887                if (ps != null) {
16888                    final boolean targetIsInstantApp =
16889                            ps.getInstantApp(UserHandle.getUserId(callingUid));
16890                    doDeletePackage = !targetIsInstantApp
16891                            || canViewInstantApps;
16892                }
16893                if (doDeletePackage) {
16894                    if (!deleteAllUsers) {
16895                        returnCode = deletePackageX(internalPackageName, versionCode,
16896                                userId, deleteFlags);
16897                    } else {
16898                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
16899                                internalPackageName, users);
16900                        // If nobody is blocking uninstall, proceed with delete for all users
16901                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16902                            returnCode = deletePackageX(internalPackageName, versionCode,
16903                                    userId, deleteFlags);
16904                        } else {
16905                            // Otherwise uninstall individually for users with blockUninstalls=false
16906                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16907                            for (int userId : users) {
16908                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16909                                    returnCode = deletePackageX(internalPackageName, versionCode,
16910                                            userId, userFlags);
16911                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16912                                        Slog.w(TAG, "Package delete failed for user " + userId
16913                                                + ", returnCode " + returnCode);
16914                                    }
16915                                }
16916                            }
16917                            // The app has only been marked uninstalled for certain users.
16918                            // We still need to report that delete was blocked
16919                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16920                        }
16921                    }
16922                } else {
16923                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16924                }
16925                try {
16926                    observer.onPackageDeleted(packageName, returnCode, null);
16927                } catch (RemoteException e) {
16928                    Log.i(TAG, "Observer no longer exists.");
16929                } //end catch
16930            } //end run
16931        });
16932    }
16933
16934    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
16935        if (pkg.staticSharedLibName != null) {
16936            return pkg.manifestPackageName;
16937        }
16938        return pkg.packageName;
16939    }
16940
16941    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
16942        // Handle renamed packages
16943        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
16944        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
16945
16946        // Is this a static library?
16947        SparseArray<SharedLibraryEntry> versionedLib =
16948                mStaticLibsByDeclaringPackage.get(packageName);
16949        if (versionedLib == null || versionedLib.size() <= 0) {
16950            return packageName;
16951        }
16952
16953        // Figure out which lib versions the caller can see
16954        SparseIntArray versionsCallerCanSee = null;
16955        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
16956        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
16957                && callingAppId != Process.ROOT_UID) {
16958            versionsCallerCanSee = new SparseIntArray();
16959            String libName = versionedLib.valueAt(0).info.getName();
16960            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
16961            if (uidPackages != null) {
16962                for (String uidPackage : uidPackages) {
16963                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
16964                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
16965                    if (libIdx >= 0) {
16966                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
16967                        versionsCallerCanSee.append(libVersion, libVersion);
16968                    }
16969                }
16970            }
16971        }
16972
16973        // Caller can see nothing - done
16974        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
16975            return packageName;
16976        }
16977
16978        // Find the version the caller can see and the app version code
16979        SharedLibraryEntry highestVersion = null;
16980        final int versionCount = versionedLib.size();
16981        for (int i = 0; i < versionCount; i++) {
16982            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
16983            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
16984                    libEntry.info.getVersion()) < 0) {
16985                continue;
16986            }
16987            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
16988            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
16989                if (libVersionCode == versionCode) {
16990                    return libEntry.apk;
16991                }
16992            } else if (highestVersion == null) {
16993                highestVersion = libEntry;
16994            } else if (libVersionCode  > highestVersion.info
16995                    .getDeclaringPackage().getVersionCode()) {
16996                highestVersion = libEntry;
16997            }
16998        }
16999
17000        if (highestVersion != null) {
17001            return highestVersion.apk;
17002        }
17003
17004        return packageName;
17005    }
17006
17007    boolean isCallerVerifier(int callingUid) {
17008        final int callingUserId = UserHandle.getUserId(callingUid);
17009        return mRequiredVerifierPackage != null &&
17010                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17011    }
17012
17013    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17014        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17015              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17016            return true;
17017        }
17018        final int callingUserId = UserHandle.getUserId(callingUid);
17019        // If the caller installed the pkgName, then allow it to silently uninstall.
17020        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17021            return true;
17022        }
17023
17024        // Allow package verifier to silently uninstall.
17025        if (mRequiredVerifierPackage != null &&
17026                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17027            return true;
17028        }
17029
17030        // Allow package uninstaller to silently uninstall.
17031        if (mRequiredUninstallerPackage != null &&
17032                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17033            return true;
17034        }
17035
17036        // Allow storage manager to silently uninstall.
17037        if (mStorageManagerPackage != null &&
17038                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17039            return true;
17040        }
17041
17042        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17043        // uninstall for device owner provisioning.
17044        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17045                == PERMISSION_GRANTED) {
17046            return true;
17047        }
17048
17049        return false;
17050    }
17051
17052    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17053        int[] result = EMPTY_INT_ARRAY;
17054        for (int userId : userIds) {
17055            if (getBlockUninstallForUser(packageName, userId)) {
17056                result = ArrayUtils.appendInt(result, userId);
17057            }
17058        }
17059        return result;
17060    }
17061
17062    @Override
17063    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17064        final int callingUid = Binder.getCallingUid();
17065        if (getInstantAppPackageName(callingUid) != null
17066                && !isCallerSameApp(packageName, callingUid)) {
17067            return false;
17068        }
17069        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17070    }
17071
17072    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17073        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17074                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17075        try {
17076            if (dpm != null) {
17077                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17078                        /* callingUserOnly =*/ false);
17079                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17080                        : deviceOwnerComponentName.getPackageName();
17081                // Does the package contains the device owner?
17082                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17083                // this check is probably not needed, since DO should be registered as a device
17084                // admin on some user too. (Original bug for this: b/17657954)
17085                if (packageName.equals(deviceOwnerPackageName)) {
17086                    return true;
17087                }
17088                // Does it contain a device admin for any user?
17089                int[] users;
17090                if (userId == UserHandle.USER_ALL) {
17091                    users = sUserManager.getUserIds();
17092                } else {
17093                    users = new int[]{userId};
17094                }
17095                for (int i = 0; i < users.length; ++i) {
17096                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17097                        return true;
17098                    }
17099                }
17100            }
17101        } catch (RemoteException e) {
17102        }
17103        return false;
17104    }
17105
17106    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17107        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17108    }
17109
17110    /**
17111     *  This method is an internal method that could be get invoked either
17112     *  to delete an installed package or to clean up a failed installation.
17113     *  After deleting an installed package, a broadcast is sent to notify any
17114     *  listeners that the package has been removed. For cleaning up a failed
17115     *  installation, the broadcast is not necessary since the package's
17116     *  installation wouldn't have sent the initial broadcast either
17117     *  The key steps in deleting a package are
17118     *  deleting the package information in internal structures like mPackages,
17119     *  deleting the packages base directories through installd
17120     *  updating mSettings to reflect current status
17121     *  persisting settings for later use
17122     *  sending a broadcast if necessary
17123     */
17124    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17125        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17126        final boolean res;
17127
17128        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17129                ? UserHandle.USER_ALL : userId;
17130
17131        if (isPackageDeviceAdmin(packageName, removeUser)) {
17132            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17133            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17134        }
17135
17136        PackageSetting uninstalledPs = null;
17137        PackageParser.Package pkg = null;
17138
17139        // for the uninstall-updates case and restricted profiles, remember the per-
17140        // user handle installed state
17141        int[] allUsers;
17142        synchronized (mPackages) {
17143            uninstalledPs = mSettings.mPackages.get(packageName);
17144            if (uninstalledPs == null) {
17145                Slog.w(TAG, "Not removing non-existent package " + packageName);
17146                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17147            }
17148
17149            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17150                    && uninstalledPs.versionCode != versionCode) {
17151                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17152                        + uninstalledPs.versionCode + " != " + versionCode);
17153                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17154            }
17155
17156            // Static shared libs can be declared by any package, so let us not
17157            // allow removing a package if it provides a lib others depend on.
17158            pkg = mPackages.get(packageName);
17159
17160            allUsers = sUserManager.getUserIds();
17161
17162            if (pkg != null && pkg.staticSharedLibName != null) {
17163                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17164                        pkg.staticSharedLibVersion);
17165                if (libEntry != null) {
17166                    for (int currUserId : allUsers) {
17167                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17168                            continue;
17169                        }
17170                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17171                                libEntry.info, 0, currUserId);
17172                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17173                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17174                                    + " hosting lib " + libEntry.info.getName() + " version "
17175                                    + libEntry.info.getVersion() + " used by " + libClientPackages
17176                                    + " for user " + currUserId);
17177                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17178                        }
17179                    }
17180                }
17181            }
17182
17183            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17184        }
17185
17186        final int freezeUser;
17187        if (isUpdatedSystemApp(uninstalledPs)
17188                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17189            // We're downgrading a system app, which will apply to all users, so
17190            // freeze them all during the downgrade
17191            freezeUser = UserHandle.USER_ALL;
17192        } else {
17193            freezeUser = removeUser;
17194        }
17195
17196        synchronized (mInstallLock) {
17197            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17198            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17199                    deleteFlags, "deletePackageX")) {
17200                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17201                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17202            }
17203            synchronized (mPackages) {
17204                if (res) {
17205                    if (pkg != null) {
17206                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17207                    }
17208                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17209                    updateInstantAppInstallerLocked(packageName);
17210                }
17211            }
17212        }
17213
17214        if (res) {
17215            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17216            info.sendPackageRemovedBroadcasts(killApp);
17217            info.sendSystemPackageUpdatedBroadcasts();
17218            info.sendSystemPackageAppearedBroadcasts();
17219        }
17220        // Force a gc here.
17221        Runtime.getRuntime().gc();
17222        // Delete the resources here after sending the broadcast to let
17223        // other processes clean up before deleting resources.
17224        if (info.args != null) {
17225            synchronized (mInstallLock) {
17226                info.args.doPostDeleteLI(true);
17227            }
17228        }
17229
17230        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17231    }
17232
17233    static class PackageRemovedInfo {
17234        final PackageSender packageSender;
17235        String removedPackage;
17236        String installerPackageName;
17237        int uid = -1;
17238        int removedAppId = -1;
17239        int[] origUsers;
17240        int[] removedUsers = null;
17241        int[] broadcastUsers = null;
17242        SparseArray<Integer> installReasons;
17243        boolean isRemovedPackageSystemUpdate = false;
17244        boolean isUpdate;
17245        boolean dataRemoved;
17246        boolean removedForAllUsers;
17247        boolean isStaticSharedLib;
17248        // Clean up resources deleted packages.
17249        InstallArgs args = null;
17250        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17251        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17252
17253        PackageRemovedInfo(PackageSender packageSender) {
17254            this.packageSender = packageSender;
17255        }
17256
17257        void sendPackageRemovedBroadcasts(boolean killApp) {
17258            sendPackageRemovedBroadcastInternal(killApp);
17259            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17260            for (int i = 0; i < childCount; i++) {
17261                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17262                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17263            }
17264        }
17265
17266        void sendSystemPackageUpdatedBroadcasts() {
17267            if (isRemovedPackageSystemUpdate) {
17268                sendSystemPackageUpdatedBroadcastsInternal();
17269                final int childCount = (removedChildPackages != null)
17270                        ? removedChildPackages.size() : 0;
17271                for (int i = 0; i < childCount; i++) {
17272                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17273                    if (childInfo.isRemovedPackageSystemUpdate) {
17274                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17275                    }
17276                }
17277            }
17278        }
17279
17280        void sendSystemPackageAppearedBroadcasts() {
17281            final int packageCount = (appearedChildPackages != null)
17282                    ? appearedChildPackages.size() : 0;
17283            for (int i = 0; i < packageCount; i++) {
17284                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17285                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17286                    true /*sendBootCompleted*/, false /*startReceiver*/,
17287                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17288            }
17289        }
17290
17291        private void sendSystemPackageUpdatedBroadcastsInternal() {
17292            Bundle extras = new Bundle(2);
17293            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17294            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17295            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17296                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17297            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17298                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17299            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17300                null, null, 0, removedPackage, null, null);
17301            if (installerPackageName != null) {
17302                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17303                        removedPackage, extras, 0 /*flags*/,
17304                        installerPackageName, null, null);
17305                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17306                        removedPackage, extras, 0 /*flags*/,
17307                        installerPackageName, null, null);
17308            }
17309        }
17310
17311        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17312            // Don't send static shared library removal broadcasts as these
17313            // libs are visible only the the apps that depend on them an one
17314            // cannot remove the library if it has a dependency.
17315            if (isStaticSharedLib) {
17316                return;
17317            }
17318            Bundle extras = new Bundle(2);
17319            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17320            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17321            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17322            if (isUpdate || isRemovedPackageSystemUpdate) {
17323                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17324            }
17325            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17326            if (removedPackage != null) {
17327                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17328                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17329                if (installerPackageName != null) {
17330                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17331                            removedPackage, extras, 0 /*flags*/,
17332                            installerPackageName, null, broadcastUsers);
17333                }
17334                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17335                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17336                        removedPackage, extras,
17337                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17338                        null, null, broadcastUsers);
17339                }
17340            }
17341            if (removedAppId >= 0) {
17342                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17343                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17344                    null, null, broadcastUsers);
17345            }
17346        }
17347
17348        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17349            removedUsers = userIds;
17350            if (removedUsers == null) {
17351                broadcastUsers = null;
17352                return;
17353            }
17354
17355            broadcastUsers = EMPTY_INT_ARRAY;
17356            for (int i = userIds.length - 1; i >= 0; --i) {
17357                final int userId = userIds[i];
17358                if (deletedPackageSetting.getInstantApp(userId)) {
17359                    continue;
17360                }
17361                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17362            }
17363        }
17364    }
17365
17366    /*
17367     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17368     * flag is not set, the data directory is removed as well.
17369     * make sure this flag is set for partially installed apps. If not its meaningless to
17370     * delete a partially installed application.
17371     */
17372    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17373            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17374        String packageName = ps.name;
17375        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17376        // Retrieve object to delete permissions for shared user later on
17377        final PackageParser.Package deletedPkg;
17378        final PackageSetting deletedPs;
17379        // reader
17380        synchronized (mPackages) {
17381            deletedPkg = mPackages.get(packageName);
17382            deletedPs = mSettings.mPackages.get(packageName);
17383            if (outInfo != null) {
17384                outInfo.removedPackage = packageName;
17385                outInfo.installerPackageName = ps.installerPackageName;
17386                outInfo.isStaticSharedLib = deletedPkg != null
17387                        && deletedPkg.staticSharedLibName != null;
17388                outInfo.populateUsers(deletedPs == null ? null
17389                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17390            }
17391        }
17392
17393        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17394
17395        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17396            final PackageParser.Package resolvedPkg;
17397            if (deletedPkg != null) {
17398                resolvedPkg = deletedPkg;
17399            } else {
17400                // We don't have a parsed package when it lives on an ejected
17401                // adopted storage device, so fake something together
17402                resolvedPkg = new PackageParser.Package(ps.name);
17403                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17404            }
17405            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17406                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17407            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17408            if (outInfo != null) {
17409                outInfo.dataRemoved = true;
17410            }
17411            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17412        }
17413
17414        int removedAppId = -1;
17415
17416        // writer
17417        synchronized (mPackages) {
17418            boolean installedStateChanged = false;
17419            if (deletedPs != null) {
17420                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17421                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17422                    clearDefaultBrowserIfNeeded(packageName);
17423                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17424                    removedAppId = mSettings.removePackageLPw(packageName);
17425                    if (outInfo != null) {
17426                        outInfo.removedAppId = removedAppId;
17427                    }
17428                    mPermissionManager.updatePermissions(
17429                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17430                    if (deletedPs.sharedUser != null) {
17431                        // Remove permissions associated with package. Since runtime
17432                        // permissions are per user we have to kill the removed package
17433                        // or packages running under the shared user of the removed
17434                        // package if revoking the permissions requested only by the removed
17435                        // package is successful and this causes a change in gids.
17436                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17437                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17438                                    userId);
17439                            if (userIdToKill == UserHandle.USER_ALL
17440                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17441                                // If gids changed for this user, kill all affected packages.
17442                                mHandler.post(new Runnable() {
17443                                    @Override
17444                                    public void run() {
17445                                        // This has to happen with no lock held.
17446                                        killApplication(deletedPs.name, deletedPs.appId,
17447                                                KILL_APP_REASON_GIDS_CHANGED);
17448                                    }
17449                                });
17450                                break;
17451                            }
17452                        }
17453                    }
17454                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17455                }
17456                // make sure to preserve per-user disabled state if this removal was just
17457                // a downgrade of a system app to the factory package
17458                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17459                    if (DEBUG_REMOVE) {
17460                        Slog.d(TAG, "Propagating install state across downgrade");
17461                    }
17462                    for (int userId : allUserHandles) {
17463                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17464                        if (DEBUG_REMOVE) {
17465                            Slog.d(TAG, "    user " + userId + " => " + installed);
17466                        }
17467                        if (installed != ps.getInstalled(userId)) {
17468                            installedStateChanged = true;
17469                        }
17470                        ps.setInstalled(installed, userId);
17471                    }
17472                }
17473            }
17474            // can downgrade to reader
17475            if (writeSettings) {
17476                // Save settings now
17477                mSettings.writeLPr();
17478            }
17479            if (installedStateChanged) {
17480                mSettings.writeKernelMappingLPr(ps);
17481            }
17482        }
17483        if (removedAppId != -1) {
17484            // A user ID was deleted here. Go through all users and remove it
17485            // from KeyStore.
17486            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17487        }
17488    }
17489
17490    static boolean locationIsPrivileged(File path) {
17491        try {
17492            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17493                    .getCanonicalPath();
17494            return path.getCanonicalPath().startsWith(privilegedAppDir);
17495        } catch (IOException e) {
17496            Slog.e(TAG, "Unable to access code path " + path);
17497        }
17498        return false;
17499    }
17500
17501    static boolean locationIsOem(File path) {
17502        try {
17503            return path.getCanonicalPath().startsWith(
17504                    Environment.getOemDirectory().getCanonicalPath());
17505        } catch (IOException e) {
17506            Slog.e(TAG, "Unable to access code path " + path);
17507        }
17508        return false;
17509    }
17510
17511    /*
17512     * Tries to delete system package.
17513     */
17514    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17515            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17516            boolean writeSettings) {
17517        if (deletedPs.parentPackageName != null) {
17518            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17519            return false;
17520        }
17521
17522        final boolean applyUserRestrictions
17523                = (allUserHandles != null) && (outInfo.origUsers != null);
17524        final PackageSetting disabledPs;
17525        // Confirm if the system package has been updated
17526        // An updated system app can be deleted. This will also have to restore
17527        // the system pkg from system partition
17528        // reader
17529        synchronized (mPackages) {
17530            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17531        }
17532
17533        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17534                + " disabledPs=" + disabledPs);
17535
17536        if (disabledPs == null) {
17537            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17538            return false;
17539        } else if (DEBUG_REMOVE) {
17540            Slog.d(TAG, "Deleting system pkg from data partition");
17541        }
17542
17543        if (DEBUG_REMOVE) {
17544            if (applyUserRestrictions) {
17545                Slog.d(TAG, "Remembering install states:");
17546                for (int userId : allUserHandles) {
17547                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17548                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17549                }
17550            }
17551        }
17552
17553        // Delete the updated package
17554        outInfo.isRemovedPackageSystemUpdate = true;
17555        if (outInfo.removedChildPackages != null) {
17556            final int childCount = (deletedPs.childPackageNames != null)
17557                    ? deletedPs.childPackageNames.size() : 0;
17558            for (int i = 0; i < childCount; i++) {
17559                String childPackageName = deletedPs.childPackageNames.get(i);
17560                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17561                        .contains(childPackageName)) {
17562                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17563                            childPackageName);
17564                    if (childInfo != null) {
17565                        childInfo.isRemovedPackageSystemUpdate = true;
17566                    }
17567                }
17568            }
17569        }
17570
17571        if (disabledPs.versionCode < deletedPs.versionCode) {
17572            // Delete data for downgrades
17573            flags &= ~PackageManager.DELETE_KEEP_DATA;
17574        } else {
17575            // Preserve data by setting flag
17576            flags |= PackageManager.DELETE_KEEP_DATA;
17577        }
17578
17579        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17580                outInfo, writeSettings, disabledPs.pkg);
17581        if (!ret) {
17582            return false;
17583        }
17584
17585        // writer
17586        synchronized (mPackages) {
17587            // NOTE: The system package always needs to be enabled; even if it's for
17588            // a compressed stub. If we don't, installing the system package fails
17589            // during scan [scanning checks the disabled packages]. We will reverse
17590            // this later, after we've "installed" the stub.
17591            // Reinstate the old system package
17592            enableSystemPackageLPw(disabledPs.pkg);
17593            // Remove any native libraries from the upgraded package.
17594            removeNativeBinariesLI(deletedPs);
17595        }
17596
17597        // Install the system package
17598        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17599        try {
17600            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
17601                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17602        } catch (PackageManagerException e) {
17603            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17604                    + e.getMessage());
17605            return false;
17606        } finally {
17607            if (disabledPs.pkg.isStub) {
17608                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17609            }
17610        }
17611        return true;
17612    }
17613
17614    /**
17615     * Installs a package that's already on the system partition.
17616     */
17617    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
17618            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17619            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17620                    throws PackageManagerException {
17621        @ParseFlags int parseFlags =
17622                mDefParseFlags
17623                | PackageParser.PARSE_MUST_BE_APK
17624                | PackageParser.PARSE_IS_SYSTEM_DIR;
17625        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17626        if (isPrivileged || locationIsPrivileged(codePath)) {
17627            scanFlags |= SCAN_AS_PRIVILEGED;
17628        }
17629        if (locationIsOem(codePath)) {
17630            scanFlags |= SCAN_AS_OEM;
17631        }
17632
17633        final PackageParser.Package pkg =
17634                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17635
17636        try {
17637            // update shared libraries for the newly re-installed system package
17638            updateSharedLibrariesLPr(pkg, null);
17639        } catch (PackageManagerException e) {
17640            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17641        }
17642
17643        prepareAppDataAfterInstallLIF(pkg);
17644
17645        // writer
17646        synchronized (mPackages) {
17647            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17648
17649            // Propagate the permissions state as we do not want to drop on the floor
17650            // runtime permissions. The update permissions method below will take
17651            // care of removing obsolete permissions and grant install permissions.
17652            if (origPermissionState != null) {
17653                ps.getPermissionsState().copyFrom(origPermissionState);
17654            }
17655            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17656                    mPermissionCallback);
17657
17658            final boolean applyUserRestrictions
17659                    = (allUserHandles != null) && (origUserHandles != null);
17660            if (applyUserRestrictions) {
17661                boolean installedStateChanged = false;
17662                if (DEBUG_REMOVE) {
17663                    Slog.d(TAG, "Propagating install state across reinstall");
17664                }
17665                for (int userId : allUserHandles) {
17666                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17667                    if (DEBUG_REMOVE) {
17668                        Slog.d(TAG, "    user " + userId + " => " + installed);
17669                    }
17670                    if (installed != ps.getInstalled(userId)) {
17671                        installedStateChanged = true;
17672                    }
17673                    ps.setInstalled(installed, userId);
17674
17675                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17676                }
17677                // Regardless of writeSettings we need to ensure that this restriction
17678                // state propagation is persisted
17679                mSettings.writeAllUsersPackageRestrictionsLPr();
17680                if (installedStateChanged) {
17681                    mSettings.writeKernelMappingLPr(ps);
17682                }
17683            }
17684            // can downgrade to reader here
17685            if (writeSettings) {
17686                mSettings.writeLPr();
17687            }
17688        }
17689        return pkg;
17690    }
17691
17692    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17693            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17694            PackageRemovedInfo outInfo, boolean writeSettings,
17695            PackageParser.Package replacingPackage) {
17696        synchronized (mPackages) {
17697            if (outInfo != null) {
17698                outInfo.uid = ps.appId;
17699            }
17700
17701            if (outInfo != null && outInfo.removedChildPackages != null) {
17702                final int childCount = (ps.childPackageNames != null)
17703                        ? ps.childPackageNames.size() : 0;
17704                for (int i = 0; i < childCount; i++) {
17705                    String childPackageName = ps.childPackageNames.get(i);
17706                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17707                    if (childPs == null) {
17708                        return false;
17709                    }
17710                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17711                            childPackageName);
17712                    if (childInfo != null) {
17713                        childInfo.uid = childPs.appId;
17714                    }
17715                }
17716            }
17717        }
17718
17719        // Delete package data from internal structures and also remove data if flag is set
17720        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17721
17722        // Delete the child packages data
17723        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17724        for (int i = 0; i < childCount; i++) {
17725            PackageSetting childPs;
17726            synchronized (mPackages) {
17727                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17728            }
17729            if (childPs != null) {
17730                PackageRemovedInfo childOutInfo = (outInfo != null
17731                        && outInfo.removedChildPackages != null)
17732                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17733                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17734                        && (replacingPackage != null
17735                        && !replacingPackage.hasChildPackage(childPs.name))
17736                        ? flags & ~DELETE_KEEP_DATA : flags;
17737                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17738                        deleteFlags, writeSettings);
17739            }
17740        }
17741
17742        // Delete application code and resources only for parent packages
17743        if (ps.parentPackageName == null) {
17744            if (deleteCodeAndResources && (outInfo != null)) {
17745                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17746                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17747                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17748            }
17749        }
17750
17751        return true;
17752    }
17753
17754    @Override
17755    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17756            int userId) {
17757        mContext.enforceCallingOrSelfPermission(
17758                android.Manifest.permission.DELETE_PACKAGES, null);
17759        synchronized (mPackages) {
17760            // Cannot block uninstall of static shared libs as they are
17761            // considered a part of the using app (emulating static linking).
17762            // Also static libs are installed always on internal storage.
17763            PackageParser.Package pkg = mPackages.get(packageName);
17764            if (pkg != null && pkg.staticSharedLibName != null) {
17765                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17766                        + " providing static shared library: " + pkg.staticSharedLibName);
17767                return false;
17768            }
17769            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
17770            mSettings.writePackageRestrictionsLPr(userId);
17771        }
17772        return true;
17773    }
17774
17775    @Override
17776    public boolean getBlockUninstallForUser(String packageName, int userId) {
17777        synchronized (mPackages) {
17778            final PackageSetting ps = mSettings.mPackages.get(packageName);
17779            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
17780                return false;
17781            }
17782            return mSettings.getBlockUninstallLPr(userId, packageName);
17783        }
17784    }
17785
17786    @Override
17787    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17788        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
17789        synchronized (mPackages) {
17790            PackageSetting ps = mSettings.mPackages.get(packageName);
17791            if (ps == null) {
17792                Log.w(TAG, "Package doesn't exist: " + packageName);
17793                return false;
17794            }
17795            if (systemUserApp) {
17796                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17797            } else {
17798                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17799            }
17800            mSettings.writeLPr();
17801        }
17802        return true;
17803    }
17804
17805    /*
17806     * This method handles package deletion in general
17807     */
17808    private boolean deletePackageLIF(String packageName, UserHandle user,
17809            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17810            PackageRemovedInfo outInfo, boolean writeSettings,
17811            PackageParser.Package replacingPackage) {
17812        if (packageName == null) {
17813            Slog.w(TAG, "Attempt to delete null packageName.");
17814            return false;
17815        }
17816
17817        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17818
17819        PackageSetting ps;
17820        synchronized (mPackages) {
17821            ps = mSettings.mPackages.get(packageName);
17822            if (ps == null) {
17823                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17824                return false;
17825            }
17826
17827            if (ps.parentPackageName != null && (!isSystemApp(ps)
17828                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17829                if (DEBUG_REMOVE) {
17830                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17831                            + ((user == null) ? UserHandle.USER_ALL : user));
17832                }
17833                final int removedUserId = (user != null) ? user.getIdentifier()
17834                        : UserHandle.USER_ALL;
17835                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17836                    return false;
17837                }
17838                markPackageUninstalledForUserLPw(ps, user);
17839                scheduleWritePackageRestrictionsLocked(user);
17840                return true;
17841            }
17842        }
17843
17844        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17845                && user.getIdentifier() != UserHandle.USER_ALL)) {
17846            // The caller is asking that the package only be deleted for a single
17847            // user.  To do this, we just mark its uninstalled state and delete
17848            // its data. If this is a system app, we only allow this to happen if
17849            // they have set the special DELETE_SYSTEM_APP which requests different
17850            // semantics than normal for uninstalling system apps.
17851            markPackageUninstalledForUserLPw(ps, user);
17852
17853            if (!isSystemApp(ps)) {
17854                // Do not uninstall the APK if an app should be cached
17855                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17856                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17857                    // Other user still have this package installed, so all
17858                    // we need to do is clear this user's data and save that
17859                    // it is uninstalled.
17860                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17861                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17862                        return false;
17863                    }
17864                    scheduleWritePackageRestrictionsLocked(user);
17865                    return true;
17866                } else {
17867                    // We need to set it back to 'installed' so the uninstall
17868                    // broadcasts will be sent correctly.
17869                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17870                    ps.setInstalled(true, user.getIdentifier());
17871                    mSettings.writeKernelMappingLPr(ps);
17872                }
17873            } else {
17874                // This is a system app, so we assume that the
17875                // other users still have this package installed, so all
17876                // we need to do is clear this user's data and save that
17877                // it is uninstalled.
17878                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17879                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17880                    return false;
17881                }
17882                scheduleWritePackageRestrictionsLocked(user);
17883                return true;
17884            }
17885        }
17886
17887        // If we are deleting a composite package for all users, keep track
17888        // of result for each child.
17889        if (ps.childPackageNames != null && outInfo != null) {
17890            synchronized (mPackages) {
17891                final int childCount = ps.childPackageNames.size();
17892                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17893                for (int i = 0; i < childCount; i++) {
17894                    String childPackageName = ps.childPackageNames.get(i);
17895                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
17896                    childInfo.removedPackage = childPackageName;
17897                    childInfo.installerPackageName = ps.installerPackageName;
17898                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17899                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17900                    if (childPs != null) {
17901                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17902                    }
17903                }
17904            }
17905        }
17906
17907        boolean ret = false;
17908        if (isSystemApp(ps)) {
17909            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17910            // When an updated system application is deleted we delete the existing resources
17911            // as well and fall back to existing code in system partition
17912            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17913        } else {
17914            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17915            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17916                    outInfo, writeSettings, replacingPackage);
17917        }
17918
17919        // Take a note whether we deleted the package for all users
17920        if (outInfo != null) {
17921            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17922            if (outInfo.removedChildPackages != null) {
17923                synchronized (mPackages) {
17924                    final int childCount = outInfo.removedChildPackages.size();
17925                    for (int i = 0; i < childCount; i++) {
17926                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17927                        if (childInfo != null) {
17928                            childInfo.removedForAllUsers = mPackages.get(
17929                                    childInfo.removedPackage) == null;
17930                        }
17931                    }
17932                }
17933            }
17934            // If we uninstalled an update to a system app there may be some
17935            // child packages that appeared as they are declared in the system
17936            // app but were not declared in the update.
17937            if (isSystemApp(ps)) {
17938                synchronized (mPackages) {
17939                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17940                    final int childCount = (updatedPs.childPackageNames != null)
17941                            ? updatedPs.childPackageNames.size() : 0;
17942                    for (int i = 0; i < childCount; i++) {
17943                        String childPackageName = updatedPs.childPackageNames.get(i);
17944                        if (outInfo.removedChildPackages == null
17945                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17946                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17947                            if (childPs == null) {
17948                                continue;
17949                            }
17950                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17951                            installRes.name = childPackageName;
17952                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17953                            installRes.pkg = mPackages.get(childPackageName);
17954                            installRes.uid = childPs.pkg.applicationInfo.uid;
17955                            if (outInfo.appearedChildPackages == null) {
17956                                outInfo.appearedChildPackages = new ArrayMap<>();
17957                            }
17958                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17959                        }
17960                    }
17961                }
17962            }
17963        }
17964
17965        return ret;
17966    }
17967
17968    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17969        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17970                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17971        for (int nextUserId : userIds) {
17972            if (DEBUG_REMOVE) {
17973                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17974            }
17975            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17976                    false /*installed*/,
17977                    true /*stopped*/,
17978                    true /*notLaunched*/,
17979                    false /*hidden*/,
17980                    false /*suspended*/,
17981                    false /*instantApp*/,
17982                    false /*virtualPreload*/,
17983                    null /*lastDisableAppCaller*/,
17984                    null /*enabledComponents*/,
17985                    null /*disabledComponents*/,
17986                    ps.readUserState(nextUserId).domainVerificationStatus,
17987                    0, PackageManager.INSTALL_REASON_UNKNOWN);
17988        }
17989        mSettings.writeKernelMappingLPr(ps);
17990    }
17991
17992    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17993            PackageRemovedInfo outInfo) {
17994        final PackageParser.Package pkg;
17995        synchronized (mPackages) {
17996            pkg = mPackages.get(ps.name);
17997        }
17998
17999        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18000                : new int[] {userId};
18001        for (int nextUserId : userIds) {
18002            if (DEBUG_REMOVE) {
18003                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18004                        + nextUserId);
18005            }
18006
18007            destroyAppDataLIF(pkg, userId,
18008                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18009            destroyAppProfilesLIF(pkg, userId);
18010            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18011            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18012            schedulePackageCleaning(ps.name, nextUserId, false);
18013            synchronized (mPackages) {
18014                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18015                    scheduleWritePackageRestrictionsLocked(nextUserId);
18016                }
18017                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18018            }
18019        }
18020
18021        if (outInfo != null) {
18022            outInfo.removedPackage = ps.name;
18023            outInfo.installerPackageName = ps.installerPackageName;
18024            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18025            outInfo.removedAppId = ps.appId;
18026            outInfo.removedUsers = userIds;
18027            outInfo.broadcastUsers = userIds;
18028        }
18029
18030        return true;
18031    }
18032
18033    private final class ClearStorageConnection implements ServiceConnection {
18034        IMediaContainerService mContainerService;
18035
18036        @Override
18037        public void onServiceConnected(ComponentName name, IBinder service) {
18038            synchronized (this) {
18039                mContainerService = IMediaContainerService.Stub
18040                        .asInterface(Binder.allowBlocking(service));
18041                notifyAll();
18042            }
18043        }
18044
18045        @Override
18046        public void onServiceDisconnected(ComponentName name) {
18047        }
18048    }
18049
18050    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18051        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18052
18053        final boolean mounted;
18054        if (Environment.isExternalStorageEmulated()) {
18055            mounted = true;
18056        } else {
18057            final String status = Environment.getExternalStorageState();
18058
18059            mounted = status.equals(Environment.MEDIA_MOUNTED)
18060                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18061        }
18062
18063        if (!mounted) {
18064            return;
18065        }
18066
18067        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18068        int[] users;
18069        if (userId == UserHandle.USER_ALL) {
18070            users = sUserManager.getUserIds();
18071        } else {
18072            users = new int[] { userId };
18073        }
18074        final ClearStorageConnection conn = new ClearStorageConnection();
18075        if (mContext.bindServiceAsUser(
18076                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18077            try {
18078                for (int curUser : users) {
18079                    long timeout = SystemClock.uptimeMillis() + 5000;
18080                    synchronized (conn) {
18081                        long now;
18082                        while (conn.mContainerService == null &&
18083                                (now = SystemClock.uptimeMillis()) < timeout) {
18084                            try {
18085                                conn.wait(timeout - now);
18086                            } catch (InterruptedException e) {
18087                            }
18088                        }
18089                    }
18090                    if (conn.mContainerService == null) {
18091                        return;
18092                    }
18093
18094                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18095                    clearDirectory(conn.mContainerService,
18096                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18097                    if (allData) {
18098                        clearDirectory(conn.mContainerService,
18099                                userEnv.buildExternalStorageAppDataDirs(packageName));
18100                        clearDirectory(conn.mContainerService,
18101                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18102                    }
18103                }
18104            } finally {
18105                mContext.unbindService(conn);
18106            }
18107        }
18108    }
18109
18110    @Override
18111    public void clearApplicationProfileData(String packageName) {
18112        enforceSystemOrRoot("Only the system can clear all profile data");
18113
18114        final PackageParser.Package pkg;
18115        synchronized (mPackages) {
18116            pkg = mPackages.get(packageName);
18117        }
18118
18119        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18120            synchronized (mInstallLock) {
18121                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18122            }
18123        }
18124    }
18125
18126    @Override
18127    public void clearApplicationUserData(final String packageName,
18128            final IPackageDataObserver observer, final int userId) {
18129        mContext.enforceCallingOrSelfPermission(
18130                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18131
18132        final int callingUid = Binder.getCallingUid();
18133        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18134                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18135
18136        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18137        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18138        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18139            throw new SecurityException("Cannot clear data for a protected package: "
18140                    + packageName);
18141        }
18142        // Queue up an async operation since the package deletion may take a little while.
18143        mHandler.post(new Runnable() {
18144            public void run() {
18145                mHandler.removeCallbacks(this);
18146                final boolean succeeded;
18147                if (!filterApp) {
18148                    try (PackageFreezer freezer = freezePackage(packageName,
18149                            "clearApplicationUserData")) {
18150                        synchronized (mInstallLock) {
18151                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18152                        }
18153                        clearExternalStorageDataSync(packageName, userId, true);
18154                        synchronized (mPackages) {
18155                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18156                                    packageName, userId);
18157                        }
18158                    }
18159                    if (succeeded) {
18160                        // invoke DeviceStorageMonitor's update method to clear any notifications
18161                        DeviceStorageMonitorInternal dsm = LocalServices
18162                                .getService(DeviceStorageMonitorInternal.class);
18163                        if (dsm != null) {
18164                            dsm.checkMemory();
18165                        }
18166                    }
18167                } else {
18168                    succeeded = false;
18169                }
18170                if (observer != null) {
18171                    try {
18172                        observer.onRemoveCompleted(packageName, succeeded);
18173                    } catch (RemoteException e) {
18174                        Log.i(TAG, "Observer no longer exists.");
18175                    }
18176                } //end if observer
18177            } //end run
18178        });
18179    }
18180
18181    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18182        if (packageName == null) {
18183            Slog.w(TAG, "Attempt to delete null packageName.");
18184            return false;
18185        }
18186
18187        // Try finding details about the requested package
18188        PackageParser.Package pkg;
18189        synchronized (mPackages) {
18190            pkg = mPackages.get(packageName);
18191            if (pkg == null) {
18192                final PackageSetting ps = mSettings.mPackages.get(packageName);
18193                if (ps != null) {
18194                    pkg = ps.pkg;
18195                }
18196            }
18197
18198            if (pkg == null) {
18199                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18200                return false;
18201            }
18202
18203            PackageSetting ps = (PackageSetting) pkg.mExtras;
18204            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18205        }
18206
18207        clearAppDataLIF(pkg, userId,
18208                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18209
18210        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18211        removeKeystoreDataIfNeeded(userId, appId);
18212
18213        UserManagerInternal umInternal = getUserManagerInternal();
18214        final int flags;
18215        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18216            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18217        } else if (umInternal.isUserRunning(userId)) {
18218            flags = StorageManager.FLAG_STORAGE_DE;
18219        } else {
18220            flags = 0;
18221        }
18222        prepareAppDataContentsLIF(pkg, userId, flags);
18223
18224        return true;
18225    }
18226
18227    /**
18228     * Reverts user permission state changes (permissions and flags) in
18229     * all packages for a given user.
18230     *
18231     * @param userId The device user for which to do a reset.
18232     */
18233    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18234        final int packageCount = mPackages.size();
18235        for (int i = 0; i < packageCount; i++) {
18236            PackageParser.Package pkg = mPackages.valueAt(i);
18237            PackageSetting ps = (PackageSetting) pkg.mExtras;
18238            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18239        }
18240    }
18241
18242    private void resetNetworkPolicies(int userId) {
18243        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18244    }
18245
18246    /**
18247     * Reverts user permission state changes (permissions and flags).
18248     *
18249     * @param ps The package for which to reset.
18250     * @param userId The device user for which to do a reset.
18251     */
18252    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18253            final PackageSetting ps, final int userId) {
18254        if (ps.pkg == null) {
18255            return;
18256        }
18257
18258        // These are flags that can change base on user actions.
18259        final int userSettableMask = FLAG_PERMISSION_USER_SET
18260                | FLAG_PERMISSION_USER_FIXED
18261                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18262                | FLAG_PERMISSION_REVIEW_REQUIRED;
18263
18264        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18265                | FLAG_PERMISSION_POLICY_FIXED;
18266
18267        boolean writeInstallPermissions = false;
18268        boolean writeRuntimePermissions = false;
18269
18270        final int permissionCount = ps.pkg.requestedPermissions.size();
18271        for (int i = 0; i < permissionCount; i++) {
18272            final String permName = ps.pkg.requestedPermissions.get(i);
18273            final BasePermission bp =
18274                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18275            if (bp == null) {
18276                continue;
18277            }
18278
18279            // If shared user we just reset the state to which only this app contributed.
18280            if (ps.sharedUser != null) {
18281                boolean used = false;
18282                final int packageCount = ps.sharedUser.packages.size();
18283                for (int j = 0; j < packageCount; j++) {
18284                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18285                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18286                            && pkg.pkg.requestedPermissions.contains(permName)) {
18287                        used = true;
18288                        break;
18289                    }
18290                }
18291                if (used) {
18292                    continue;
18293                }
18294            }
18295
18296            final PermissionsState permissionsState = ps.getPermissionsState();
18297
18298            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18299
18300            // Always clear the user settable flags.
18301            final boolean hasInstallState =
18302                    permissionsState.getInstallPermissionState(permName) != null;
18303            // If permission review is enabled and this is a legacy app, mark the
18304            // permission as requiring a review as this is the initial state.
18305            int flags = 0;
18306            if (mSettings.mPermissions.mPermissionReviewRequired
18307                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18308                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18309            }
18310            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18311                if (hasInstallState) {
18312                    writeInstallPermissions = true;
18313                } else {
18314                    writeRuntimePermissions = true;
18315                }
18316            }
18317
18318            // Below is only runtime permission handling.
18319            if (!bp.isRuntime()) {
18320                continue;
18321            }
18322
18323            // Never clobber system or policy.
18324            if ((oldFlags & policyOrSystemFlags) != 0) {
18325                continue;
18326            }
18327
18328            // If this permission was granted by default, make sure it is.
18329            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18330                if (permissionsState.grantRuntimePermission(bp, userId)
18331                        != PERMISSION_OPERATION_FAILURE) {
18332                    writeRuntimePermissions = true;
18333                }
18334            // If permission review is enabled the permissions for a legacy apps
18335            // are represented as constantly granted runtime ones, so don't revoke.
18336            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18337                // Otherwise, reset the permission.
18338                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18339                switch (revokeResult) {
18340                    case PERMISSION_OPERATION_SUCCESS:
18341                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18342                        writeRuntimePermissions = true;
18343                        final int appId = ps.appId;
18344                        mHandler.post(new Runnable() {
18345                            @Override
18346                            public void run() {
18347                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18348                            }
18349                        });
18350                    } break;
18351                }
18352            }
18353        }
18354
18355        // Synchronously write as we are taking permissions away.
18356        if (writeRuntimePermissions) {
18357            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18358        }
18359
18360        // Synchronously write as we are taking permissions away.
18361        if (writeInstallPermissions) {
18362            mSettings.writeLPr();
18363        }
18364    }
18365
18366    /**
18367     * Remove entries from the keystore daemon. Will only remove it if the
18368     * {@code appId} is valid.
18369     */
18370    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18371        if (appId < 0) {
18372            return;
18373        }
18374
18375        final KeyStore keyStore = KeyStore.getInstance();
18376        if (keyStore != null) {
18377            if (userId == UserHandle.USER_ALL) {
18378                for (final int individual : sUserManager.getUserIds()) {
18379                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18380                }
18381            } else {
18382                keyStore.clearUid(UserHandle.getUid(userId, appId));
18383            }
18384        } else {
18385            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18386        }
18387    }
18388
18389    @Override
18390    public void deleteApplicationCacheFiles(final String packageName,
18391            final IPackageDataObserver observer) {
18392        final int userId = UserHandle.getCallingUserId();
18393        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18394    }
18395
18396    @Override
18397    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18398            final IPackageDataObserver observer) {
18399        final int callingUid = Binder.getCallingUid();
18400        mContext.enforceCallingOrSelfPermission(
18401                android.Manifest.permission.DELETE_CACHE_FILES, null);
18402        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18403                /* requireFullPermission= */ true, /* checkShell= */ false,
18404                "delete application cache files");
18405        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18406                android.Manifest.permission.ACCESS_INSTANT_APPS);
18407
18408        final PackageParser.Package pkg;
18409        synchronized (mPackages) {
18410            pkg = mPackages.get(packageName);
18411        }
18412
18413        // Queue up an async operation since the package deletion may take a little while.
18414        mHandler.post(new Runnable() {
18415            public void run() {
18416                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18417                boolean doClearData = true;
18418                if (ps != null) {
18419                    final boolean targetIsInstantApp =
18420                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18421                    doClearData = !targetIsInstantApp
18422                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18423                }
18424                if (doClearData) {
18425                    synchronized (mInstallLock) {
18426                        final int flags = StorageManager.FLAG_STORAGE_DE
18427                                | StorageManager.FLAG_STORAGE_CE;
18428                        // We're only clearing cache files, so we don't care if the
18429                        // app is unfrozen and still able to run
18430                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18431                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18432                    }
18433                    clearExternalStorageDataSync(packageName, userId, false);
18434                }
18435                if (observer != null) {
18436                    try {
18437                        observer.onRemoveCompleted(packageName, true);
18438                    } catch (RemoteException e) {
18439                        Log.i(TAG, "Observer no longer exists.");
18440                    }
18441                }
18442            }
18443        });
18444    }
18445
18446    @Override
18447    public void getPackageSizeInfo(final String packageName, int userHandle,
18448            final IPackageStatsObserver observer) {
18449        throw new UnsupportedOperationException(
18450                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18451    }
18452
18453    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18454        final PackageSetting ps;
18455        synchronized (mPackages) {
18456            ps = mSettings.mPackages.get(packageName);
18457            if (ps == null) {
18458                Slog.w(TAG, "Failed to find settings for " + packageName);
18459                return false;
18460            }
18461        }
18462
18463        final String[] packageNames = { packageName };
18464        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18465        final String[] codePaths = { ps.codePathString };
18466
18467        try {
18468            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18469                    ps.appId, ceDataInodes, codePaths, stats);
18470
18471            // For now, ignore code size of packages on system partition
18472            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18473                stats.codeSize = 0;
18474            }
18475
18476            // External clients expect these to be tracked separately
18477            stats.dataSize -= stats.cacheSize;
18478
18479        } catch (InstallerException e) {
18480            Slog.w(TAG, String.valueOf(e));
18481            return false;
18482        }
18483
18484        return true;
18485    }
18486
18487    private int getUidTargetSdkVersionLockedLPr(int uid) {
18488        Object obj = mSettings.getUserIdLPr(uid);
18489        if (obj instanceof SharedUserSetting) {
18490            final SharedUserSetting sus = (SharedUserSetting) obj;
18491            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18492            final Iterator<PackageSetting> it = sus.packages.iterator();
18493            while (it.hasNext()) {
18494                final PackageSetting ps = it.next();
18495                if (ps.pkg != null) {
18496                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18497                    if (v < vers) vers = v;
18498                }
18499            }
18500            return vers;
18501        } else if (obj instanceof PackageSetting) {
18502            final PackageSetting ps = (PackageSetting) obj;
18503            if (ps.pkg != null) {
18504                return ps.pkg.applicationInfo.targetSdkVersion;
18505            }
18506        }
18507        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18508    }
18509
18510    @Override
18511    public void addPreferredActivity(IntentFilter filter, int match,
18512            ComponentName[] set, ComponentName activity, int userId) {
18513        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18514                "Adding preferred");
18515    }
18516
18517    private void addPreferredActivityInternal(IntentFilter filter, int match,
18518            ComponentName[] set, ComponentName activity, boolean always, int userId,
18519            String opname) {
18520        // writer
18521        int callingUid = Binder.getCallingUid();
18522        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18523                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18524        if (filter.countActions() == 0) {
18525            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18526            return;
18527        }
18528        synchronized (mPackages) {
18529            if (mContext.checkCallingOrSelfPermission(
18530                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18531                    != PackageManager.PERMISSION_GRANTED) {
18532                if (getUidTargetSdkVersionLockedLPr(callingUid)
18533                        < Build.VERSION_CODES.FROYO) {
18534                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18535                            + callingUid);
18536                    return;
18537                }
18538                mContext.enforceCallingOrSelfPermission(
18539                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18540            }
18541
18542            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18543            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18544                    + userId + ":");
18545            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18546            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18547            scheduleWritePackageRestrictionsLocked(userId);
18548            postPreferredActivityChangedBroadcast(userId);
18549        }
18550    }
18551
18552    private void postPreferredActivityChangedBroadcast(int userId) {
18553        mHandler.post(() -> {
18554            final IActivityManager am = ActivityManager.getService();
18555            if (am == null) {
18556                return;
18557            }
18558
18559            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18560            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18561            try {
18562                am.broadcastIntent(null, intent, null, null,
18563                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18564                        null, false, false, userId);
18565            } catch (RemoteException e) {
18566            }
18567        });
18568    }
18569
18570    @Override
18571    public void replacePreferredActivity(IntentFilter filter, int match,
18572            ComponentName[] set, ComponentName activity, int userId) {
18573        if (filter.countActions() != 1) {
18574            throw new IllegalArgumentException(
18575                    "replacePreferredActivity expects filter to have only 1 action.");
18576        }
18577        if (filter.countDataAuthorities() != 0
18578                || filter.countDataPaths() != 0
18579                || filter.countDataSchemes() > 1
18580                || filter.countDataTypes() != 0) {
18581            throw new IllegalArgumentException(
18582                    "replacePreferredActivity expects filter to have no data authorities, " +
18583                    "paths, or types; and at most one scheme.");
18584        }
18585
18586        final int callingUid = Binder.getCallingUid();
18587        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18588                true /* requireFullPermission */, false /* checkShell */,
18589                "replace preferred activity");
18590        synchronized (mPackages) {
18591            if (mContext.checkCallingOrSelfPermission(
18592                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18593                    != PackageManager.PERMISSION_GRANTED) {
18594                if (getUidTargetSdkVersionLockedLPr(callingUid)
18595                        < Build.VERSION_CODES.FROYO) {
18596                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18597                            + Binder.getCallingUid());
18598                    return;
18599                }
18600                mContext.enforceCallingOrSelfPermission(
18601                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18602            }
18603
18604            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18605            if (pir != null) {
18606                // Get all of the existing entries that exactly match this filter.
18607                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18608                if (existing != null && existing.size() == 1) {
18609                    PreferredActivity cur = existing.get(0);
18610                    if (DEBUG_PREFERRED) {
18611                        Slog.i(TAG, "Checking replace of preferred:");
18612                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18613                        if (!cur.mPref.mAlways) {
18614                            Slog.i(TAG, "  -- CUR; not mAlways!");
18615                        } else {
18616                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18617                            Slog.i(TAG, "  -- CUR: mSet="
18618                                    + Arrays.toString(cur.mPref.mSetComponents));
18619                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18620                            Slog.i(TAG, "  -- NEW: mMatch="
18621                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18622                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18623                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18624                        }
18625                    }
18626                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18627                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18628                            && cur.mPref.sameSet(set)) {
18629                        // Setting the preferred activity to what it happens to be already
18630                        if (DEBUG_PREFERRED) {
18631                            Slog.i(TAG, "Replacing with same preferred activity "
18632                                    + cur.mPref.mShortComponent + " for user "
18633                                    + userId + ":");
18634                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18635                        }
18636                        return;
18637                    }
18638                }
18639
18640                if (existing != null) {
18641                    if (DEBUG_PREFERRED) {
18642                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18643                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18644                    }
18645                    for (int i = 0; i < existing.size(); i++) {
18646                        PreferredActivity pa = existing.get(i);
18647                        if (DEBUG_PREFERRED) {
18648                            Slog.i(TAG, "Removing existing preferred activity "
18649                                    + pa.mPref.mComponent + ":");
18650                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18651                        }
18652                        pir.removeFilter(pa);
18653                    }
18654                }
18655            }
18656            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18657                    "Replacing preferred");
18658        }
18659    }
18660
18661    @Override
18662    public void clearPackagePreferredActivities(String packageName) {
18663        final int callingUid = Binder.getCallingUid();
18664        if (getInstantAppPackageName(callingUid) != null) {
18665            return;
18666        }
18667        // writer
18668        synchronized (mPackages) {
18669            PackageParser.Package pkg = mPackages.get(packageName);
18670            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18671                if (mContext.checkCallingOrSelfPermission(
18672                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18673                        != PackageManager.PERMISSION_GRANTED) {
18674                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18675                            < Build.VERSION_CODES.FROYO) {
18676                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18677                                + callingUid);
18678                        return;
18679                    }
18680                    mContext.enforceCallingOrSelfPermission(
18681                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18682                }
18683            }
18684            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18685            if (ps != null
18686                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18687                return;
18688            }
18689            int user = UserHandle.getCallingUserId();
18690            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18691                scheduleWritePackageRestrictionsLocked(user);
18692            }
18693        }
18694    }
18695
18696    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18697    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18698        ArrayList<PreferredActivity> removed = null;
18699        boolean changed = false;
18700        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18701            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18702            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18703            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18704                continue;
18705            }
18706            Iterator<PreferredActivity> it = pir.filterIterator();
18707            while (it.hasNext()) {
18708                PreferredActivity pa = it.next();
18709                // Mark entry for removal only if it matches the package name
18710                // and the entry is of type "always".
18711                if (packageName == null ||
18712                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18713                                && pa.mPref.mAlways)) {
18714                    if (removed == null) {
18715                        removed = new ArrayList<PreferredActivity>();
18716                    }
18717                    removed.add(pa);
18718                }
18719            }
18720            if (removed != null) {
18721                for (int j=0; j<removed.size(); j++) {
18722                    PreferredActivity pa = removed.get(j);
18723                    pir.removeFilter(pa);
18724                }
18725                changed = true;
18726            }
18727        }
18728        if (changed) {
18729            postPreferredActivityChangedBroadcast(userId);
18730        }
18731        return changed;
18732    }
18733
18734    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18735    private void clearIntentFilterVerificationsLPw(int userId) {
18736        final int packageCount = mPackages.size();
18737        for (int i = 0; i < packageCount; i++) {
18738            PackageParser.Package pkg = mPackages.valueAt(i);
18739            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18740        }
18741    }
18742
18743    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18744    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18745        if (userId == UserHandle.USER_ALL) {
18746            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18747                    sUserManager.getUserIds())) {
18748                for (int oneUserId : sUserManager.getUserIds()) {
18749                    scheduleWritePackageRestrictionsLocked(oneUserId);
18750                }
18751            }
18752        } else {
18753            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18754                scheduleWritePackageRestrictionsLocked(userId);
18755            }
18756        }
18757    }
18758
18759    /** Clears state for all users, and touches intent filter verification policy */
18760    void clearDefaultBrowserIfNeeded(String packageName) {
18761        for (int oneUserId : sUserManager.getUserIds()) {
18762            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
18763        }
18764    }
18765
18766    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
18767        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
18768        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
18769            if (packageName.equals(defaultBrowserPackageName)) {
18770                setDefaultBrowserPackageName(null, userId);
18771            }
18772        }
18773    }
18774
18775    @Override
18776    public void resetApplicationPreferences(int userId) {
18777        mContext.enforceCallingOrSelfPermission(
18778                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18779        final long identity = Binder.clearCallingIdentity();
18780        // writer
18781        try {
18782            synchronized (mPackages) {
18783                clearPackagePreferredActivitiesLPw(null, userId);
18784                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18785                // TODO: We have to reset the default SMS and Phone. This requires
18786                // significant refactoring to keep all default apps in the package
18787                // manager (cleaner but more work) or have the services provide
18788                // callbacks to the package manager to request a default app reset.
18789                applyFactoryDefaultBrowserLPw(userId);
18790                clearIntentFilterVerificationsLPw(userId);
18791                primeDomainVerificationsLPw(userId);
18792                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18793                scheduleWritePackageRestrictionsLocked(userId);
18794            }
18795            resetNetworkPolicies(userId);
18796        } finally {
18797            Binder.restoreCallingIdentity(identity);
18798        }
18799    }
18800
18801    @Override
18802    public int getPreferredActivities(List<IntentFilter> outFilters,
18803            List<ComponentName> outActivities, String packageName) {
18804        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
18805            return 0;
18806        }
18807        int num = 0;
18808        final int userId = UserHandle.getCallingUserId();
18809        // reader
18810        synchronized (mPackages) {
18811            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18812            if (pir != null) {
18813                final Iterator<PreferredActivity> it = pir.filterIterator();
18814                while (it.hasNext()) {
18815                    final PreferredActivity pa = it.next();
18816                    if (packageName == null
18817                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18818                                    && pa.mPref.mAlways)) {
18819                        if (outFilters != null) {
18820                            outFilters.add(new IntentFilter(pa));
18821                        }
18822                        if (outActivities != null) {
18823                            outActivities.add(pa.mPref.mComponent);
18824                        }
18825                    }
18826                }
18827            }
18828        }
18829
18830        return num;
18831    }
18832
18833    @Override
18834    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18835            int userId) {
18836        int callingUid = Binder.getCallingUid();
18837        if (callingUid != Process.SYSTEM_UID) {
18838            throw new SecurityException(
18839                    "addPersistentPreferredActivity can only be run by the system");
18840        }
18841        if (filter.countActions() == 0) {
18842            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18843            return;
18844        }
18845        synchronized (mPackages) {
18846            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18847                    ":");
18848            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18849            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18850                    new PersistentPreferredActivity(filter, activity));
18851            scheduleWritePackageRestrictionsLocked(userId);
18852            postPreferredActivityChangedBroadcast(userId);
18853        }
18854    }
18855
18856    @Override
18857    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18858        int callingUid = Binder.getCallingUid();
18859        if (callingUid != Process.SYSTEM_UID) {
18860            throw new SecurityException(
18861                    "clearPackagePersistentPreferredActivities can only be run by the system");
18862        }
18863        ArrayList<PersistentPreferredActivity> removed = null;
18864        boolean changed = false;
18865        synchronized (mPackages) {
18866            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18867                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18868                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18869                        .valueAt(i);
18870                if (userId != thisUserId) {
18871                    continue;
18872                }
18873                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18874                while (it.hasNext()) {
18875                    PersistentPreferredActivity ppa = it.next();
18876                    // Mark entry for removal only if it matches the package name.
18877                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18878                        if (removed == null) {
18879                            removed = new ArrayList<PersistentPreferredActivity>();
18880                        }
18881                        removed.add(ppa);
18882                    }
18883                }
18884                if (removed != null) {
18885                    for (int j=0; j<removed.size(); j++) {
18886                        PersistentPreferredActivity ppa = removed.get(j);
18887                        ppir.removeFilter(ppa);
18888                    }
18889                    changed = true;
18890                }
18891            }
18892
18893            if (changed) {
18894                scheduleWritePackageRestrictionsLocked(userId);
18895                postPreferredActivityChangedBroadcast(userId);
18896            }
18897        }
18898    }
18899
18900    /**
18901     * Common machinery for picking apart a restored XML blob and passing
18902     * it to a caller-supplied functor to be applied to the running system.
18903     */
18904    private void restoreFromXml(XmlPullParser parser, int userId,
18905            String expectedStartTag, BlobXmlRestorer functor)
18906            throws IOException, XmlPullParserException {
18907        int type;
18908        while ((type = parser.next()) != XmlPullParser.START_TAG
18909                && type != XmlPullParser.END_DOCUMENT) {
18910        }
18911        if (type != XmlPullParser.START_TAG) {
18912            // oops didn't find a start tag?!
18913            if (DEBUG_BACKUP) {
18914                Slog.e(TAG, "Didn't find start tag during restore");
18915            }
18916            return;
18917        }
18918Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18919        // this is supposed to be TAG_PREFERRED_BACKUP
18920        if (!expectedStartTag.equals(parser.getName())) {
18921            if (DEBUG_BACKUP) {
18922                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18923            }
18924            return;
18925        }
18926
18927        // skip interfering stuff, then we're aligned with the backing implementation
18928        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18929Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18930        functor.apply(parser, userId);
18931    }
18932
18933    private interface BlobXmlRestorer {
18934        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18935    }
18936
18937    /**
18938     * Non-Binder method, support for the backup/restore mechanism: write the
18939     * full set of preferred activities in its canonical XML format.  Returns the
18940     * XML output as a byte array, or null if there is none.
18941     */
18942    @Override
18943    public byte[] getPreferredActivityBackup(int userId) {
18944        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18945            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18946        }
18947
18948        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18949        try {
18950            final XmlSerializer serializer = new FastXmlSerializer();
18951            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18952            serializer.startDocument(null, true);
18953            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18954
18955            synchronized (mPackages) {
18956                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18957            }
18958
18959            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18960            serializer.endDocument();
18961            serializer.flush();
18962        } catch (Exception e) {
18963            if (DEBUG_BACKUP) {
18964                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18965            }
18966            return null;
18967        }
18968
18969        return dataStream.toByteArray();
18970    }
18971
18972    @Override
18973    public void restorePreferredActivities(byte[] backup, int userId) {
18974        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18975            throw new SecurityException("Only the system may call restorePreferredActivities()");
18976        }
18977
18978        try {
18979            final XmlPullParser parser = Xml.newPullParser();
18980            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18981            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18982                    new BlobXmlRestorer() {
18983                        @Override
18984                        public void apply(XmlPullParser parser, int userId)
18985                                throws XmlPullParserException, IOException {
18986                            synchronized (mPackages) {
18987                                mSettings.readPreferredActivitiesLPw(parser, userId);
18988                            }
18989                        }
18990                    } );
18991        } catch (Exception e) {
18992            if (DEBUG_BACKUP) {
18993                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18994            }
18995        }
18996    }
18997
18998    /**
18999     * Non-Binder method, support for the backup/restore mechanism: write the
19000     * default browser (etc) settings in its canonical XML format.  Returns the default
19001     * browser XML representation as a byte array, or null if there is none.
19002     */
19003    @Override
19004    public byte[] getDefaultAppsBackup(int userId) {
19005        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19006            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19007        }
19008
19009        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19010        try {
19011            final XmlSerializer serializer = new FastXmlSerializer();
19012            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19013            serializer.startDocument(null, true);
19014            serializer.startTag(null, TAG_DEFAULT_APPS);
19015
19016            synchronized (mPackages) {
19017                mSettings.writeDefaultAppsLPr(serializer, userId);
19018            }
19019
19020            serializer.endTag(null, TAG_DEFAULT_APPS);
19021            serializer.endDocument();
19022            serializer.flush();
19023        } catch (Exception e) {
19024            if (DEBUG_BACKUP) {
19025                Slog.e(TAG, "Unable to write default apps for backup", e);
19026            }
19027            return null;
19028        }
19029
19030        return dataStream.toByteArray();
19031    }
19032
19033    @Override
19034    public void restoreDefaultApps(byte[] backup, int userId) {
19035        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19036            throw new SecurityException("Only the system may call restoreDefaultApps()");
19037        }
19038
19039        try {
19040            final XmlPullParser parser = Xml.newPullParser();
19041            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19042            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19043                    new BlobXmlRestorer() {
19044                        @Override
19045                        public void apply(XmlPullParser parser, int userId)
19046                                throws XmlPullParserException, IOException {
19047                            synchronized (mPackages) {
19048                                mSettings.readDefaultAppsLPw(parser, userId);
19049                            }
19050                        }
19051                    } );
19052        } catch (Exception e) {
19053            if (DEBUG_BACKUP) {
19054                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19055            }
19056        }
19057    }
19058
19059    @Override
19060    public byte[] getIntentFilterVerificationBackup(int userId) {
19061        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19062            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19063        }
19064
19065        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19066        try {
19067            final XmlSerializer serializer = new FastXmlSerializer();
19068            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19069            serializer.startDocument(null, true);
19070            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19071
19072            synchronized (mPackages) {
19073                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19074            }
19075
19076            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19077            serializer.endDocument();
19078            serializer.flush();
19079        } catch (Exception e) {
19080            if (DEBUG_BACKUP) {
19081                Slog.e(TAG, "Unable to write default apps for backup", e);
19082            }
19083            return null;
19084        }
19085
19086        return dataStream.toByteArray();
19087    }
19088
19089    @Override
19090    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19091        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19092            throw new SecurityException("Only the system may call restorePreferredActivities()");
19093        }
19094
19095        try {
19096            final XmlPullParser parser = Xml.newPullParser();
19097            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19098            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19099                    new BlobXmlRestorer() {
19100                        @Override
19101                        public void apply(XmlPullParser parser, int userId)
19102                                throws XmlPullParserException, IOException {
19103                            synchronized (mPackages) {
19104                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19105                                mSettings.writeLPr();
19106                            }
19107                        }
19108                    } );
19109        } catch (Exception e) {
19110            if (DEBUG_BACKUP) {
19111                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19112            }
19113        }
19114    }
19115
19116    @Override
19117    public byte[] getPermissionGrantBackup(int userId) {
19118        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19119            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19120        }
19121
19122        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19123        try {
19124            final XmlSerializer serializer = new FastXmlSerializer();
19125            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19126            serializer.startDocument(null, true);
19127            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19128
19129            synchronized (mPackages) {
19130                serializeRuntimePermissionGrantsLPr(serializer, userId);
19131            }
19132
19133            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19134            serializer.endDocument();
19135            serializer.flush();
19136        } catch (Exception e) {
19137            if (DEBUG_BACKUP) {
19138                Slog.e(TAG, "Unable to write default apps for backup", e);
19139            }
19140            return null;
19141        }
19142
19143        return dataStream.toByteArray();
19144    }
19145
19146    @Override
19147    public void restorePermissionGrants(byte[] backup, int userId) {
19148        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19149            throw new SecurityException("Only the system may call restorePermissionGrants()");
19150        }
19151
19152        try {
19153            final XmlPullParser parser = Xml.newPullParser();
19154            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19155            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19156                    new BlobXmlRestorer() {
19157                        @Override
19158                        public void apply(XmlPullParser parser, int userId)
19159                                throws XmlPullParserException, IOException {
19160                            synchronized (mPackages) {
19161                                processRestoredPermissionGrantsLPr(parser, userId);
19162                            }
19163                        }
19164                    } );
19165        } catch (Exception e) {
19166            if (DEBUG_BACKUP) {
19167                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19168            }
19169        }
19170    }
19171
19172    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19173            throws IOException {
19174        serializer.startTag(null, TAG_ALL_GRANTS);
19175
19176        final int N = mSettings.mPackages.size();
19177        for (int i = 0; i < N; i++) {
19178            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19179            boolean pkgGrantsKnown = false;
19180
19181            PermissionsState packagePerms = ps.getPermissionsState();
19182
19183            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19184                final int grantFlags = state.getFlags();
19185                // only look at grants that are not system/policy fixed
19186                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19187                    final boolean isGranted = state.isGranted();
19188                    // And only back up the user-twiddled state bits
19189                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19190                        final String packageName = mSettings.mPackages.keyAt(i);
19191                        if (!pkgGrantsKnown) {
19192                            serializer.startTag(null, TAG_GRANT);
19193                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19194                            pkgGrantsKnown = true;
19195                        }
19196
19197                        final boolean userSet =
19198                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19199                        final boolean userFixed =
19200                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19201                        final boolean revoke =
19202                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19203
19204                        serializer.startTag(null, TAG_PERMISSION);
19205                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19206                        if (isGranted) {
19207                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19208                        }
19209                        if (userSet) {
19210                            serializer.attribute(null, ATTR_USER_SET, "true");
19211                        }
19212                        if (userFixed) {
19213                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19214                        }
19215                        if (revoke) {
19216                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19217                        }
19218                        serializer.endTag(null, TAG_PERMISSION);
19219                    }
19220                }
19221            }
19222
19223            if (pkgGrantsKnown) {
19224                serializer.endTag(null, TAG_GRANT);
19225            }
19226        }
19227
19228        serializer.endTag(null, TAG_ALL_GRANTS);
19229    }
19230
19231    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19232            throws XmlPullParserException, IOException {
19233        String pkgName = null;
19234        int outerDepth = parser.getDepth();
19235        int type;
19236        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19237                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19238            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19239                continue;
19240            }
19241
19242            final String tagName = parser.getName();
19243            if (tagName.equals(TAG_GRANT)) {
19244                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19245                if (DEBUG_BACKUP) {
19246                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19247                }
19248            } else if (tagName.equals(TAG_PERMISSION)) {
19249
19250                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19251                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19252
19253                int newFlagSet = 0;
19254                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19255                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19256                }
19257                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19258                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19259                }
19260                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19261                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19262                }
19263                if (DEBUG_BACKUP) {
19264                    Slog.v(TAG, "  + Restoring grant:"
19265                            + " pkg=" + pkgName
19266                            + " perm=" + permName
19267                            + " granted=" + isGranted
19268                            + " bits=0x" + Integer.toHexString(newFlagSet));
19269                }
19270                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19271                if (ps != null) {
19272                    // Already installed so we apply the grant immediately
19273                    if (DEBUG_BACKUP) {
19274                        Slog.v(TAG, "        + already installed; applying");
19275                    }
19276                    PermissionsState perms = ps.getPermissionsState();
19277                    BasePermission bp =
19278                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19279                    if (bp != null) {
19280                        if (isGranted) {
19281                            perms.grantRuntimePermission(bp, userId);
19282                        }
19283                        if (newFlagSet != 0) {
19284                            perms.updatePermissionFlags(
19285                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19286                        }
19287                    }
19288                } else {
19289                    // Need to wait for post-restore install to apply the grant
19290                    if (DEBUG_BACKUP) {
19291                        Slog.v(TAG, "        - not yet installed; saving for later");
19292                    }
19293                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19294                            isGranted, newFlagSet, userId);
19295                }
19296            } else {
19297                PackageManagerService.reportSettingsProblem(Log.WARN,
19298                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19299                XmlUtils.skipCurrentTag(parser);
19300            }
19301        }
19302
19303        scheduleWriteSettingsLocked();
19304        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19305    }
19306
19307    @Override
19308    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19309            int sourceUserId, int targetUserId, int flags) {
19310        mContext.enforceCallingOrSelfPermission(
19311                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19312        int callingUid = Binder.getCallingUid();
19313        enforceOwnerRights(ownerPackage, callingUid);
19314        PackageManagerServiceUtils.enforceShellRestriction(
19315                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19316        if (intentFilter.countActions() == 0) {
19317            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19318            return;
19319        }
19320        synchronized (mPackages) {
19321            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19322                    ownerPackage, targetUserId, flags);
19323            CrossProfileIntentResolver resolver =
19324                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19325            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19326            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19327            if (existing != null) {
19328                int size = existing.size();
19329                for (int i = 0; i < size; i++) {
19330                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19331                        return;
19332                    }
19333                }
19334            }
19335            resolver.addFilter(newFilter);
19336            scheduleWritePackageRestrictionsLocked(sourceUserId);
19337        }
19338    }
19339
19340    @Override
19341    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19342        mContext.enforceCallingOrSelfPermission(
19343                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19344        final int callingUid = Binder.getCallingUid();
19345        enforceOwnerRights(ownerPackage, callingUid);
19346        PackageManagerServiceUtils.enforceShellRestriction(
19347                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19348        synchronized (mPackages) {
19349            CrossProfileIntentResolver resolver =
19350                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19351            ArraySet<CrossProfileIntentFilter> set =
19352                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19353            for (CrossProfileIntentFilter filter : set) {
19354                if (filter.getOwnerPackage().equals(ownerPackage)) {
19355                    resolver.removeFilter(filter);
19356                }
19357            }
19358            scheduleWritePackageRestrictionsLocked(sourceUserId);
19359        }
19360    }
19361
19362    // Enforcing that callingUid is owning pkg on userId
19363    private void enforceOwnerRights(String pkg, int callingUid) {
19364        // The system owns everything.
19365        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19366            return;
19367        }
19368        final int callingUserId = UserHandle.getUserId(callingUid);
19369        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19370        if (pi == null) {
19371            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19372                    + callingUserId);
19373        }
19374        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19375            throw new SecurityException("Calling uid " + callingUid
19376                    + " does not own package " + pkg);
19377        }
19378    }
19379
19380    @Override
19381    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19382        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19383            return null;
19384        }
19385        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19386    }
19387
19388    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19389        UserManagerService ums = UserManagerService.getInstance();
19390        if (ums != null) {
19391            final UserInfo parent = ums.getProfileParent(userId);
19392            final int launcherUid = (parent != null) ? parent.id : userId;
19393            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19394            if (launcherComponent != null) {
19395                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19396                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19397                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19398                        .setPackage(launcherComponent.getPackageName());
19399                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19400            }
19401        }
19402    }
19403
19404    /**
19405     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19406     * then reports the most likely home activity or null if there are more than one.
19407     */
19408    private ComponentName getDefaultHomeActivity(int userId) {
19409        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19410        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19411        if (cn != null) {
19412            return cn;
19413        }
19414
19415        // Find the launcher with the highest priority and return that component if there are no
19416        // other home activity with the same priority.
19417        int lastPriority = Integer.MIN_VALUE;
19418        ComponentName lastComponent = null;
19419        final int size = allHomeCandidates.size();
19420        for (int i = 0; i < size; i++) {
19421            final ResolveInfo ri = allHomeCandidates.get(i);
19422            if (ri.priority > lastPriority) {
19423                lastComponent = ri.activityInfo.getComponentName();
19424                lastPriority = ri.priority;
19425            } else if (ri.priority == lastPriority) {
19426                // Two components found with same priority.
19427                lastComponent = null;
19428            }
19429        }
19430        return lastComponent;
19431    }
19432
19433    private Intent getHomeIntent() {
19434        Intent intent = new Intent(Intent.ACTION_MAIN);
19435        intent.addCategory(Intent.CATEGORY_HOME);
19436        intent.addCategory(Intent.CATEGORY_DEFAULT);
19437        return intent;
19438    }
19439
19440    private IntentFilter getHomeFilter() {
19441        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19442        filter.addCategory(Intent.CATEGORY_HOME);
19443        filter.addCategory(Intent.CATEGORY_DEFAULT);
19444        return filter;
19445    }
19446
19447    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19448            int userId) {
19449        Intent intent  = getHomeIntent();
19450        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19451                PackageManager.GET_META_DATA, userId);
19452        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19453                true, false, false, userId);
19454
19455        allHomeCandidates.clear();
19456        if (list != null) {
19457            for (ResolveInfo ri : list) {
19458                allHomeCandidates.add(ri);
19459            }
19460        }
19461        return (preferred == null || preferred.activityInfo == null)
19462                ? null
19463                : new ComponentName(preferred.activityInfo.packageName,
19464                        preferred.activityInfo.name);
19465    }
19466
19467    @Override
19468    public void setHomeActivity(ComponentName comp, int userId) {
19469        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19470            return;
19471        }
19472        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19473        getHomeActivitiesAsUser(homeActivities, userId);
19474
19475        boolean found = false;
19476
19477        final int size = homeActivities.size();
19478        final ComponentName[] set = new ComponentName[size];
19479        for (int i = 0; i < size; i++) {
19480            final ResolveInfo candidate = homeActivities.get(i);
19481            final ActivityInfo info = candidate.activityInfo;
19482            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19483            set[i] = activityName;
19484            if (!found && activityName.equals(comp)) {
19485                found = true;
19486            }
19487        }
19488        if (!found) {
19489            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19490                    + userId);
19491        }
19492        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19493                set, comp, userId);
19494    }
19495
19496    private @Nullable String getSetupWizardPackageName() {
19497        final Intent intent = new Intent(Intent.ACTION_MAIN);
19498        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19499
19500        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19501                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19502                        | MATCH_DISABLED_COMPONENTS,
19503                UserHandle.myUserId());
19504        if (matches.size() == 1) {
19505            return matches.get(0).getComponentInfo().packageName;
19506        } else {
19507            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19508                    + ": matches=" + matches);
19509            return null;
19510        }
19511    }
19512
19513    private @Nullable String getStorageManagerPackageName() {
19514        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19515
19516        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19517                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19518                        | MATCH_DISABLED_COMPONENTS,
19519                UserHandle.myUserId());
19520        if (matches.size() == 1) {
19521            return matches.get(0).getComponentInfo().packageName;
19522        } else {
19523            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19524                    + matches.size() + ": matches=" + matches);
19525            return null;
19526        }
19527    }
19528
19529    @Override
19530    public void setApplicationEnabledSetting(String appPackageName,
19531            int newState, int flags, int userId, String callingPackage) {
19532        if (!sUserManager.exists(userId)) return;
19533        if (callingPackage == null) {
19534            callingPackage = Integer.toString(Binder.getCallingUid());
19535        }
19536        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19537    }
19538
19539    @Override
19540    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19541        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19542        synchronized (mPackages) {
19543            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19544            if (pkgSetting != null) {
19545                pkgSetting.setUpdateAvailable(updateAvailable);
19546            }
19547        }
19548    }
19549
19550    @Override
19551    public void setComponentEnabledSetting(ComponentName componentName,
19552            int newState, int flags, int userId) {
19553        if (!sUserManager.exists(userId)) return;
19554        setEnabledSetting(componentName.getPackageName(),
19555                componentName.getClassName(), newState, flags, userId, null);
19556    }
19557
19558    private void setEnabledSetting(final String packageName, String className, int newState,
19559            final int flags, int userId, String callingPackage) {
19560        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19561              || newState == COMPONENT_ENABLED_STATE_ENABLED
19562              || newState == COMPONENT_ENABLED_STATE_DISABLED
19563              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19564              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19565            throw new IllegalArgumentException("Invalid new component state: "
19566                    + newState);
19567        }
19568        PackageSetting pkgSetting;
19569        final int callingUid = Binder.getCallingUid();
19570        final int permission;
19571        if (callingUid == Process.SYSTEM_UID) {
19572            permission = PackageManager.PERMISSION_GRANTED;
19573        } else {
19574            permission = mContext.checkCallingOrSelfPermission(
19575                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19576        }
19577        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19578                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19579        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19580        boolean sendNow = false;
19581        boolean isApp = (className == null);
19582        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19583        String componentName = isApp ? packageName : className;
19584        int packageUid = -1;
19585        ArrayList<String> components;
19586
19587        // reader
19588        synchronized (mPackages) {
19589            pkgSetting = mSettings.mPackages.get(packageName);
19590            if (pkgSetting == null) {
19591                if (!isCallerInstantApp) {
19592                    if (className == null) {
19593                        throw new IllegalArgumentException("Unknown package: " + packageName);
19594                    }
19595                    throw new IllegalArgumentException(
19596                            "Unknown component: " + packageName + "/" + className);
19597                } else {
19598                    // throw SecurityException to prevent leaking package information
19599                    throw new SecurityException(
19600                            "Attempt to change component state; "
19601                            + "pid=" + Binder.getCallingPid()
19602                            + ", uid=" + callingUid
19603                            + (className == null
19604                                    ? ", package=" + packageName
19605                                    : ", component=" + packageName + "/" + className));
19606                }
19607            }
19608        }
19609
19610        // Limit who can change which apps
19611        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19612            // Don't allow apps that don't have permission to modify other apps
19613            if (!allowedByPermission
19614                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19615                throw new SecurityException(
19616                        "Attempt to change component state; "
19617                        + "pid=" + Binder.getCallingPid()
19618                        + ", uid=" + callingUid
19619                        + (className == null
19620                                ? ", package=" + packageName
19621                                : ", component=" + packageName + "/" + className));
19622            }
19623            // Don't allow changing protected packages.
19624            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19625                throw new SecurityException("Cannot disable a protected package: " + packageName);
19626            }
19627        }
19628
19629        synchronized (mPackages) {
19630            if (callingUid == Process.SHELL_UID
19631                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19632                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19633                // unless it is a test package.
19634                int oldState = pkgSetting.getEnabled(userId);
19635                if (className == null
19636                        &&
19637                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19638                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19639                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19640                        &&
19641                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19642                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19643                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19644                    // ok
19645                } else {
19646                    throw new SecurityException(
19647                            "Shell cannot change component state for " + packageName + "/"
19648                                    + className + " to " + newState);
19649                }
19650            }
19651        }
19652        if (className == null) {
19653            // We're dealing with an application/package level state change
19654            synchronized (mPackages) {
19655                if (pkgSetting.getEnabled(userId) == newState) {
19656                    // Nothing to do
19657                    return;
19658                }
19659            }
19660            // If we're enabling a system stub, there's a little more work to do.
19661            // Prior to enabling the package, we need to decompress the APK(s) to the
19662            // data partition and then replace the version on the system partition.
19663            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19664            final boolean isSystemStub = deletedPkg.isStub
19665                    && deletedPkg.isSystem();
19666            if (isSystemStub
19667                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19668                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19669                final File codePath = decompressPackage(deletedPkg);
19670                if (codePath == null) {
19671                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19672                    return;
19673                }
19674                // TODO remove direct parsing of the package object during internal cleanup
19675                // of scan package
19676                // We need to call parse directly here for no other reason than we need
19677                // the new package in order to disable the old one [we use the information
19678                // for some internal optimization to optionally create a new package setting
19679                // object on replace]. However, we can't get the package from the scan
19680                // because the scan modifies live structures and we need to remove the
19681                // old [system] package from the system before a scan can be attempted.
19682                // Once scan is indempotent we can remove this parse and use the package
19683                // object we scanned, prior to adding it to package settings.
19684                final PackageParser pp = new PackageParser();
19685                pp.setSeparateProcesses(mSeparateProcesses);
19686                pp.setDisplayMetrics(mMetrics);
19687                pp.setCallback(mPackageParserCallback);
19688                final PackageParser.Package tmpPkg;
19689                try {
19690                    final @ParseFlags int parseFlags = mDefParseFlags
19691                            | PackageParser.PARSE_MUST_BE_APK
19692                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19693                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19694                } catch (PackageParserException e) {
19695                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19696                    return;
19697                }
19698                synchronized (mInstallLock) {
19699                    // Disable the stub and remove any package entries
19700                    removePackageLI(deletedPkg, true);
19701                    synchronized (mPackages) {
19702                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19703                    }
19704                    final PackageParser.Package pkg;
19705                    try (PackageFreezer freezer =
19706                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19707                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
19708                                | PackageParser.PARSE_ENFORCE_CODE;
19709                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
19710                                0 /*currentTime*/, null /*user*/);
19711                        prepareAppDataAfterInstallLIF(pkg);
19712                        synchronized (mPackages) {
19713                            try {
19714                                updateSharedLibrariesLPr(pkg, null);
19715                            } catch (PackageManagerException e) {
19716                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
19717                            }
19718                            mPermissionManager.updatePermissions(
19719                                    pkg.packageName, pkg, true, mPackages.values(),
19720                                    mPermissionCallback);
19721                            mSettings.writeLPr();
19722                        }
19723                    } catch (PackageManagerException e) {
19724                        // Whoops! Something went wrong; try to roll back to the stub
19725                        Slog.w(TAG, "Failed to install compressed system package:"
19726                                + pkgSetting.name, e);
19727                        // Remove the failed install
19728                        removeCodePathLI(codePath);
19729
19730                        // Install the system package
19731                        try (PackageFreezer freezer =
19732                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19733                            synchronized (mPackages) {
19734                                // NOTE: The system package always needs to be enabled; even
19735                                // if it's for a compressed stub. If we don't, installing the
19736                                // system package fails during scan [scanning checks the disabled
19737                                // packages]. We will reverse this later, after we've "installed"
19738                                // the stub.
19739                                // This leaves us in a fragile state; the stub should never be
19740                                // enabled, so, cross your fingers and hope nothing goes wrong
19741                                // until we can disable the package later.
19742                                enableSystemPackageLPw(deletedPkg);
19743                            }
19744                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
19745                                    false /*isPrivileged*/, null /*allUserHandles*/,
19746                                    null /*origUserHandles*/, null /*origPermissionsState*/,
19747                                    true /*writeSettings*/);
19748                        } catch (PackageManagerException pme) {
19749                            Slog.w(TAG, "Failed to restore system package:"
19750                                    + deletedPkg.packageName, pme);
19751                        } finally {
19752                            synchronized (mPackages) {
19753                                mSettings.disableSystemPackageLPw(
19754                                        deletedPkg.packageName, true /*replaced*/);
19755                                mSettings.writeLPr();
19756                            }
19757                        }
19758                        return;
19759                    }
19760                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
19761                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19762                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19763                    mDexManager.notifyPackageUpdated(pkg.packageName,
19764                            pkg.baseCodePath, pkg.splitCodePaths);
19765                }
19766            }
19767            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19768                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19769                // Don't care about who enables an app.
19770                callingPackage = null;
19771            }
19772            synchronized (mPackages) {
19773                pkgSetting.setEnabled(newState, userId, callingPackage);
19774            }
19775        } else {
19776            synchronized (mPackages) {
19777                // We're dealing with a component level state change
19778                // First, verify that this is a valid class name.
19779                PackageParser.Package pkg = pkgSetting.pkg;
19780                if (pkg == null || !pkg.hasComponentClassName(className)) {
19781                    if (pkg != null &&
19782                            pkg.applicationInfo.targetSdkVersion >=
19783                                    Build.VERSION_CODES.JELLY_BEAN) {
19784                        throw new IllegalArgumentException("Component class " + className
19785                                + " does not exist in " + packageName);
19786                    } else {
19787                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19788                                + className + " does not exist in " + packageName);
19789                    }
19790                }
19791                switch (newState) {
19792                    case COMPONENT_ENABLED_STATE_ENABLED:
19793                        if (!pkgSetting.enableComponentLPw(className, userId)) {
19794                            return;
19795                        }
19796                        break;
19797                    case COMPONENT_ENABLED_STATE_DISABLED:
19798                        if (!pkgSetting.disableComponentLPw(className, userId)) {
19799                            return;
19800                        }
19801                        break;
19802                    case COMPONENT_ENABLED_STATE_DEFAULT:
19803                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
19804                            return;
19805                        }
19806                        break;
19807                    default:
19808                        Slog.e(TAG, "Invalid new component state: " + newState);
19809                        return;
19810                }
19811            }
19812        }
19813        synchronized (mPackages) {
19814            scheduleWritePackageRestrictionsLocked(userId);
19815            updateSequenceNumberLP(pkgSetting, new int[] { userId });
19816            final long callingId = Binder.clearCallingIdentity();
19817            try {
19818                updateInstantAppInstallerLocked(packageName);
19819            } finally {
19820                Binder.restoreCallingIdentity(callingId);
19821            }
19822            components = mPendingBroadcasts.get(userId, packageName);
19823            final boolean newPackage = components == null;
19824            if (newPackage) {
19825                components = new ArrayList<String>();
19826            }
19827            if (!components.contains(componentName)) {
19828                components.add(componentName);
19829            }
19830            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19831                sendNow = true;
19832                // Purge entry from pending broadcast list if another one exists already
19833                // since we are sending one right away.
19834                mPendingBroadcasts.remove(userId, packageName);
19835            } else {
19836                if (newPackage) {
19837                    mPendingBroadcasts.put(userId, packageName, components);
19838                }
19839                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19840                    // Schedule a message
19841                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19842                }
19843            }
19844        }
19845
19846        long callingId = Binder.clearCallingIdentity();
19847        try {
19848            if (sendNow) {
19849                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19850                sendPackageChangedBroadcast(packageName,
19851                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19852            }
19853        } finally {
19854            Binder.restoreCallingIdentity(callingId);
19855        }
19856    }
19857
19858    @Override
19859    public void flushPackageRestrictionsAsUser(int userId) {
19860        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19861            return;
19862        }
19863        if (!sUserManager.exists(userId)) {
19864            return;
19865        }
19866        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19867                false /* checkShell */, "flushPackageRestrictions");
19868        synchronized (mPackages) {
19869            mSettings.writePackageRestrictionsLPr(userId);
19870            mDirtyUsers.remove(userId);
19871            if (mDirtyUsers.isEmpty()) {
19872                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19873            }
19874        }
19875    }
19876
19877    private void sendPackageChangedBroadcast(String packageName,
19878            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19879        if (DEBUG_INSTALL)
19880            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19881                    + componentNames);
19882        Bundle extras = new Bundle(4);
19883        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19884        String nameList[] = new String[componentNames.size()];
19885        componentNames.toArray(nameList);
19886        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19887        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19888        extras.putInt(Intent.EXTRA_UID, packageUid);
19889        // If this is not reporting a change of the overall package, then only send it
19890        // to registered receivers.  We don't want to launch a swath of apps for every
19891        // little component state change.
19892        final int flags = !componentNames.contains(packageName)
19893                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19894        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19895                new int[] {UserHandle.getUserId(packageUid)});
19896    }
19897
19898    @Override
19899    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19900        if (!sUserManager.exists(userId)) return;
19901        final int callingUid = Binder.getCallingUid();
19902        if (getInstantAppPackageName(callingUid) != null) {
19903            return;
19904        }
19905        final int permission = mContext.checkCallingOrSelfPermission(
19906                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19907        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19908        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19909                true /* requireFullPermission */, true /* checkShell */, "stop package");
19910        // writer
19911        synchronized (mPackages) {
19912            final PackageSetting ps = mSettings.mPackages.get(packageName);
19913            if (!filterAppAccessLPr(ps, callingUid, userId)
19914                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19915                            allowedByPermission, callingUid, userId)) {
19916                scheduleWritePackageRestrictionsLocked(userId);
19917            }
19918        }
19919    }
19920
19921    @Override
19922    public String getInstallerPackageName(String packageName) {
19923        final int callingUid = Binder.getCallingUid();
19924        if (getInstantAppPackageName(callingUid) != null) {
19925            return null;
19926        }
19927        // reader
19928        synchronized (mPackages) {
19929            final PackageSetting ps = mSettings.mPackages.get(packageName);
19930            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19931                return null;
19932            }
19933            return mSettings.getInstallerPackageNameLPr(packageName);
19934        }
19935    }
19936
19937    public boolean isOrphaned(String packageName) {
19938        // reader
19939        synchronized (mPackages) {
19940            return mSettings.isOrphaned(packageName);
19941        }
19942    }
19943
19944    @Override
19945    public int getApplicationEnabledSetting(String packageName, int userId) {
19946        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19947        int callingUid = Binder.getCallingUid();
19948        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19949                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19950        // reader
19951        synchronized (mPackages) {
19952            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
19953                return COMPONENT_ENABLED_STATE_DISABLED;
19954            }
19955            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19956        }
19957    }
19958
19959    @Override
19960    public int getComponentEnabledSetting(ComponentName component, int userId) {
19961        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19962        int callingUid = Binder.getCallingUid();
19963        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19964                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
19965        synchronized (mPackages) {
19966            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
19967                    component, TYPE_UNKNOWN, userId)) {
19968                return COMPONENT_ENABLED_STATE_DISABLED;
19969            }
19970            return mSettings.getComponentEnabledSettingLPr(component, userId);
19971        }
19972    }
19973
19974    @Override
19975    public void enterSafeMode() {
19976        enforceSystemOrRoot("Only the system can request entering safe mode");
19977
19978        if (!mSystemReady) {
19979            mSafeMode = true;
19980        }
19981    }
19982
19983    @Override
19984    public void systemReady() {
19985        enforceSystemOrRoot("Only the system can claim the system is ready");
19986
19987        mSystemReady = true;
19988        final ContentResolver resolver = mContext.getContentResolver();
19989        ContentObserver co = new ContentObserver(mHandler) {
19990            @Override
19991            public void onChange(boolean selfChange) {
19992                mEphemeralAppsDisabled =
19993                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
19994                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
19995            }
19996        };
19997        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19998                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
19999                false, co, UserHandle.USER_SYSTEM);
20000        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20001                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20002        co.onChange(true);
20003
20004        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20005        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20006        // it is done.
20007        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20008            @Override
20009            public void onChange(boolean selfChange) {
20010                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20011                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20012                        oobEnabled == 1 ? "true" : "false");
20013            }
20014        };
20015        mContext.getContentResolver().registerContentObserver(
20016                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20017                UserHandle.USER_SYSTEM);
20018        // At boot, restore the value from the setting, which persists across reboot.
20019        privAppOobObserver.onChange(true);
20020
20021        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20022        // disabled after already being started.
20023        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20024                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20025
20026        // Read the compatibilty setting when the system is ready.
20027        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20028                mContext.getContentResolver(),
20029                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20030        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20031        if (DEBUG_SETTINGS) {
20032            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20033        }
20034
20035        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20036
20037        synchronized (mPackages) {
20038            // Verify that all of the preferred activity components actually
20039            // exist.  It is possible for applications to be updated and at
20040            // that point remove a previously declared activity component that
20041            // had been set as a preferred activity.  We try to clean this up
20042            // the next time we encounter that preferred activity, but it is
20043            // possible for the user flow to never be able to return to that
20044            // situation so here we do a sanity check to make sure we haven't
20045            // left any junk around.
20046            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20047            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20048                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20049                removed.clear();
20050                for (PreferredActivity pa : pir.filterSet()) {
20051                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20052                        removed.add(pa);
20053                    }
20054                }
20055                if (removed.size() > 0) {
20056                    for (int r=0; r<removed.size(); r++) {
20057                        PreferredActivity pa = removed.get(r);
20058                        Slog.w(TAG, "Removing dangling preferred activity: "
20059                                + pa.mPref.mComponent);
20060                        pir.removeFilter(pa);
20061                    }
20062                    mSettings.writePackageRestrictionsLPr(
20063                            mSettings.mPreferredActivities.keyAt(i));
20064                }
20065            }
20066
20067            for (int userId : UserManagerService.getInstance().getUserIds()) {
20068                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20069                    grantPermissionsUserIds = ArrayUtils.appendInt(
20070                            grantPermissionsUserIds, userId);
20071                }
20072            }
20073        }
20074        sUserManager.systemReady();
20075
20076        // If we upgraded grant all default permissions before kicking off.
20077        for (int userId : grantPermissionsUserIds) {
20078            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20079        }
20080
20081        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20082            // If we did not grant default permissions, we preload from this the
20083            // default permission exceptions lazily to ensure we don't hit the
20084            // disk on a new user creation.
20085            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20086        }
20087
20088        // Now that we've scanned all packages, and granted any default
20089        // permissions, ensure permissions are updated. Beware of dragons if you
20090        // try optimizing this.
20091        synchronized (mPackages) {
20092            mPermissionManager.updateAllPermissions(
20093                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20094                    mPermissionCallback);
20095        }
20096
20097        // Kick off any messages waiting for system ready
20098        if (mPostSystemReadyMessages != null) {
20099            for (Message msg : mPostSystemReadyMessages) {
20100                msg.sendToTarget();
20101            }
20102            mPostSystemReadyMessages = null;
20103        }
20104
20105        // Watch for external volumes that come and go over time
20106        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20107        storage.registerListener(mStorageListener);
20108
20109        mInstallerService.systemReady();
20110        mPackageDexOptimizer.systemReady();
20111
20112        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20113                StorageManagerInternal.class);
20114        StorageManagerInternal.addExternalStoragePolicy(
20115                new StorageManagerInternal.ExternalStorageMountPolicy() {
20116            @Override
20117            public int getMountMode(int uid, String packageName) {
20118                if (Process.isIsolated(uid)) {
20119                    return Zygote.MOUNT_EXTERNAL_NONE;
20120                }
20121                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20122                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20123                }
20124                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20125                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20126                }
20127                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20128                    return Zygote.MOUNT_EXTERNAL_READ;
20129                }
20130                return Zygote.MOUNT_EXTERNAL_WRITE;
20131            }
20132
20133            @Override
20134            public boolean hasExternalStorage(int uid, String packageName) {
20135                return true;
20136            }
20137        });
20138
20139        // Now that we're mostly running, clean up stale users and apps
20140        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20141        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20142
20143        mPermissionManager.systemReady();
20144    }
20145
20146    public void waitForAppDataPrepared() {
20147        if (mPrepareAppDataFuture == null) {
20148            return;
20149        }
20150        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20151        mPrepareAppDataFuture = null;
20152    }
20153
20154    @Override
20155    public boolean isSafeMode() {
20156        // allow instant applications
20157        return mSafeMode;
20158    }
20159
20160    @Override
20161    public boolean hasSystemUidErrors() {
20162        // allow instant applications
20163        return mHasSystemUidErrors;
20164    }
20165
20166    static String arrayToString(int[] array) {
20167        StringBuffer buf = new StringBuffer(128);
20168        buf.append('[');
20169        if (array != null) {
20170            for (int i=0; i<array.length; i++) {
20171                if (i > 0) buf.append(", ");
20172                buf.append(array[i]);
20173            }
20174        }
20175        buf.append(']');
20176        return buf.toString();
20177    }
20178
20179    @Override
20180    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20181            FileDescriptor err, String[] args, ShellCallback callback,
20182            ResultReceiver resultReceiver) {
20183        (new PackageManagerShellCommand(this)).exec(
20184                this, in, out, err, args, callback, resultReceiver);
20185    }
20186
20187    @Override
20188    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20189        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20190
20191        DumpState dumpState = new DumpState();
20192        boolean fullPreferred = false;
20193        boolean checkin = false;
20194
20195        String packageName = null;
20196        ArraySet<String> permissionNames = null;
20197
20198        int opti = 0;
20199        while (opti < args.length) {
20200            String opt = args[opti];
20201            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20202                break;
20203            }
20204            opti++;
20205
20206            if ("-a".equals(opt)) {
20207                // Right now we only know how to print all.
20208            } else if ("-h".equals(opt)) {
20209                pw.println("Package manager dump options:");
20210                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20211                pw.println("    --checkin: dump for a checkin");
20212                pw.println("    -f: print details of intent filters");
20213                pw.println("    -h: print this help");
20214                pw.println("  cmd may be one of:");
20215                pw.println("    l[ibraries]: list known shared libraries");
20216                pw.println("    f[eatures]: list device features");
20217                pw.println("    k[eysets]: print known keysets");
20218                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20219                pw.println("    perm[issions]: dump permissions");
20220                pw.println("    permission [name ...]: dump declaration and use of given permission");
20221                pw.println("    pref[erred]: print preferred package settings");
20222                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20223                pw.println("    prov[iders]: dump content providers");
20224                pw.println("    p[ackages]: dump installed packages");
20225                pw.println("    s[hared-users]: dump shared user IDs");
20226                pw.println("    m[essages]: print collected runtime messages");
20227                pw.println("    v[erifiers]: print package verifier info");
20228                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20229                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20230                pw.println("    version: print database version info");
20231                pw.println("    write: write current settings now");
20232                pw.println("    installs: details about install sessions");
20233                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20234                pw.println("    dexopt: dump dexopt state");
20235                pw.println("    compiler-stats: dump compiler statistics");
20236                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20237                pw.println("    <package.name>: info about given package");
20238                return;
20239            } else if ("--checkin".equals(opt)) {
20240                checkin = true;
20241            } else if ("-f".equals(opt)) {
20242                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20243            } else if ("--proto".equals(opt)) {
20244                dumpProto(fd);
20245                return;
20246            } else {
20247                pw.println("Unknown argument: " + opt + "; use -h for help");
20248            }
20249        }
20250
20251        // Is the caller requesting to dump a particular piece of data?
20252        if (opti < args.length) {
20253            String cmd = args[opti];
20254            opti++;
20255            // Is this a package name?
20256            if ("android".equals(cmd) || cmd.contains(".")) {
20257                packageName = cmd;
20258                // When dumping a single package, we always dump all of its
20259                // filter information since the amount of data will be reasonable.
20260                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20261            } else if ("check-permission".equals(cmd)) {
20262                if (opti >= args.length) {
20263                    pw.println("Error: check-permission missing permission argument");
20264                    return;
20265                }
20266                String perm = args[opti];
20267                opti++;
20268                if (opti >= args.length) {
20269                    pw.println("Error: check-permission missing package argument");
20270                    return;
20271                }
20272
20273                String pkg = args[opti];
20274                opti++;
20275                int user = UserHandle.getUserId(Binder.getCallingUid());
20276                if (opti < args.length) {
20277                    try {
20278                        user = Integer.parseInt(args[opti]);
20279                    } catch (NumberFormatException e) {
20280                        pw.println("Error: check-permission user argument is not a number: "
20281                                + args[opti]);
20282                        return;
20283                    }
20284                }
20285
20286                // Normalize package name to handle renamed packages and static libs
20287                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20288
20289                pw.println(checkPermission(perm, pkg, user));
20290                return;
20291            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20292                dumpState.setDump(DumpState.DUMP_LIBS);
20293            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20294                dumpState.setDump(DumpState.DUMP_FEATURES);
20295            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20296                if (opti >= args.length) {
20297                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20298                            | DumpState.DUMP_SERVICE_RESOLVERS
20299                            | DumpState.DUMP_RECEIVER_RESOLVERS
20300                            | DumpState.DUMP_CONTENT_RESOLVERS);
20301                } else {
20302                    while (opti < args.length) {
20303                        String name = args[opti];
20304                        if ("a".equals(name) || "activity".equals(name)) {
20305                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20306                        } else if ("s".equals(name) || "service".equals(name)) {
20307                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20308                        } else if ("r".equals(name) || "receiver".equals(name)) {
20309                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20310                        } else if ("c".equals(name) || "content".equals(name)) {
20311                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20312                        } else {
20313                            pw.println("Error: unknown resolver table type: " + name);
20314                            return;
20315                        }
20316                        opti++;
20317                    }
20318                }
20319            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20320                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20321            } else if ("permission".equals(cmd)) {
20322                if (opti >= args.length) {
20323                    pw.println("Error: permission requires permission name");
20324                    return;
20325                }
20326                permissionNames = new ArraySet<>();
20327                while (opti < args.length) {
20328                    permissionNames.add(args[opti]);
20329                    opti++;
20330                }
20331                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20332                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20333            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20334                dumpState.setDump(DumpState.DUMP_PREFERRED);
20335            } else if ("preferred-xml".equals(cmd)) {
20336                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20337                if (opti < args.length && "--full".equals(args[opti])) {
20338                    fullPreferred = true;
20339                    opti++;
20340                }
20341            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20342                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20343            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20344                dumpState.setDump(DumpState.DUMP_PACKAGES);
20345            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20346                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20347            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20349            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20350                dumpState.setDump(DumpState.DUMP_MESSAGES);
20351            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20352                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20353            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20354                    || "intent-filter-verifiers".equals(cmd)) {
20355                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20356            } else if ("version".equals(cmd)) {
20357                dumpState.setDump(DumpState.DUMP_VERSION);
20358            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20359                dumpState.setDump(DumpState.DUMP_KEYSETS);
20360            } else if ("installs".equals(cmd)) {
20361                dumpState.setDump(DumpState.DUMP_INSTALLS);
20362            } else if ("frozen".equals(cmd)) {
20363                dumpState.setDump(DumpState.DUMP_FROZEN);
20364            } else if ("volumes".equals(cmd)) {
20365                dumpState.setDump(DumpState.DUMP_VOLUMES);
20366            } else if ("dexopt".equals(cmd)) {
20367                dumpState.setDump(DumpState.DUMP_DEXOPT);
20368            } else if ("compiler-stats".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20370            } else if ("changes".equals(cmd)) {
20371                dumpState.setDump(DumpState.DUMP_CHANGES);
20372            } else if ("write".equals(cmd)) {
20373                synchronized (mPackages) {
20374                    mSettings.writeLPr();
20375                    pw.println("Settings written.");
20376                    return;
20377                }
20378            }
20379        }
20380
20381        if (checkin) {
20382            pw.println("vers,1");
20383        }
20384
20385        // reader
20386        synchronized (mPackages) {
20387            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20388                if (!checkin) {
20389                    if (dumpState.onTitlePrinted())
20390                        pw.println();
20391                    pw.println("Database versions:");
20392                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20393                }
20394            }
20395
20396            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20397                if (!checkin) {
20398                    if (dumpState.onTitlePrinted())
20399                        pw.println();
20400                    pw.println("Verifiers:");
20401                    pw.print("  Required: ");
20402                    pw.print(mRequiredVerifierPackage);
20403                    pw.print(" (uid=");
20404                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20405                            UserHandle.USER_SYSTEM));
20406                    pw.println(")");
20407                } else if (mRequiredVerifierPackage != null) {
20408                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20409                    pw.print(",");
20410                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20411                            UserHandle.USER_SYSTEM));
20412                }
20413            }
20414
20415            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20416                    packageName == null) {
20417                if (mIntentFilterVerifierComponent != null) {
20418                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20419                    if (!checkin) {
20420                        if (dumpState.onTitlePrinted())
20421                            pw.println();
20422                        pw.println("Intent Filter Verifier:");
20423                        pw.print("  Using: ");
20424                        pw.print(verifierPackageName);
20425                        pw.print(" (uid=");
20426                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20427                                UserHandle.USER_SYSTEM));
20428                        pw.println(")");
20429                    } else if (verifierPackageName != null) {
20430                        pw.print("ifv,"); pw.print(verifierPackageName);
20431                        pw.print(",");
20432                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20433                                UserHandle.USER_SYSTEM));
20434                    }
20435                } else {
20436                    pw.println();
20437                    pw.println("No Intent Filter Verifier available!");
20438                }
20439            }
20440
20441            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20442                boolean printedHeader = false;
20443                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20444                while (it.hasNext()) {
20445                    String libName = it.next();
20446                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20447                    if (versionedLib == null) {
20448                        continue;
20449                    }
20450                    final int versionCount = versionedLib.size();
20451                    for (int i = 0; i < versionCount; i++) {
20452                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20453                        if (!checkin) {
20454                            if (!printedHeader) {
20455                                if (dumpState.onTitlePrinted())
20456                                    pw.println();
20457                                pw.println("Libraries:");
20458                                printedHeader = true;
20459                            }
20460                            pw.print("  ");
20461                        } else {
20462                            pw.print("lib,");
20463                        }
20464                        pw.print(libEntry.info.getName());
20465                        if (libEntry.info.isStatic()) {
20466                            pw.print(" version=" + libEntry.info.getVersion());
20467                        }
20468                        if (!checkin) {
20469                            pw.print(" -> ");
20470                        }
20471                        if (libEntry.path != null) {
20472                            pw.print(" (jar) ");
20473                            pw.print(libEntry.path);
20474                        } else {
20475                            pw.print(" (apk) ");
20476                            pw.print(libEntry.apk);
20477                        }
20478                        pw.println();
20479                    }
20480                }
20481            }
20482
20483            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20484                if (dumpState.onTitlePrinted())
20485                    pw.println();
20486                if (!checkin) {
20487                    pw.println("Features:");
20488                }
20489
20490                synchronized (mAvailableFeatures) {
20491                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20492                        if (checkin) {
20493                            pw.print("feat,");
20494                            pw.print(feat.name);
20495                            pw.print(",");
20496                            pw.println(feat.version);
20497                        } else {
20498                            pw.print("  ");
20499                            pw.print(feat.name);
20500                            if (feat.version > 0) {
20501                                pw.print(" version=");
20502                                pw.print(feat.version);
20503                            }
20504                            pw.println();
20505                        }
20506                    }
20507                }
20508            }
20509
20510            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20511                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20512                        : "Activity Resolver Table:", "  ", packageName,
20513                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20514                    dumpState.setTitlePrinted(true);
20515                }
20516            }
20517            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20518                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20519                        : "Receiver Resolver Table:", "  ", packageName,
20520                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20521                    dumpState.setTitlePrinted(true);
20522                }
20523            }
20524            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20525                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20526                        : "Service Resolver Table:", "  ", packageName,
20527                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20528                    dumpState.setTitlePrinted(true);
20529                }
20530            }
20531            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20532                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20533                        : "Provider Resolver Table:", "  ", packageName,
20534                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20535                    dumpState.setTitlePrinted(true);
20536                }
20537            }
20538
20539            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20540                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20541                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20542                    int user = mSettings.mPreferredActivities.keyAt(i);
20543                    if (pir.dump(pw,
20544                            dumpState.getTitlePrinted()
20545                                ? "\nPreferred Activities User " + user + ":"
20546                                : "Preferred Activities User " + user + ":", "  ",
20547                            packageName, true, false)) {
20548                        dumpState.setTitlePrinted(true);
20549                    }
20550                }
20551            }
20552
20553            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20554                pw.flush();
20555                FileOutputStream fout = new FileOutputStream(fd);
20556                BufferedOutputStream str = new BufferedOutputStream(fout);
20557                XmlSerializer serializer = new FastXmlSerializer();
20558                try {
20559                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20560                    serializer.startDocument(null, true);
20561                    serializer.setFeature(
20562                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20563                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20564                    serializer.endDocument();
20565                    serializer.flush();
20566                } catch (IllegalArgumentException e) {
20567                    pw.println("Failed writing: " + e);
20568                } catch (IllegalStateException e) {
20569                    pw.println("Failed writing: " + e);
20570                } catch (IOException e) {
20571                    pw.println("Failed writing: " + e);
20572                }
20573            }
20574
20575            if (!checkin
20576                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20577                    && packageName == null) {
20578                pw.println();
20579                int count = mSettings.mPackages.size();
20580                if (count == 0) {
20581                    pw.println("No applications!");
20582                    pw.println();
20583                } else {
20584                    final String prefix = "  ";
20585                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20586                    if (allPackageSettings.size() == 0) {
20587                        pw.println("No domain preferred apps!");
20588                        pw.println();
20589                    } else {
20590                        pw.println("App verification status:");
20591                        pw.println();
20592                        count = 0;
20593                        for (PackageSetting ps : allPackageSettings) {
20594                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20595                            if (ivi == null || ivi.getPackageName() == null) continue;
20596                            pw.println(prefix + "Package: " + ivi.getPackageName());
20597                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20598                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20599                            pw.println();
20600                            count++;
20601                        }
20602                        if (count == 0) {
20603                            pw.println(prefix + "No app verification established.");
20604                            pw.println();
20605                        }
20606                        for (int userId : sUserManager.getUserIds()) {
20607                            pw.println("App linkages for user " + userId + ":");
20608                            pw.println();
20609                            count = 0;
20610                            for (PackageSetting ps : allPackageSettings) {
20611                                final long status = ps.getDomainVerificationStatusForUser(userId);
20612                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20613                                        && !DEBUG_DOMAIN_VERIFICATION) {
20614                                    continue;
20615                                }
20616                                pw.println(prefix + "Package: " + ps.name);
20617                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20618                                String statusStr = IntentFilterVerificationInfo.
20619                                        getStatusStringFromValue(status);
20620                                pw.println(prefix + "Status:  " + statusStr);
20621                                pw.println();
20622                                count++;
20623                            }
20624                            if (count == 0) {
20625                                pw.println(prefix + "No configured app linkages.");
20626                                pw.println();
20627                            }
20628                        }
20629                    }
20630                }
20631            }
20632
20633            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20634                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20635            }
20636
20637            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20638                boolean printedSomething = false;
20639                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20640                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20641                        continue;
20642                    }
20643                    if (!printedSomething) {
20644                        if (dumpState.onTitlePrinted())
20645                            pw.println();
20646                        pw.println("Registered ContentProviders:");
20647                        printedSomething = true;
20648                    }
20649                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20650                    pw.print("    "); pw.println(p.toString());
20651                }
20652                printedSomething = false;
20653                for (Map.Entry<String, PackageParser.Provider> entry :
20654                        mProvidersByAuthority.entrySet()) {
20655                    PackageParser.Provider p = entry.getValue();
20656                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20657                        continue;
20658                    }
20659                    if (!printedSomething) {
20660                        if (dumpState.onTitlePrinted())
20661                            pw.println();
20662                        pw.println("ContentProvider Authorities:");
20663                        printedSomething = true;
20664                    }
20665                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20666                    pw.print("    "); pw.println(p.toString());
20667                    if (p.info != null && p.info.applicationInfo != null) {
20668                        final String appInfo = p.info.applicationInfo.toString();
20669                        pw.print("      applicationInfo="); pw.println(appInfo);
20670                    }
20671                }
20672            }
20673
20674            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20675                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20676            }
20677
20678            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20679                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20680            }
20681
20682            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20683                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20684            }
20685
20686            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20687                if (dumpState.onTitlePrinted()) pw.println();
20688                pw.println("Package Changes:");
20689                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20690                final int K = mChangedPackages.size();
20691                for (int i = 0; i < K; i++) {
20692                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20693                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20694                    final int N = changes.size();
20695                    if (N == 0) {
20696                        pw.print("    "); pw.println("No packages changed");
20697                    } else {
20698                        for (int j = 0; j < N; j++) {
20699                            final String pkgName = changes.valueAt(j);
20700                            final int sequenceNumber = changes.keyAt(j);
20701                            pw.print("    ");
20702                            pw.print("seq=");
20703                            pw.print(sequenceNumber);
20704                            pw.print(", package=");
20705                            pw.println(pkgName);
20706                        }
20707                    }
20708                }
20709            }
20710
20711            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20712                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20713            }
20714
20715            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20716                // XXX should handle packageName != null by dumping only install data that
20717                // the given package is involved with.
20718                if (dumpState.onTitlePrinted()) pw.println();
20719
20720                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20721                ipw.println();
20722                ipw.println("Frozen packages:");
20723                ipw.increaseIndent();
20724                if (mFrozenPackages.size() == 0) {
20725                    ipw.println("(none)");
20726                } else {
20727                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20728                        ipw.println(mFrozenPackages.valueAt(i));
20729                    }
20730                }
20731                ipw.decreaseIndent();
20732            }
20733
20734            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
20735                if (dumpState.onTitlePrinted()) pw.println();
20736
20737                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20738                ipw.println();
20739                ipw.println("Loaded volumes:");
20740                ipw.increaseIndent();
20741                if (mLoadedVolumes.size() == 0) {
20742                    ipw.println("(none)");
20743                } else {
20744                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
20745                        ipw.println(mLoadedVolumes.valueAt(i));
20746                    }
20747                }
20748                ipw.decreaseIndent();
20749            }
20750
20751            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20752                if (dumpState.onTitlePrinted()) pw.println();
20753                dumpDexoptStateLPr(pw, packageName);
20754            }
20755
20756            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20757                if (dumpState.onTitlePrinted()) pw.println();
20758                dumpCompilerStatsLPr(pw, packageName);
20759            }
20760
20761            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20762                if (dumpState.onTitlePrinted()) pw.println();
20763                mSettings.dumpReadMessagesLPr(pw, dumpState);
20764
20765                pw.println();
20766                pw.println("Package warning messages:");
20767                dumpCriticalInfo(pw, null);
20768            }
20769
20770            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20771                dumpCriticalInfo(pw, "msg,");
20772            }
20773        }
20774
20775        // PackageInstaller should be called outside of mPackages lock
20776        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20777            // XXX should handle packageName != null by dumping only install data that
20778            // the given package is involved with.
20779            if (dumpState.onTitlePrinted()) pw.println();
20780            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20781        }
20782    }
20783
20784    private void dumpProto(FileDescriptor fd) {
20785        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20786
20787        synchronized (mPackages) {
20788            final long requiredVerifierPackageToken =
20789                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20790            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20791            proto.write(
20792                    PackageServiceDumpProto.PackageShortProto.UID,
20793                    getPackageUid(
20794                            mRequiredVerifierPackage,
20795                            MATCH_DEBUG_TRIAGED_MISSING,
20796                            UserHandle.USER_SYSTEM));
20797            proto.end(requiredVerifierPackageToken);
20798
20799            if (mIntentFilterVerifierComponent != null) {
20800                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20801                final long verifierPackageToken =
20802                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20803                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20804                proto.write(
20805                        PackageServiceDumpProto.PackageShortProto.UID,
20806                        getPackageUid(
20807                                verifierPackageName,
20808                                MATCH_DEBUG_TRIAGED_MISSING,
20809                                UserHandle.USER_SYSTEM));
20810                proto.end(verifierPackageToken);
20811            }
20812
20813            dumpSharedLibrariesProto(proto);
20814            dumpFeaturesProto(proto);
20815            mSettings.dumpPackagesProto(proto);
20816            mSettings.dumpSharedUsersProto(proto);
20817            dumpCriticalInfo(proto);
20818        }
20819        proto.flush();
20820    }
20821
20822    private void dumpFeaturesProto(ProtoOutputStream proto) {
20823        synchronized (mAvailableFeatures) {
20824            final int count = mAvailableFeatures.size();
20825            for (int i = 0; i < count; i++) {
20826                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
20827            }
20828        }
20829    }
20830
20831    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20832        final int count = mSharedLibraries.size();
20833        for (int i = 0; i < count; i++) {
20834            final String libName = mSharedLibraries.keyAt(i);
20835            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20836            if (versionedLib == null) {
20837                continue;
20838            }
20839            final int versionCount = versionedLib.size();
20840            for (int j = 0; j < versionCount; j++) {
20841                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20842                final long sharedLibraryToken =
20843                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20844                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20845                final boolean isJar = (libEntry.path != null);
20846                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20847                if (isJar) {
20848                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20849                } else {
20850                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20851                }
20852                proto.end(sharedLibraryToken);
20853            }
20854        }
20855    }
20856
20857    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20858        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20859        ipw.println();
20860        ipw.println("Dexopt state:");
20861        ipw.increaseIndent();
20862        Collection<PackageParser.Package> packages = null;
20863        if (packageName != null) {
20864            PackageParser.Package targetPackage = mPackages.get(packageName);
20865            if (targetPackage != null) {
20866                packages = Collections.singletonList(targetPackage);
20867            } else {
20868                ipw.println("Unable to find package: " + packageName);
20869                return;
20870            }
20871        } else {
20872            packages = mPackages.values();
20873        }
20874
20875        for (PackageParser.Package pkg : packages) {
20876            ipw.println("[" + pkg.packageName + "]");
20877            ipw.increaseIndent();
20878            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
20879                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
20880            ipw.decreaseIndent();
20881        }
20882    }
20883
20884    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20885        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20886        ipw.println();
20887        ipw.println("Compiler stats:");
20888        ipw.increaseIndent();
20889        Collection<PackageParser.Package> packages = null;
20890        if (packageName != null) {
20891            PackageParser.Package targetPackage = mPackages.get(packageName);
20892            if (targetPackage != null) {
20893                packages = Collections.singletonList(targetPackage);
20894            } else {
20895                ipw.println("Unable to find package: " + packageName);
20896                return;
20897            }
20898        } else {
20899            packages = mPackages.values();
20900        }
20901
20902        for (PackageParser.Package pkg : packages) {
20903            ipw.println("[" + pkg.packageName + "]");
20904            ipw.increaseIndent();
20905
20906            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20907            if (stats == null) {
20908                ipw.println("(No recorded stats)");
20909            } else {
20910                stats.dump(ipw);
20911            }
20912            ipw.decreaseIndent();
20913        }
20914    }
20915
20916    private String dumpDomainString(String packageName) {
20917        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20918                .getList();
20919        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20920
20921        ArraySet<String> result = new ArraySet<>();
20922        if (iviList.size() > 0) {
20923            for (IntentFilterVerificationInfo ivi : iviList) {
20924                for (String host : ivi.getDomains()) {
20925                    result.add(host);
20926                }
20927            }
20928        }
20929        if (filters != null && filters.size() > 0) {
20930            for (IntentFilter filter : filters) {
20931                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20932                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20933                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20934                    result.addAll(filter.getHostsList());
20935                }
20936            }
20937        }
20938
20939        StringBuilder sb = new StringBuilder(result.size() * 16);
20940        for (String domain : result) {
20941            if (sb.length() > 0) sb.append(" ");
20942            sb.append(domain);
20943        }
20944        return sb.toString();
20945    }
20946
20947    // ------- apps on sdcard specific code -------
20948    static final boolean DEBUG_SD_INSTALL = false;
20949
20950    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20951
20952    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20953
20954    private boolean mMediaMounted = false;
20955
20956    static String getEncryptKey() {
20957        try {
20958            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20959                    SD_ENCRYPTION_KEYSTORE_NAME);
20960            if (sdEncKey == null) {
20961                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20962                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20963                if (sdEncKey == null) {
20964                    Slog.e(TAG, "Failed to create encryption keys");
20965                    return null;
20966                }
20967            }
20968            return sdEncKey;
20969        } catch (NoSuchAlgorithmException nsae) {
20970            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20971            return null;
20972        } catch (IOException ioe) {
20973            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20974            return null;
20975        }
20976    }
20977
20978    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20979            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20980        final int size = infos.size();
20981        final String[] packageNames = new String[size];
20982        final int[] packageUids = new int[size];
20983        for (int i = 0; i < size; i++) {
20984            final ApplicationInfo info = infos.get(i);
20985            packageNames[i] = info.packageName;
20986            packageUids[i] = info.uid;
20987        }
20988        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20989                finishedReceiver);
20990    }
20991
20992    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20993            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20994        sendResourcesChangedBroadcast(mediaStatus, replacing,
20995                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20996    }
20997
20998    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20999            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21000        int size = pkgList.length;
21001        if (size > 0) {
21002            // Send broadcasts here
21003            Bundle extras = new Bundle();
21004            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21005            if (uidArr != null) {
21006                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21007            }
21008            if (replacing) {
21009                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21010            }
21011            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21012                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21013            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21014        }
21015    }
21016
21017    private void loadPrivatePackages(final VolumeInfo vol) {
21018        mHandler.post(new Runnable() {
21019            @Override
21020            public void run() {
21021                loadPrivatePackagesInner(vol);
21022            }
21023        });
21024    }
21025
21026    private void loadPrivatePackagesInner(VolumeInfo vol) {
21027        final String volumeUuid = vol.fsUuid;
21028        if (TextUtils.isEmpty(volumeUuid)) {
21029            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21030            return;
21031        }
21032
21033        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21034        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21035        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21036
21037        final VersionInfo ver;
21038        final List<PackageSetting> packages;
21039        synchronized (mPackages) {
21040            ver = mSettings.findOrCreateVersion(volumeUuid);
21041            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21042        }
21043
21044        for (PackageSetting ps : packages) {
21045            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21046            synchronized (mInstallLock) {
21047                final PackageParser.Package pkg;
21048                try {
21049                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21050                    loaded.add(pkg.applicationInfo);
21051
21052                } catch (PackageManagerException e) {
21053                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21054                }
21055
21056                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21057                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21058                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21059                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21060                }
21061            }
21062        }
21063
21064        // Reconcile app data for all started/unlocked users
21065        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21066        final UserManager um = mContext.getSystemService(UserManager.class);
21067        UserManagerInternal umInternal = getUserManagerInternal();
21068        for (UserInfo user : um.getUsers()) {
21069            final int flags;
21070            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21071                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21072            } else if (umInternal.isUserRunning(user.id)) {
21073                flags = StorageManager.FLAG_STORAGE_DE;
21074            } else {
21075                continue;
21076            }
21077
21078            try {
21079                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21080                synchronized (mInstallLock) {
21081                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21082                }
21083            } catch (IllegalStateException e) {
21084                // Device was probably ejected, and we'll process that event momentarily
21085                Slog.w(TAG, "Failed to prepare storage: " + e);
21086            }
21087        }
21088
21089        synchronized (mPackages) {
21090            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21091            if (sdkUpdated) {
21092                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21093                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21094            }
21095            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21096                    mPermissionCallback);
21097
21098            // Yay, everything is now upgraded
21099            ver.forceCurrent();
21100
21101            mSettings.writeLPr();
21102        }
21103
21104        for (PackageFreezer freezer : freezers) {
21105            freezer.close();
21106        }
21107
21108        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21109        sendResourcesChangedBroadcast(true, false, loaded, null);
21110        mLoadedVolumes.add(vol.getId());
21111    }
21112
21113    private void unloadPrivatePackages(final VolumeInfo vol) {
21114        mHandler.post(new Runnable() {
21115            @Override
21116            public void run() {
21117                unloadPrivatePackagesInner(vol);
21118            }
21119        });
21120    }
21121
21122    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21123        final String volumeUuid = vol.fsUuid;
21124        if (TextUtils.isEmpty(volumeUuid)) {
21125            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21126            return;
21127        }
21128
21129        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21130        synchronized (mInstallLock) {
21131        synchronized (mPackages) {
21132            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21133            for (PackageSetting ps : packages) {
21134                if (ps.pkg == null) continue;
21135
21136                final ApplicationInfo info = ps.pkg.applicationInfo;
21137                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21138                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21139
21140                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21141                        "unloadPrivatePackagesInner")) {
21142                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21143                            false, null)) {
21144                        unloaded.add(info);
21145                    } else {
21146                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21147                    }
21148                }
21149
21150                // Try very hard to release any references to this package
21151                // so we don't risk the system server being killed due to
21152                // open FDs
21153                AttributeCache.instance().removePackage(ps.name);
21154            }
21155
21156            mSettings.writeLPr();
21157        }
21158        }
21159
21160        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21161        sendResourcesChangedBroadcast(false, false, unloaded, null);
21162        mLoadedVolumes.remove(vol.getId());
21163
21164        // Try very hard to release any references to this path so we don't risk
21165        // the system server being killed due to open FDs
21166        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21167
21168        for (int i = 0; i < 3; i++) {
21169            System.gc();
21170            System.runFinalization();
21171        }
21172    }
21173
21174    private void assertPackageKnown(String volumeUuid, String packageName)
21175            throws PackageManagerException {
21176        synchronized (mPackages) {
21177            // Normalize package name to handle renamed packages
21178            packageName = normalizePackageNameLPr(packageName);
21179
21180            final PackageSetting ps = mSettings.mPackages.get(packageName);
21181            if (ps == null) {
21182                throw new PackageManagerException("Package " + packageName + " is unknown");
21183            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21184                throw new PackageManagerException(
21185                        "Package " + packageName + " found on unknown volume " + volumeUuid
21186                                + "; expected volume " + ps.volumeUuid);
21187            }
21188        }
21189    }
21190
21191    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21192            throws PackageManagerException {
21193        synchronized (mPackages) {
21194            // Normalize package name to handle renamed packages
21195            packageName = normalizePackageNameLPr(packageName);
21196
21197            final PackageSetting ps = mSettings.mPackages.get(packageName);
21198            if (ps == null) {
21199                throw new PackageManagerException("Package " + packageName + " is unknown");
21200            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21201                throw new PackageManagerException(
21202                        "Package " + packageName + " found on unknown volume " + volumeUuid
21203                                + "; expected volume " + ps.volumeUuid);
21204            } else if (!ps.getInstalled(userId)) {
21205                throw new PackageManagerException(
21206                        "Package " + packageName + " not installed for user " + userId);
21207            }
21208        }
21209    }
21210
21211    private List<String> collectAbsoluteCodePaths() {
21212        synchronized (mPackages) {
21213            List<String> codePaths = new ArrayList<>();
21214            final int packageCount = mSettings.mPackages.size();
21215            for (int i = 0; i < packageCount; i++) {
21216                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21217                codePaths.add(ps.codePath.getAbsolutePath());
21218            }
21219            return codePaths;
21220        }
21221    }
21222
21223    /**
21224     * Examine all apps present on given mounted volume, and destroy apps that
21225     * aren't expected, either due to uninstallation or reinstallation on
21226     * another volume.
21227     */
21228    private void reconcileApps(String volumeUuid) {
21229        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21230        List<File> filesToDelete = null;
21231
21232        final File[] files = FileUtils.listFilesOrEmpty(
21233                Environment.getDataAppDirectory(volumeUuid));
21234        for (File file : files) {
21235            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21236                    && !PackageInstallerService.isStageName(file.getName());
21237            if (!isPackage) {
21238                // Ignore entries which are not packages
21239                continue;
21240            }
21241
21242            String absolutePath = file.getAbsolutePath();
21243
21244            boolean pathValid = false;
21245            final int absoluteCodePathCount = absoluteCodePaths.size();
21246            for (int i = 0; i < absoluteCodePathCount; i++) {
21247                String absoluteCodePath = absoluteCodePaths.get(i);
21248                if (absolutePath.startsWith(absoluteCodePath)) {
21249                    pathValid = true;
21250                    break;
21251                }
21252            }
21253
21254            if (!pathValid) {
21255                if (filesToDelete == null) {
21256                    filesToDelete = new ArrayList<>();
21257                }
21258                filesToDelete.add(file);
21259            }
21260        }
21261
21262        if (filesToDelete != null) {
21263            final int fileToDeleteCount = filesToDelete.size();
21264            for (int i = 0; i < fileToDeleteCount; i++) {
21265                File fileToDelete = filesToDelete.get(i);
21266                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21267                synchronized (mInstallLock) {
21268                    removeCodePathLI(fileToDelete);
21269                }
21270            }
21271        }
21272    }
21273
21274    /**
21275     * Reconcile all app data for the given user.
21276     * <p>
21277     * Verifies that directories exist and that ownership and labeling is
21278     * correct for all installed apps on all mounted volumes.
21279     */
21280    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21281        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21282        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21283            final String volumeUuid = vol.getFsUuid();
21284            synchronized (mInstallLock) {
21285                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21286            }
21287        }
21288    }
21289
21290    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21291            boolean migrateAppData) {
21292        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21293    }
21294
21295    /**
21296     * Reconcile all app data on given mounted volume.
21297     * <p>
21298     * Destroys app data that isn't expected, either due to uninstallation or
21299     * reinstallation on another volume.
21300     * <p>
21301     * Verifies that directories exist and that ownership and labeling is
21302     * correct for all installed apps.
21303     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21304     */
21305    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21306            boolean migrateAppData, boolean onlyCoreApps) {
21307        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21308                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21309        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21310
21311        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21312        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21313
21314        // First look for stale data that doesn't belong, and check if things
21315        // have changed since we did our last restorecon
21316        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21317            if (StorageManager.isFileEncryptedNativeOrEmulated()
21318                    && !StorageManager.isUserKeyUnlocked(userId)) {
21319                throw new RuntimeException(
21320                        "Yikes, someone asked us to reconcile CE storage while " + userId
21321                                + " was still locked; this would have caused massive data loss!");
21322            }
21323
21324            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21325            for (File file : files) {
21326                final String packageName = file.getName();
21327                try {
21328                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21329                } catch (PackageManagerException e) {
21330                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21331                    try {
21332                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21333                                StorageManager.FLAG_STORAGE_CE, 0);
21334                    } catch (InstallerException e2) {
21335                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21336                    }
21337                }
21338            }
21339        }
21340        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21341            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21342            for (File file : files) {
21343                final String packageName = file.getName();
21344                try {
21345                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21346                } catch (PackageManagerException e) {
21347                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21348                    try {
21349                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21350                                StorageManager.FLAG_STORAGE_DE, 0);
21351                    } catch (InstallerException e2) {
21352                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21353                    }
21354                }
21355            }
21356        }
21357
21358        // Ensure that data directories are ready to roll for all packages
21359        // installed for this volume and user
21360        final List<PackageSetting> packages;
21361        synchronized (mPackages) {
21362            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21363        }
21364        int preparedCount = 0;
21365        for (PackageSetting ps : packages) {
21366            final String packageName = ps.name;
21367            if (ps.pkg == null) {
21368                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21369                // TODO: might be due to legacy ASEC apps; we should circle back
21370                // and reconcile again once they're scanned
21371                continue;
21372            }
21373            // Skip non-core apps if requested
21374            if (onlyCoreApps && !ps.pkg.coreApp) {
21375                result.add(packageName);
21376                continue;
21377            }
21378
21379            if (ps.getInstalled(userId)) {
21380                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21381                preparedCount++;
21382            }
21383        }
21384
21385        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21386        return result;
21387    }
21388
21389    /**
21390     * Prepare app data for the given app just after it was installed or
21391     * upgraded. This method carefully only touches users that it's installed
21392     * for, and it forces a restorecon to handle any seinfo changes.
21393     * <p>
21394     * Verifies that directories exist and that ownership and labeling is
21395     * correct for all installed apps. If there is an ownership mismatch, it
21396     * will try recovering system apps by wiping data; third-party app data is
21397     * left intact.
21398     * <p>
21399     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21400     */
21401    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21402        final PackageSetting ps;
21403        synchronized (mPackages) {
21404            ps = mSettings.mPackages.get(pkg.packageName);
21405            mSettings.writeKernelMappingLPr(ps);
21406        }
21407
21408        final UserManager um = mContext.getSystemService(UserManager.class);
21409        UserManagerInternal umInternal = getUserManagerInternal();
21410        for (UserInfo user : um.getUsers()) {
21411            final int flags;
21412            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21413                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21414            } else if (umInternal.isUserRunning(user.id)) {
21415                flags = StorageManager.FLAG_STORAGE_DE;
21416            } else {
21417                continue;
21418            }
21419
21420            if (ps.getInstalled(user.id)) {
21421                // TODO: when user data is locked, mark that we're still dirty
21422                prepareAppDataLIF(pkg, user.id, flags);
21423            }
21424        }
21425    }
21426
21427    /**
21428     * Prepare app data for the given app.
21429     * <p>
21430     * Verifies that directories exist and that ownership and labeling is
21431     * correct for all installed apps. If there is an ownership mismatch, this
21432     * will try recovering system apps by wiping data; third-party app data is
21433     * left intact.
21434     */
21435    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21436        if (pkg == null) {
21437            Slog.wtf(TAG, "Package was null!", new Throwable());
21438            return;
21439        }
21440        prepareAppDataLeafLIF(pkg, userId, flags);
21441        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21442        for (int i = 0; i < childCount; i++) {
21443            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21444        }
21445    }
21446
21447    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21448            boolean maybeMigrateAppData) {
21449        prepareAppDataLIF(pkg, userId, flags);
21450
21451        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21452            // We may have just shuffled around app data directories, so
21453            // prepare them one more time
21454            prepareAppDataLIF(pkg, userId, flags);
21455        }
21456    }
21457
21458    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21459        if (DEBUG_APP_DATA) {
21460            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21461                    + Integer.toHexString(flags));
21462        }
21463
21464        final String volumeUuid = pkg.volumeUuid;
21465        final String packageName = pkg.packageName;
21466        final ApplicationInfo app = pkg.applicationInfo;
21467        final int appId = UserHandle.getAppId(app.uid);
21468
21469        Preconditions.checkNotNull(app.seInfo);
21470
21471        long ceDataInode = -1;
21472        try {
21473            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21474                    appId, app.seInfo, app.targetSdkVersion);
21475        } catch (InstallerException e) {
21476            if (app.isSystemApp()) {
21477                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21478                        + ", but trying to recover: " + e);
21479                destroyAppDataLeafLIF(pkg, userId, flags);
21480                try {
21481                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21482                            appId, app.seInfo, app.targetSdkVersion);
21483                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21484                } catch (InstallerException e2) {
21485                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21486                }
21487            } else {
21488                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21489            }
21490        }
21491
21492        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21493            // TODO: mark this structure as dirty so we persist it!
21494            synchronized (mPackages) {
21495                final PackageSetting ps = mSettings.mPackages.get(packageName);
21496                if (ps != null) {
21497                    ps.setCeDataInode(ceDataInode, userId);
21498                }
21499            }
21500        }
21501
21502        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21503    }
21504
21505    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21506        if (pkg == null) {
21507            Slog.wtf(TAG, "Package was null!", new Throwable());
21508            return;
21509        }
21510        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21512        for (int i = 0; i < childCount; i++) {
21513            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21514        }
21515    }
21516
21517    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21518        final String volumeUuid = pkg.volumeUuid;
21519        final String packageName = pkg.packageName;
21520        final ApplicationInfo app = pkg.applicationInfo;
21521
21522        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21523            // Create a native library symlink only if we have native libraries
21524            // and if the native libraries are 32 bit libraries. We do not provide
21525            // this symlink for 64 bit libraries.
21526            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21527                final String nativeLibPath = app.nativeLibraryDir;
21528                try {
21529                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21530                            nativeLibPath, userId);
21531                } catch (InstallerException e) {
21532                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21533                }
21534            }
21535        }
21536    }
21537
21538    /**
21539     * For system apps on non-FBE devices, this method migrates any existing
21540     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21541     * requested by the app.
21542     */
21543    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21544        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21545                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21546            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21547                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21548            try {
21549                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21550                        storageTarget);
21551            } catch (InstallerException e) {
21552                logCriticalInfo(Log.WARN,
21553                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21554            }
21555            return true;
21556        } else {
21557            return false;
21558        }
21559    }
21560
21561    public PackageFreezer freezePackage(String packageName, String killReason) {
21562        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21563    }
21564
21565    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21566        return new PackageFreezer(packageName, userId, killReason);
21567    }
21568
21569    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21570            String killReason) {
21571        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21572    }
21573
21574    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21575            String killReason) {
21576        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21577            return new PackageFreezer();
21578        } else {
21579            return freezePackage(packageName, userId, killReason);
21580        }
21581    }
21582
21583    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21584            String killReason) {
21585        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21586    }
21587
21588    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21589            String killReason) {
21590        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21591            return new PackageFreezer();
21592        } else {
21593            return freezePackage(packageName, userId, killReason);
21594        }
21595    }
21596
21597    /**
21598     * Class that freezes and kills the given package upon creation, and
21599     * unfreezes it upon closing. This is typically used when doing surgery on
21600     * app code/data to prevent the app from running while you're working.
21601     */
21602    private class PackageFreezer implements AutoCloseable {
21603        private final String mPackageName;
21604        private final PackageFreezer[] mChildren;
21605
21606        private final boolean mWeFroze;
21607
21608        private final AtomicBoolean mClosed = new AtomicBoolean();
21609        private final CloseGuard mCloseGuard = CloseGuard.get();
21610
21611        /**
21612         * Create and return a stub freezer that doesn't actually do anything,
21613         * typically used when someone requested
21614         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21615         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21616         */
21617        public PackageFreezer() {
21618            mPackageName = null;
21619            mChildren = null;
21620            mWeFroze = false;
21621            mCloseGuard.open("close");
21622        }
21623
21624        public PackageFreezer(String packageName, int userId, String killReason) {
21625            synchronized (mPackages) {
21626                mPackageName = packageName;
21627                mWeFroze = mFrozenPackages.add(mPackageName);
21628
21629                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21630                if (ps != null) {
21631                    killApplication(ps.name, ps.appId, userId, killReason);
21632                }
21633
21634                final PackageParser.Package p = mPackages.get(packageName);
21635                if (p != null && p.childPackages != null) {
21636                    final int N = p.childPackages.size();
21637                    mChildren = new PackageFreezer[N];
21638                    for (int i = 0; i < N; i++) {
21639                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21640                                userId, killReason);
21641                    }
21642                } else {
21643                    mChildren = null;
21644                }
21645            }
21646            mCloseGuard.open("close");
21647        }
21648
21649        @Override
21650        protected void finalize() throws Throwable {
21651            try {
21652                if (mCloseGuard != null) {
21653                    mCloseGuard.warnIfOpen();
21654                }
21655
21656                close();
21657            } finally {
21658                super.finalize();
21659            }
21660        }
21661
21662        @Override
21663        public void close() {
21664            mCloseGuard.close();
21665            if (mClosed.compareAndSet(false, true)) {
21666                synchronized (mPackages) {
21667                    if (mWeFroze) {
21668                        mFrozenPackages.remove(mPackageName);
21669                    }
21670
21671                    if (mChildren != null) {
21672                        for (PackageFreezer freezer : mChildren) {
21673                            freezer.close();
21674                        }
21675                    }
21676                }
21677            }
21678        }
21679    }
21680
21681    /**
21682     * Verify that given package is currently frozen.
21683     */
21684    private void checkPackageFrozen(String packageName) {
21685        synchronized (mPackages) {
21686            if (!mFrozenPackages.contains(packageName)) {
21687                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21688            }
21689        }
21690    }
21691
21692    @Override
21693    public int movePackage(final String packageName, final String volumeUuid) {
21694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21695
21696        final int callingUid = Binder.getCallingUid();
21697        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21698        final int moveId = mNextMoveId.getAndIncrement();
21699        mHandler.post(new Runnable() {
21700            @Override
21701            public void run() {
21702                try {
21703                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
21704                } catch (PackageManagerException e) {
21705                    Slog.w(TAG, "Failed to move " + packageName, e);
21706                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
21707                }
21708            }
21709        });
21710        return moveId;
21711    }
21712
21713    private void movePackageInternal(final String packageName, final String volumeUuid,
21714            final int moveId, final int callingUid, UserHandle user)
21715                    throws PackageManagerException {
21716        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21717        final PackageManager pm = mContext.getPackageManager();
21718
21719        final boolean currentAsec;
21720        final String currentVolumeUuid;
21721        final File codeFile;
21722        final String installerPackageName;
21723        final String packageAbiOverride;
21724        final int appId;
21725        final String seinfo;
21726        final String label;
21727        final int targetSdkVersion;
21728        final PackageFreezer freezer;
21729        final int[] installedUserIds;
21730
21731        // reader
21732        synchronized (mPackages) {
21733            final PackageParser.Package pkg = mPackages.get(packageName);
21734            final PackageSetting ps = mSettings.mPackages.get(packageName);
21735            if (pkg == null
21736                    || ps == null
21737                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
21738                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21739            }
21740            if (pkg.applicationInfo.isSystemApp()) {
21741                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21742                        "Cannot move system application");
21743            }
21744
21745            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21746            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21747                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21748            if (isInternalStorage && !allow3rdPartyOnInternal) {
21749                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21750                        "3rd party apps are not allowed on internal storage");
21751            }
21752
21753            if (pkg.applicationInfo.isExternalAsec()) {
21754                currentAsec = true;
21755                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21756            } else if (pkg.applicationInfo.isForwardLocked()) {
21757                currentAsec = true;
21758                currentVolumeUuid = "forward_locked";
21759            } else {
21760                currentAsec = false;
21761                currentVolumeUuid = ps.volumeUuid;
21762
21763                final File probe = new File(pkg.codePath);
21764                final File probeOat = new File(probe, "oat");
21765                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21766                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21767                            "Move only supported for modern cluster style installs");
21768                }
21769            }
21770
21771            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21772                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21773                        "Package already moved to " + volumeUuid);
21774            }
21775            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21776                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21777                        "Device admin cannot be moved");
21778            }
21779
21780            if (mFrozenPackages.contains(packageName)) {
21781                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21782                        "Failed to move already frozen package");
21783            }
21784
21785            codeFile = new File(pkg.codePath);
21786            installerPackageName = ps.installerPackageName;
21787            packageAbiOverride = ps.cpuAbiOverrideString;
21788            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21789            seinfo = pkg.applicationInfo.seInfo;
21790            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21791            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21792            freezer = freezePackage(packageName, "movePackageInternal");
21793            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21794        }
21795
21796        final Bundle extras = new Bundle();
21797        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21798        extras.putString(Intent.EXTRA_TITLE, label);
21799        mMoveCallbacks.notifyCreated(moveId, extras);
21800
21801        int installFlags;
21802        final boolean moveCompleteApp;
21803        final File measurePath;
21804
21805        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21806            installFlags = INSTALL_INTERNAL;
21807            moveCompleteApp = !currentAsec;
21808            measurePath = Environment.getDataAppDirectory(volumeUuid);
21809        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21810            installFlags = INSTALL_EXTERNAL;
21811            moveCompleteApp = false;
21812            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21813        } else {
21814            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21815            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21816                    || !volume.isMountedWritable()) {
21817                freezer.close();
21818                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21819                        "Move location not mounted private volume");
21820            }
21821
21822            Preconditions.checkState(!currentAsec);
21823
21824            installFlags = INSTALL_INTERNAL;
21825            moveCompleteApp = true;
21826            measurePath = Environment.getDataAppDirectory(volumeUuid);
21827        }
21828
21829        // If we're moving app data around, we need all the users unlocked
21830        if (moveCompleteApp) {
21831            for (int userId : installedUserIds) {
21832                if (StorageManager.isFileEncryptedNativeOrEmulated()
21833                        && !StorageManager.isUserKeyUnlocked(userId)) {
21834                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
21835                            "User " + userId + " must be unlocked");
21836                }
21837            }
21838        }
21839
21840        final PackageStats stats = new PackageStats(null, -1);
21841        synchronized (mInstaller) {
21842            for (int userId : installedUserIds) {
21843                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21844                    freezer.close();
21845                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21846                            "Failed to measure package size");
21847                }
21848            }
21849        }
21850
21851        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21852                + stats.dataSize);
21853
21854        final long startFreeBytes = measurePath.getUsableSpace();
21855        final long sizeBytes;
21856        if (moveCompleteApp) {
21857            sizeBytes = stats.codeSize + stats.dataSize;
21858        } else {
21859            sizeBytes = stats.codeSize;
21860        }
21861
21862        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21863            freezer.close();
21864            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21865                    "Not enough free space to move");
21866        }
21867
21868        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21869
21870        final CountDownLatch installedLatch = new CountDownLatch(1);
21871        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21872            @Override
21873            public void onUserActionRequired(Intent intent) throws RemoteException {
21874                throw new IllegalStateException();
21875            }
21876
21877            @Override
21878            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21879                    Bundle extras) throws RemoteException {
21880                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21881                        + PackageManager.installStatusToString(returnCode, msg));
21882
21883                installedLatch.countDown();
21884                freezer.close();
21885
21886                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21887                switch (status) {
21888                    case PackageInstaller.STATUS_SUCCESS:
21889                        mMoveCallbacks.notifyStatusChanged(moveId,
21890                                PackageManager.MOVE_SUCCEEDED);
21891                        break;
21892                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21893                        mMoveCallbacks.notifyStatusChanged(moveId,
21894                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21895                        break;
21896                    default:
21897                        mMoveCallbacks.notifyStatusChanged(moveId,
21898                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21899                        break;
21900                }
21901            }
21902        };
21903
21904        final MoveInfo move;
21905        if (moveCompleteApp) {
21906            // Kick off a thread to report progress estimates
21907            new Thread() {
21908                @Override
21909                public void run() {
21910                    while (true) {
21911                        try {
21912                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21913                                break;
21914                            }
21915                        } catch (InterruptedException ignored) {
21916                        }
21917
21918                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
21919                        final int progress = 10 + (int) MathUtils.constrain(
21920                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21921                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21922                    }
21923                }
21924            }.start();
21925
21926            final String dataAppName = codeFile.getName();
21927            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21928                    dataAppName, appId, seinfo, targetSdkVersion);
21929        } else {
21930            move = null;
21931        }
21932
21933        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21934
21935        final Message msg = mHandler.obtainMessage(INIT_COPY);
21936        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21937        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21938                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21939                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21940                PackageManager.INSTALL_REASON_UNKNOWN);
21941        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21942        msg.obj = params;
21943
21944        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21945                System.identityHashCode(msg.obj));
21946        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21947                System.identityHashCode(msg.obj));
21948
21949        mHandler.sendMessage(msg);
21950    }
21951
21952    @Override
21953    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21954        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21955
21956        final int realMoveId = mNextMoveId.getAndIncrement();
21957        final Bundle extras = new Bundle();
21958        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21959        mMoveCallbacks.notifyCreated(realMoveId, extras);
21960
21961        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21962            @Override
21963            public void onCreated(int moveId, Bundle extras) {
21964                // Ignored
21965            }
21966
21967            @Override
21968            public void onStatusChanged(int moveId, int status, long estMillis) {
21969                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21970            }
21971        };
21972
21973        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21974        storage.setPrimaryStorageUuid(volumeUuid, callback);
21975        return realMoveId;
21976    }
21977
21978    @Override
21979    public int getMoveStatus(int moveId) {
21980        mContext.enforceCallingOrSelfPermission(
21981                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21982        return mMoveCallbacks.mLastStatus.get(moveId);
21983    }
21984
21985    @Override
21986    public void registerMoveCallback(IPackageMoveObserver callback) {
21987        mContext.enforceCallingOrSelfPermission(
21988                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21989        mMoveCallbacks.register(callback);
21990    }
21991
21992    @Override
21993    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21994        mContext.enforceCallingOrSelfPermission(
21995                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21996        mMoveCallbacks.unregister(callback);
21997    }
21998
21999    @Override
22000    public boolean setInstallLocation(int loc) {
22001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22002                null);
22003        if (getInstallLocation() == loc) {
22004            return true;
22005        }
22006        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22007                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22008            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22009                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22010            return true;
22011        }
22012        return false;
22013   }
22014
22015    @Override
22016    public int getInstallLocation() {
22017        // allow instant app access
22018        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22019                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22020                PackageHelper.APP_INSTALL_AUTO);
22021    }
22022
22023    /** Called by UserManagerService */
22024    void cleanUpUser(UserManagerService userManager, int userHandle) {
22025        synchronized (mPackages) {
22026            mDirtyUsers.remove(userHandle);
22027            mUserNeedsBadging.delete(userHandle);
22028            mSettings.removeUserLPw(userHandle);
22029            mPendingBroadcasts.remove(userHandle);
22030            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22031            removeUnusedPackagesLPw(userManager, userHandle);
22032        }
22033    }
22034
22035    /**
22036     * We're removing userHandle and would like to remove any downloaded packages
22037     * that are no longer in use by any other user.
22038     * @param userHandle the user being removed
22039     */
22040    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22041        final boolean DEBUG_CLEAN_APKS = false;
22042        int [] users = userManager.getUserIds();
22043        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22044        while (psit.hasNext()) {
22045            PackageSetting ps = psit.next();
22046            if (ps.pkg == null) {
22047                continue;
22048            }
22049            final String packageName = ps.pkg.packageName;
22050            // Skip over if system app
22051            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22052                continue;
22053            }
22054            if (DEBUG_CLEAN_APKS) {
22055                Slog.i(TAG, "Checking package " + packageName);
22056            }
22057            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22058            if (keep) {
22059                if (DEBUG_CLEAN_APKS) {
22060                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22061                }
22062            } else {
22063                for (int i = 0; i < users.length; i++) {
22064                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22065                        keep = true;
22066                        if (DEBUG_CLEAN_APKS) {
22067                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22068                                    + users[i]);
22069                        }
22070                        break;
22071                    }
22072                }
22073            }
22074            if (!keep) {
22075                if (DEBUG_CLEAN_APKS) {
22076                    Slog.i(TAG, "  Removing package " + packageName);
22077                }
22078                mHandler.post(new Runnable() {
22079                    public void run() {
22080                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22081                                userHandle, 0);
22082                    } //end run
22083                });
22084            }
22085        }
22086    }
22087
22088    /** Called by UserManagerService */
22089    void createNewUser(int userId, String[] disallowedPackages) {
22090        synchronized (mInstallLock) {
22091            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22092        }
22093        synchronized (mPackages) {
22094            scheduleWritePackageRestrictionsLocked(userId);
22095            scheduleWritePackageListLocked(userId);
22096            applyFactoryDefaultBrowserLPw(userId);
22097            primeDomainVerificationsLPw(userId);
22098        }
22099    }
22100
22101    void onNewUserCreated(final int userId) {
22102        synchronized(mPackages) {
22103            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22104            // If permission review for legacy apps is required, we represent
22105            // dagerous permissions for such apps as always granted runtime
22106            // permissions to keep per user flag state whether review is needed.
22107            // Hence, if a new user is added we have to propagate dangerous
22108            // permission grants for these legacy apps.
22109            if (mSettings.mPermissions.mPermissionReviewRequired) {
22110// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22111                mPermissionManager.updateAllPermissions(
22112                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22113                        mPermissionCallback);
22114            }
22115        }
22116    }
22117
22118    @Override
22119    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22120        mContext.enforceCallingOrSelfPermission(
22121                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22122                "Only package verification agents can read the verifier device identity");
22123
22124        synchronized (mPackages) {
22125            return mSettings.getVerifierDeviceIdentityLPw();
22126        }
22127    }
22128
22129    @Override
22130    public void setPermissionEnforced(String permission, boolean enforced) {
22131        // TODO: Now that we no longer change GID for storage, this should to away.
22132        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22133                "setPermissionEnforced");
22134        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22135            synchronized (mPackages) {
22136                if (mSettings.mReadExternalStorageEnforced == null
22137                        || mSettings.mReadExternalStorageEnforced != enforced) {
22138                    mSettings.mReadExternalStorageEnforced =
22139                            enforced ? Boolean.TRUE : Boolean.FALSE;
22140                    mSettings.writeLPr();
22141                }
22142            }
22143            // kill any non-foreground processes so we restart them and
22144            // grant/revoke the GID.
22145            final IActivityManager am = ActivityManager.getService();
22146            if (am != null) {
22147                final long token = Binder.clearCallingIdentity();
22148                try {
22149                    am.killProcessesBelowForeground("setPermissionEnforcement");
22150                } catch (RemoteException e) {
22151                } finally {
22152                    Binder.restoreCallingIdentity(token);
22153                }
22154            }
22155        } else {
22156            throw new IllegalArgumentException("No selective enforcement for " + permission);
22157        }
22158    }
22159
22160    @Override
22161    @Deprecated
22162    public boolean isPermissionEnforced(String permission) {
22163        // allow instant applications
22164        return true;
22165    }
22166
22167    @Override
22168    public boolean isStorageLow() {
22169        // allow instant applications
22170        final long token = Binder.clearCallingIdentity();
22171        try {
22172            final DeviceStorageMonitorInternal
22173                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22174            if (dsm != null) {
22175                return dsm.isMemoryLow();
22176            } else {
22177                return false;
22178            }
22179        } finally {
22180            Binder.restoreCallingIdentity(token);
22181        }
22182    }
22183
22184    @Override
22185    public IPackageInstaller getPackageInstaller() {
22186        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22187            return null;
22188        }
22189        return mInstallerService;
22190    }
22191
22192    private boolean userNeedsBadging(int userId) {
22193        int index = mUserNeedsBadging.indexOfKey(userId);
22194        if (index < 0) {
22195            final UserInfo userInfo;
22196            final long token = Binder.clearCallingIdentity();
22197            try {
22198                userInfo = sUserManager.getUserInfo(userId);
22199            } finally {
22200                Binder.restoreCallingIdentity(token);
22201            }
22202            final boolean b;
22203            if (userInfo != null && userInfo.isManagedProfile()) {
22204                b = true;
22205            } else {
22206                b = false;
22207            }
22208            mUserNeedsBadging.put(userId, b);
22209            return b;
22210        }
22211        return mUserNeedsBadging.valueAt(index);
22212    }
22213
22214    @Override
22215    public KeySet getKeySetByAlias(String packageName, String alias) {
22216        if (packageName == null || alias == null) {
22217            return null;
22218        }
22219        synchronized(mPackages) {
22220            final PackageParser.Package pkg = mPackages.get(packageName);
22221            if (pkg == null) {
22222                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22223                throw new IllegalArgumentException("Unknown package: " + packageName);
22224            }
22225            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22226            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22227                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22228                throw new IllegalArgumentException("Unknown package: " + packageName);
22229            }
22230            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22231            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22232        }
22233    }
22234
22235    @Override
22236    public KeySet getSigningKeySet(String packageName) {
22237        if (packageName == null) {
22238            return null;
22239        }
22240        synchronized(mPackages) {
22241            final int callingUid = Binder.getCallingUid();
22242            final int callingUserId = UserHandle.getUserId(callingUid);
22243            final PackageParser.Package pkg = mPackages.get(packageName);
22244            if (pkg == null) {
22245                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22246                throw new IllegalArgumentException("Unknown package: " + packageName);
22247            }
22248            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22249            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22250                // filter and pretend the package doesn't exist
22251                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22252                        + ", uid:" + callingUid);
22253                throw new IllegalArgumentException("Unknown package: " + packageName);
22254            }
22255            if (pkg.applicationInfo.uid != callingUid
22256                    && Process.SYSTEM_UID != callingUid) {
22257                throw new SecurityException("May not access signing KeySet of other apps.");
22258            }
22259            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22260            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22261        }
22262    }
22263
22264    @Override
22265    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22266        final int callingUid = Binder.getCallingUid();
22267        if (getInstantAppPackageName(callingUid) != null) {
22268            return false;
22269        }
22270        if (packageName == null || ks == null) {
22271            return false;
22272        }
22273        synchronized(mPackages) {
22274            final PackageParser.Package pkg = mPackages.get(packageName);
22275            if (pkg == null
22276                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22277                            UserHandle.getUserId(callingUid))) {
22278                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22279                throw new IllegalArgumentException("Unknown package: " + packageName);
22280            }
22281            IBinder ksh = ks.getToken();
22282            if (ksh instanceof KeySetHandle) {
22283                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22284                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22285            }
22286            return false;
22287        }
22288    }
22289
22290    @Override
22291    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22292        final int callingUid = Binder.getCallingUid();
22293        if (getInstantAppPackageName(callingUid) != null) {
22294            return false;
22295        }
22296        if (packageName == null || ks == null) {
22297            return false;
22298        }
22299        synchronized(mPackages) {
22300            final PackageParser.Package pkg = mPackages.get(packageName);
22301            if (pkg == null
22302                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22303                            UserHandle.getUserId(callingUid))) {
22304                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22305                throw new IllegalArgumentException("Unknown package: " + packageName);
22306            }
22307            IBinder ksh = ks.getToken();
22308            if (ksh instanceof KeySetHandle) {
22309                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22310                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22311            }
22312            return false;
22313        }
22314    }
22315
22316    private void deletePackageIfUnusedLPr(final String packageName) {
22317        PackageSetting ps = mSettings.mPackages.get(packageName);
22318        if (ps == null) {
22319            return;
22320        }
22321        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22322            // TODO Implement atomic delete if package is unused
22323            // It is currently possible that the package will be deleted even if it is installed
22324            // after this method returns.
22325            mHandler.post(new Runnable() {
22326                public void run() {
22327                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22328                            0, PackageManager.DELETE_ALL_USERS);
22329                }
22330            });
22331        }
22332    }
22333
22334    /**
22335     * Check and throw if the given before/after packages would be considered a
22336     * downgrade.
22337     */
22338    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22339            throws PackageManagerException {
22340        if (after.versionCode < before.mVersionCode) {
22341            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22342                    "Update version code " + after.versionCode + " is older than current "
22343                    + before.mVersionCode);
22344        } else if (after.versionCode == before.mVersionCode) {
22345            if (after.baseRevisionCode < before.baseRevisionCode) {
22346                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22347                        "Update base revision code " + after.baseRevisionCode
22348                        + " is older than current " + before.baseRevisionCode);
22349            }
22350
22351            if (!ArrayUtils.isEmpty(after.splitNames)) {
22352                for (int i = 0; i < after.splitNames.length; i++) {
22353                    final String splitName = after.splitNames[i];
22354                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22355                    if (j != -1) {
22356                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22357                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22358                                    "Update split " + splitName + " revision code "
22359                                    + after.splitRevisionCodes[i] + " is older than current "
22360                                    + before.splitRevisionCodes[j]);
22361                        }
22362                    }
22363                }
22364            }
22365        }
22366    }
22367
22368    private static class MoveCallbacks extends Handler {
22369        private static final int MSG_CREATED = 1;
22370        private static final int MSG_STATUS_CHANGED = 2;
22371
22372        private final RemoteCallbackList<IPackageMoveObserver>
22373                mCallbacks = new RemoteCallbackList<>();
22374
22375        private final SparseIntArray mLastStatus = new SparseIntArray();
22376
22377        public MoveCallbacks(Looper looper) {
22378            super(looper);
22379        }
22380
22381        public void register(IPackageMoveObserver callback) {
22382            mCallbacks.register(callback);
22383        }
22384
22385        public void unregister(IPackageMoveObserver callback) {
22386            mCallbacks.unregister(callback);
22387        }
22388
22389        @Override
22390        public void handleMessage(Message msg) {
22391            final SomeArgs args = (SomeArgs) msg.obj;
22392            final int n = mCallbacks.beginBroadcast();
22393            for (int i = 0; i < n; i++) {
22394                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22395                try {
22396                    invokeCallback(callback, msg.what, args);
22397                } catch (RemoteException ignored) {
22398                }
22399            }
22400            mCallbacks.finishBroadcast();
22401            args.recycle();
22402        }
22403
22404        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22405                throws RemoteException {
22406            switch (what) {
22407                case MSG_CREATED: {
22408                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22409                    break;
22410                }
22411                case MSG_STATUS_CHANGED: {
22412                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22413                    break;
22414                }
22415            }
22416        }
22417
22418        private void notifyCreated(int moveId, Bundle extras) {
22419            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22420
22421            final SomeArgs args = SomeArgs.obtain();
22422            args.argi1 = moveId;
22423            args.arg2 = extras;
22424            obtainMessage(MSG_CREATED, args).sendToTarget();
22425        }
22426
22427        private void notifyStatusChanged(int moveId, int status) {
22428            notifyStatusChanged(moveId, status, -1);
22429        }
22430
22431        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22432            Slog.v(TAG, "Move " + moveId + " status " + status);
22433
22434            final SomeArgs args = SomeArgs.obtain();
22435            args.argi1 = moveId;
22436            args.argi2 = status;
22437            args.arg3 = estMillis;
22438            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22439
22440            synchronized (mLastStatus) {
22441                mLastStatus.put(moveId, status);
22442            }
22443        }
22444    }
22445
22446    private final static class OnPermissionChangeListeners extends Handler {
22447        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22448
22449        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22450                new RemoteCallbackList<>();
22451
22452        public OnPermissionChangeListeners(Looper looper) {
22453            super(looper);
22454        }
22455
22456        @Override
22457        public void handleMessage(Message msg) {
22458            switch (msg.what) {
22459                case MSG_ON_PERMISSIONS_CHANGED: {
22460                    final int uid = msg.arg1;
22461                    handleOnPermissionsChanged(uid);
22462                } break;
22463            }
22464        }
22465
22466        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22467            mPermissionListeners.register(listener);
22468
22469        }
22470
22471        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22472            mPermissionListeners.unregister(listener);
22473        }
22474
22475        public void onPermissionsChanged(int uid) {
22476            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22477                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22478            }
22479        }
22480
22481        private void handleOnPermissionsChanged(int uid) {
22482            final int count = mPermissionListeners.beginBroadcast();
22483            try {
22484                for (int i = 0; i < count; i++) {
22485                    IOnPermissionsChangeListener callback = mPermissionListeners
22486                            .getBroadcastItem(i);
22487                    try {
22488                        callback.onPermissionsChanged(uid);
22489                    } catch (RemoteException e) {
22490                        Log.e(TAG, "Permission listener is dead", e);
22491                    }
22492                }
22493            } finally {
22494                mPermissionListeners.finishBroadcast();
22495            }
22496        }
22497    }
22498
22499    private class PackageManagerNative extends IPackageManagerNative.Stub {
22500        @Override
22501        public String[] getNamesForUids(int[] uids) throws RemoteException {
22502            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22503            // massage results so they can be parsed by the native binder
22504            for (int i = results.length - 1; i >= 0; --i) {
22505                if (results[i] == null) {
22506                    results[i] = "";
22507                }
22508            }
22509            return results;
22510        }
22511
22512        // NB: this differentiates between preloads and sideloads
22513        @Override
22514        public String getInstallerForPackage(String packageName) throws RemoteException {
22515            final String installerName = getInstallerPackageName(packageName);
22516            if (!TextUtils.isEmpty(installerName)) {
22517                return installerName;
22518            }
22519            // differentiate between preload and sideload
22520            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22521            ApplicationInfo appInfo = getApplicationInfo(packageName,
22522                                    /*flags*/ 0,
22523                                    /*userId*/ callingUser);
22524            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22525                return "preload";
22526            }
22527            return "";
22528        }
22529
22530        @Override
22531        public int getVersionCodeForPackage(String packageName) throws RemoteException {
22532            try {
22533                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22534                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22535                if (pInfo != null) {
22536                    return pInfo.versionCode;
22537                }
22538            } catch (Exception e) {
22539            }
22540            return 0;
22541        }
22542    }
22543
22544    private class PackageManagerInternalImpl extends PackageManagerInternal {
22545        @Override
22546        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22547                int flagValues, int userId) {
22548            PackageManagerService.this.updatePermissionFlags(
22549                    permName, packageName, flagMask, flagValues, userId);
22550        }
22551
22552        @Override
22553        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22554            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22555        }
22556
22557        @Override
22558        public boolean isInstantApp(String packageName, int userId) {
22559            return PackageManagerService.this.isInstantApp(packageName, userId);
22560        }
22561
22562        @Override
22563        public String getInstantAppPackageName(int uid) {
22564            return PackageManagerService.this.getInstantAppPackageName(uid);
22565        }
22566
22567        @Override
22568        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22569            synchronized (mPackages) {
22570                return PackageManagerService.this.filterAppAccessLPr(
22571                        (PackageSetting) pkg.mExtras, callingUid, userId);
22572            }
22573        }
22574
22575        @Override
22576        public PackageParser.Package getPackage(String packageName) {
22577            synchronized (mPackages) {
22578                packageName = resolveInternalPackageNameLPr(
22579                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22580                return mPackages.get(packageName);
22581            }
22582        }
22583
22584        @Override
22585        public PackageParser.Package getDisabledPackage(String packageName) {
22586            synchronized (mPackages) {
22587                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22588                return (ps != null) ? ps.pkg : null;
22589            }
22590        }
22591
22592        @Override
22593        public String getKnownPackageName(int knownPackage, int userId) {
22594            switch(knownPackage) {
22595                case PackageManagerInternal.PACKAGE_BROWSER:
22596                    return getDefaultBrowserPackageName(userId);
22597                case PackageManagerInternal.PACKAGE_INSTALLER:
22598                    return mRequiredInstallerPackage;
22599                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22600                    return mSetupWizardPackage;
22601                case PackageManagerInternal.PACKAGE_SYSTEM:
22602                    return "android";
22603                case PackageManagerInternal.PACKAGE_VERIFIER:
22604                    return mRequiredVerifierPackage;
22605            }
22606            return null;
22607        }
22608
22609        @Override
22610        public boolean isResolveActivityComponent(ComponentInfo component) {
22611            return mResolveActivity.packageName.equals(component.packageName)
22612                    && mResolveActivity.name.equals(component.name);
22613        }
22614
22615        @Override
22616        public void setLocationPackagesProvider(PackagesProvider provider) {
22617            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22618        }
22619
22620        @Override
22621        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22622            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22623        }
22624
22625        @Override
22626        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22627            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22628        }
22629
22630        @Override
22631        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22632            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22633        }
22634
22635        @Override
22636        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22637            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22638        }
22639
22640        @Override
22641        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22642            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22643        }
22644
22645        @Override
22646        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22647            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22648        }
22649
22650        @Override
22651        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22652            synchronized (mPackages) {
22653                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22654            }
22655            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22656        }
22657
22658        @Override
22659        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22660            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22661                    packageName, userId);
22662        }
22663
22664        @Override
22665        public void setKeepUninstalledPackages(final List<String> packageList) {
22666            Preconditions.checkNotNull(packageList);
22667            List<String> removedFromList = null;
22668            synchronized (mPackages) {
22669                if (mKeepUninstalledPackages != null) {
22670                    final int packagesCount = mKeepUninstalledPackages.size();
22671                    for (int i = 0; i < packagesCount; i++) {
22672                        String oldPackage = mKeepUninstalledPackages.get(i);
22673                        if (packageList != null && packageList.contains(oldPackage)) {
22674                            continue;
22675                        }
22676                        if (removedFromList == null) {
22677                            removedFromList = new ArrayList<>();
22678                        }
22679                        removedFromList.add(oldPackage);
22680                    }
22681                }
22682                mKeepUninstalledPackages = new ArrayList<>(packageList);
22683                if (removedFromList != null) {
22684                    final int removedCount = removedFromList.size();
22685                    for (int i = 0; i < removedCount; i++) {
22686                        deletePackageIfUnusedLPr(removedFromList.get(i));
22687                    }
22688                }
22689            }
22690        }
22691
22692        @Override
22693        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22694            synchronized (mPackages) {
22695                return mPermissionManager.isPermissionsReviewRequired(
22696                        mPackages.get(packageName), userId);
22697            }
22698        }
22699
22700        @Override
22701        public PackageInfo getPackageInfo(
22702                String packageName, int flags, int filterCallingUid, int userId) {
22703            return PackageManagerService.this
22704                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
22705                            flags, filterCallingUid, userId);
22706        }
22707
22708        @Override
22709        public int getPackageUid(String packageName, int flags, int userId) {
22710            return PackageManagerService.this
22711                    .getPackageUid(packageName, flags, userId);
22712        }
22713
22714        @Override
22715        public ApplicationInfo getApplicationInfo(
22716                String packageName, int flags, int filterCallingUid, int userId) {
22717            return PackageManagerService.this
22718                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
22719        }
22720
22721        @Override
22722        public ActivityInfo getActivityInfo(
22723                ComponentName component, int flags, int filterCallingUid, int userId) {
22724            return PackageManagerService.this
22725                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
22726        }
22727
22728        @Override
22729        public List<ResolveInfo> queryIntentActivities(
22730                Intent intent, int flags, int filterCallingUid, int userId) {
22731            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22732            return PackageManagerService.this
22733                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
22734                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
22735        }
22736
22737        @Override
22738        public List<ResolveInfo> queryIntentServices(
22739                Intent intent, int flags, int callingUid, int userId) {
22740            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22741            return PackageManagerService.this
22742                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
22743                            false);
22744        }
22745
22746        @Override
22747        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22748                int userId) {
22749            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22750        }
22751
22752        @Override
22753        public void setDeviceAndProfileOwnerPackages(
22754                int deviceOwnerUserId, String deviceOwnerPackage,
22755                SparseArray<String> profileOwnerPackages) {
22756            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22757                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22758        }
22759
22760        @Override
22761        public boolean isPackageDataProtected(int userId, String packageName) {
22762            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22763        }
22764
22765        @Override
22766        public boolean isPackageEphemeral(int userId, String packageName) {
22767            synchronized (mPackages) {
22768                final PackageSetting ps = mSettings.mPackages.get(packageName);
22769                return ps != null ? ps.getInstantApp(userId) : false;
22770            }
22771        }
22772
22773        @Override
22774        public boolean wasPackageEverLaunched(String packageName, int userId) {
22775            synchronized (mPackages) {
22776                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22777            }
22778        }
22779
22780        @Override
22781        public void grantRuntimePermission(String packageName, String permName, int userId,
22782                boolean overridePolicy) {
22783            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
22784                    permName, packageName, overridePolicy, getCallingUid(), userId,
22785                    mPermissionCallback);
22786        }
22787
22788        @Override
22789        public void revokeRuntimePermission(String packageName, String permName, int userId,
22790                boolean overridePolicy) {
22791            mPermissionManager.revokeRuntimePermission(
22792                    permName, packageName, overridePolicy, getCallingUid(), userId,
22793                    mPermissionCallback);
22794        }
22795
22796        @Override
22797        public String getNameForUid(int uid) {
22798            return PackageManagerService.this.getNameForUid(uid);
22799        }
22800
22801        @Override
22802        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22803                Intent origIntent, String resolvedType, String callingPackage,
22804                Bundle verificationBundle, int userId) {
22805            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22806                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
22807                    userId);
22808        }
22809
22810        @Override
22811        public void grantEphemeralAccess(int userId, Intent intent,
22812                int targetAppId, int ephemeralAppId) {
22813            synchronized (mPackages) {
22814                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22815                        targetAppId, ephemeralAppId);
22816            }
22817        }
22818
22819        @Override
22820        public boolean isInstantAppInstallerComponent(ComponentName component) {
22821            synchronized (mPackages) {
22822                return mInstantAppInstallerActivity != null
22823                        && mInstantAppInstallerActivity.getComponentName().equals(component);
22824            }
22825        }
22826
22827        @Override
22828        public void pruneInstantApps() {
22829            mInstantAppRegistry.pruneInstantApps();
22830        }
22831
22832        @Override
22833        public String getSetupWizardPackageName() {
22834            return mSetupWizardPackage;
22835        }
22836
22837        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22838            if (policy != null) {
22839                mExternalSourcesPolicy = policy;
22840            }
22841        }
22842
22843        @Override
22844        public boolean isPackagePersistent(String packageName) {
22845            synchronized (mPackages) {
22846                PackageParser.Package pkg = mPackages.get(packageName);
22847                return pkg != null
22848                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22849                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22850                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22851                        : false;
22852            }
22853        }
22854
22855        @Override
22856        public boolean isLegacySystemApp(Package pkg) {
22857            synchronized (mPackages) {
22858                final PackageSetting ps = (PackageSetting) pkg.mExtras;
22859                return mPromoteSystemApps
22860                        && ps.isSystem()
22861                        && mExistingSystemPackages.contains(ps.name);
22862            }
22863        }
22864
22865        @Override
22866        public List<PackageInfo> getOverlayPackages(int userId) {
22867            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22868            synchronized (mPackages) {
22869                for (PackageParser.Package p : mPackages.values()) {
22870                    if (p.mOverlayTarget != null) {
22871                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22872                        if (pkg != null) {
22873                            overlayPackages.add(pkg);
22874                        }
22875                    }
22876                }
22877            }
22878            return overlayPackages;
22879        }
22880
22881        @Override
22882        public List<String> getTargetPackageNames(int userId) {
22883            List<String> targetPackages = new ArrayList<>();
22884            synchronized (mPackages) {
22885                for (PackageParser.Package p : mPackages.values()) {
22886                    if (p.mOverlayTarget == null) {
22887                        targetPackages.add(p.packageName);
22888                    }
22889                }
22890            }
22891            return targetPackages;
22892        }
22893
22894        @Override
22895        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
22896                @Nullable List<String> overlayPackageNames) {
22897            synchronized (mPackages) {
22898                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
22899                    Slog.e(TAG, "failed to find package " + targetPackageName);
22900                    return false;
22901                }
22902                ArrayList<String> overlayPaths = null;
22903                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
22904                    final int N = overlayPackageNames.size();
22905                    overlayPaths = new ArrayList<>(N);
22906                    for (int i = 0; i < N; i++) {
22907                        final String packageName = overlayPackageNames.get(i);
22908                        final PackageParser.Package pkg = mPackages.get(packageName);
22909                        if (pkg == null) {
22910                            Slog.e(TAG, "failed to find package " + packageName);
22911                            return false;
22912                        }
22913                        overlayPaths.add(pkg.baseCodePath);
22914                    }
22915                }
22916
22917                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
22918                ps.setOverlayPaths(overlayPaths, userId);
22919                return true;
22920            }
22921        }
22922
22923        @Override
22924        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
22925                int flags, int userId, boolean resolveForStart) {
22926            return resolveIntentInternal(
22927                    intent, resolvedType, flags, userId, resolveForStart);
22928        }
22929
22930        @Override
22931        public ResolveInfo resolveService(Intent intent, String resolvedType,
22932                int flags, int userId, int callingUid) {
22933            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
22934        }
22935
22936        @Override
22937        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
22938            return PackageManagerService.this.resolveContentProviderInternal(
22939                    name, flags, userId);
22940        }
22941
22942        @Override
22943        public void addIsolatedUid(int isolatedUid, int ownerUid) {
22944            synchronized (mPackages) {
22945                mIsolatedOwners.put(isolatedUid, ownerUid);
22946            }
22947        }
22948
22949        @Override
22950        public void removeIsolatedUid(int isolatedUid) {
22951            synchronized (mPackages) {
22952                mIsolatedOwners.delete(isolatedUid);
22953            }
22954        }
22955
22956        @Override
22957        public int getUidTargetSdkVersion(int uid) {
22958            synchronized (mPackages) {
22959                return getUidTargetSdkVersionLockedLPr(uid);
22960            }
22961        }
22962
22963        @Override
22964        public boolean canAccessInstantApps(int callingUid, int userId) {
22965            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
22966        }
22967
22968        @Override
22969        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
22970            synchronized (mPackages) {
22971                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
22972            }
22973        }
22974
22975        @Override
22976        public void notifyPackageUse(String packageName, int reason) {
22977            synchronized (mPackages) {
22978                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
22979            }
22980        }
22981    }
22982
22983    @Override
22984    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22985        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22986        synchronized (mPackages) {
22987            final long identity = Binder.clearCallingIdentity();
22988            try {
22989                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
22990                        packageNames, userId);
22991            } finally {
22992                Binder.restoreCallingIdentity(identity);
22993            }
22994        }
22995    }
22996
22997    @Override
22998    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22999        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23000        synchronized (mPackages) {
23001            final long identity = Binder.clearCallingIdentity();
23002            try {
23003                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23004                        packageNames, userId);
23005            } finally {
23006                Binder.restoreCallingIdentity(identity);
23007            }
23008        }
23009    }
23010
23011    private static void enforceSystemOrPhoneCaller(String tag) {
23012        int callingUid = Binder.getCallingUid();
23013        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23014            throw new SecurityException(
23015                    "Cannot call " + tag + " from UID " + callingUid);
23016        }
23017    }
23018
23019    boolean isHistoricalPackageUsageAvailable() {
23020        return mPackageUsage.isHistoricalPackageUsageAvailable();
23021    }
23022
23023    /**
23024     * Return a <b>copy</b> of the collection of packages known to the package manager.
23025     * @return A copy of the values of mPackages.
23026     */
23027    Collection<PackageParser.Package> getPackages() {
23028        synchronized (mPackages) {
23029            return new ArrayList<>(mPackages.values());
23030        }
23031    }
23032
23033    /**
23034     * Logs process start information (including base APK hash) to the security log.
23035     * @hide
23036     */
23037    @Override
23038    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23039            String apkFile, int pid) {
23040        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23041            return;
23042        }
23043        if (!SecurityLog.isLoggingEnabled()) {
23044            return;
23045        }
23046        Bundle data = new Bundle();
23047        data.putLong("startTimestamp", System.currentTimeMillis());
23048        data.putString("processName", processName);
23049        data.putInt("uid", uid);
23050        data.putString("seinfo", seinfo);
23051        data.putString("apkFile", apkFile);
23052        data.putInt("pid", pid);
23053        Message msg = mProcessLoggingHandler.obtainMessage(
23054                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23055        msg.setData(data);
23056        mProcessLoggingHandler.sendMessage(msg);
23057    }
23058
23059    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23060        return mCompilerStats.getPackageStats(pkgName);
23061    }
23062
23063    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23064        return getOrCreateCompilerPackageStats(pkg.packageName);
23065    }
23066
23067    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23068        return mCompilerStats.getOrCreatePackageStats(pkgName);
23069    }
23070
23071    public void deleteCompilerPackageStats(String pkgName) {
23072        mCompilerStats.deletePackageStats(pkgName);
23073    }
23074
23075    @Override
23076    public int getInstallReason(String packageName, int userId) {
23077        final int callingUid = Binder.getCallingUid();
23078        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23079                true /* requireFullPermission */, false /* checkShell */,
23080                "get install reason");
23081        synchronized (mPackages) {
23082            final PackageSetting ps = mSettings.mPackages.get(packageName);
23083            if (filterAppAccessLPr(ps, callingUid, userId)) {
23084                return PackageManager.INSTALL_REASON_UNKNOWN;
23085            }
23086            if (ps != null) {
23087                return ps.getInstallReason(userId);
23088            }
23089        }
23090        return PackageManager.INSTALL_REASON_UNKNOWN;
23091    }
23092
23093    @Override
23094    public boolean canRequestPackageInstalls(String packageName, int userId) {
23095        return canRequestPackageInstallsInternal(packageName, 0, userId,
23096                true /* throwIfPermNotDeclared*/);
23097    }
23098
23099    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23100            boolean throwIfPermNotDeclared) {
23101        int callingUid = Binder.getCallingUid();
23102        int uid = getPackageUid(packageName, 0, userId);
23103        if (callingUid != uid && callingUid != Process.ROOT_UID
23104                && callingUid != Process.SYSTEM_UID) {
23105            throw new SecurityException(
23106                    "Caller uid " + callingUid + " does not own package " + packageName);
23107        }
23108        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23109        if (info == null) {
23110            return false;
23111        }
23112        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23113            return false;
23114        }
23115        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23116        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23117        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23118            if (throwIfPermNotDeclared) {
23119                throw new SecurityException("Need to declare " + appOpPermission
23120                        + " to call this api");
23121            } else {
23122                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23123                return false;
23124            }
23125        }
23126        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23127            return false;
23128        }
23129        if (mExternalSourcesPolicy != null) {
23130            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23131            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23132                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23133            }
23134        }
23135        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23136    }
23137
23138    @Override
23139    public ComponentName getInstantAppResolverSettingsComponent() {
23140        return mInstantAppResolverSettingsComponent;
23141    }
23142
23143    @Override
23144    public ComponentName getInstantAppInstallerComponent() {
23145        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23146            return null;
23147        }
23148        return mInstantAppInstallerActivity == null
23149                ? null : mInstantAppInstallerActivity.getComponentName();
23150    }
23151
23152    @Override
23153    public String getInstantAppAndroidId(String packageName, int userId) {
23154        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23155                "getInstantAppAndroidId");
23156        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23157                true /* requireFullPermission */, false /* checkShell */,
23158                "getInstantAppAndroidId");
23159        // Make sure the target is an Instant App.
23160        if (!isInstantApp(packageName, userId)) {
23161            return null;
23162        }
23163        synchronized (mPackages) {
23164            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23165        }
23166    }
23167
23168    boolean canHaveOatDir(String packageName) {
23169        synchronized (mPackages) {
23170            PackageParser.Package p = mPackages.get(packageName);
23171            if (p == null) {
23172                return false;
23173            }
23174            return p.canHaveOatDir();
23175        }
23176    }
23177
23178    private String getOatDir(PackageParser.Package pkg) {
23179        if (!pkg.canHaveOatDir()) {
23180            return null;
23181        }
23182        File codePath = new File(pkg.codePath);
23183        if (codePath.isDirectory()) {
23184            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23185        }
23186        return null;
23187    }
23188
23189    void deleteOatArtifactsOfPackage(String packageName) {
23190        final String[] instructionSets;
23191        final List<String> codePaths;
23192        final String oatDir;
23193        final PackageParser.Package pkg;
23194        synchronized (mPackages) {
23195            pkg = mPackages.get(packageName);
23196        }
23197        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23198        codePaths = pkg.getAllCodePaths();
23199        oatDir = getOatDir(pkg);
23200
23201        for (String codePath : codePaths) {
23202            for (String isa : instructionSets) {
23203                try {
23204                    mInstaller.deleteOdex(codePath, isa, oatDir);
23205                } catch (InstallerException e) {
23206                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23207                }
23208            }
23209        }
23210    }
23211
23212    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23213        Set<String> unusedPackages = new HashSet<>();
23214        long currentTimeInMillis = System.currentTimeMillis();
23215        synchronized (mPackages) {
23216            for (PackageParser.Package pkg : mPackages.values()) {
23217                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23218                if (ps == null) {
23219                    continue;
23220                }
23221                PackageDexUsage.PackageUseInfo packageUseInfo =
23222                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23223                if (PackageManagerServiceUtils
23224                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23225                                downgradeTimeThresholdMillis, packageUseInfo,
23226                                pkg.getLatestPackageUseTimeInMills(),
23227                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23228                    unusedPackages.add(pkg.packageName);
23229                }
23230            }
23231        }
23232        return unusedPackages;
23233    }
23234}
23235
23236interface PackageSender {
23237    void sendPackageBroadcast(final String action, final String pkg,
23238        final Bundle extras, final int flags, final String targetPkg,
23239        final IIntentReceiver finishedReceiver, final int[] userIds);
23240    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23241        boolean includeStopped, int appId, int... userIds);
23242}
23243