PackageManagerService.java revision 12633114d97c425c4d974efa075ab20ee11f1345
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.PARSE_IS_OEM;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
106import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
107import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
108import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
109import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
111import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
112import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
117import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
118
119import android.Manifest;
120import android.annotation.IntDef;
121import android.annotation.NonNull;
122import android.annotation.Nullable;
123import android.app.ActivityManager;
124import android.app.AppOpsManager;
125import android.app.IActivityManager;
126import android.app.ResourcesManager;
127import android.app.admin.IDevicePolicyManager;
128import android.app.admin.SecurityLog;
129import android.app.backup.IBackupManager;
130import android.content.BroadcastReceiver;
131import android.content.ComponentName;
132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.IIntentReceiver;
135import android.content.Intent;
136import android.content.IntentFilter;
137import android.content.IntentSender;
138import android.content.IntentSender.SendIntentException;
139import android.content.ServiceConnection;
140import android.content.pm.ActivityInfo;
141import android.content.pm.ApplicationInfo;
142import android.content.pm.AppsQueryHelper;
143import android.content.pm.AuxiliaryResolveInfo;
144import android.content.pm.ChangedPackages;
145import android.content.pm.ComponentInfo;
146import android.content.pm.FallbackCategoryProvider;
147import android.content.pm.FeatureInfo;
148import android.content.pm.IDexModuleRegisterCallback;
149import android.content.pm.IOnPermissionsChangeListener;
150import android.content.pm.IPackageDataObserver;
151import android.content.pm.IPackageDeleteObserver;
152import android.content.pm.IPackageDeleteObserver2;
153import android.content.pm.IPackageInstallObserver2;
154import android.content.pm.IPackageInstaller;
155import android.content.pm.IPackageManager;
156import android.content.pm.IPackageManagerNative;
157import android.content.pm.IPackageMoveObserver;
158import android.content.pm.IPackageStatsObserver;
159import android.content.pm.InstantAppInfo;
160import android.content.pm.InstantAppRequest;
161import android.content.pm.InstantAppResolveInfo;
162import android.content.pm.InstrumentationInfo;
163import android.content.pm.IntentFilterVerificationInfo;
164import android.content.pm.KeySet;
165import android.content.pm.PackageCleanItem;
166import android.content.pm.PackageInfo;
167import android.content.pm.PackageInfoLite;
168import android.content.pm.PackageInstaller;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManagerInternal;
171import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageStats;
178import android.content.pm.PackageUserState;
179import android.content.pm.ParceledListSlice;
180import android.content.pm.PermissionGroupInfo;
181import android.content.pm.PermissionInfo;
182import android.content.pm.ProviderInfo;
183import android.content.pm.ResolveInfo;
184import android.content.pm.ServiceInfo;
185import android.content.pm.SharedLibraryInfo;
186import android.content.pm.Signature;
187import android.content.pm.UserInfo;
188import android.content.pm.VerifierDeviceIdentity;
189import android.content.pm.VerifierInfo;
190import android.content.pm.VersionedPackage;
191import android.content.res.Resources;
192import android.database.ContentObserver;
193import android.graphics.Bitmap;
194import android.hardware.display.DisplayManager;
195import android.net.Uri;
196import android.os.Binder;
197import android.os.Build;
198import android.os.Bundle;
199import android.os.Debug;
200import android.os.Environment;
201import android.os.Environment.UserEnvironment;
202import android.os.FileUtils;
203import android.os.Handler;
204import android.os.IBinder;
205import android.os.Looper;
206import android.os.Message;
207import android.os.Parcel;
208import android.os.ParcelFileDescriptor;
209import android.os.PatternMatcher;
210import android.os.Process;
211import android.os.RemoteCallbackList;
212import android.os.RemoteException;
213import android.os.ResultReceiver;
214import android.os.SELinux;
215import android.os.ServiceManager;
216import android.os.ShellCallback;
217import android.os.SystemClock;
218import android.os.SystemProperties;
219import android.os.Trace;
220import android.os.UserHandle;
221import android.os.UserManager;
222import android.os.UserManagerInternal;
223import android.os.storage.IStorageManager;
224import android.os.storage.StorageEventListener;
225import android.os.storage.StorageManager;
226import android.os.storage.StorageManagerInternal;
227import android.os.storage.VolumeInfo;
228import android.os.storage.VolumeRecord;
229import android.provider.Settings.Global;
230import android.provider.Settings.Secure;
231import android.security.KeyStore;
232import android.security.SystemKeyStore;
233import android.service.pm.PackageServiceDumpProto;
234import android.system.ErrnoException;
235import android.system.Os;
236import android.text.TextUtils;
237import android.text.format.DateUtils;
238import android.util.ArrayMap;
239import android.util.ArraySet;
240import android.util.Base64;
241import android.util.DisplayMetrics;
242import android.util.EventLog;
243import android.util.ExceptionUtils;
244import android.util.Log;
245import android.util.LogPrinter;
246import android.util.MathUtils;
247import android.util.PackageUtils;
248import android.util.Pair;
249import android.util.PrintStreamPrinter;
250import android.util.Slog;
251import android.util.SparseArray;
252import android.util.SparseBooleanArray;
253import android.util.SparseIntArray;
254import android.util.TimingsTraceLog;
255import android.util.Xml;
256import android.util.jar.StrictJarFile;
257import android.util.proto.ProtoOutputStream;
258import android.view.Display;
259
260import com.android.internal.R;
261import com.android.internal.annotations.GuardedBy;
262import com.android.internal.app.IMediaContainerService;
263import com.android.internal.app.ResolverActivity;
264import com.android.internal.content.NativeLibraryHelper;
265import com.android.internal.content.PackageHelper;
266import com.android.internal.logging.MetricsLogger;
267import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
268import com.android.internal.os.IParcelFileDescriptorFactory;
269import com.android.internal.os.RoSystemProperties;
270import com.android.internal.os.SomeArgs;
271import com.android.internal.os.Zygote;
272import com.android.internal.telephony.CarrierAppUtils;
273import com.android.internal.util.ArrayUtils;
274import com.android.internal.util.ConcurrentUtils;
275import com.android.internal.util.DumpUtils;
276import com.android.internal.util.FastPrintWriter;
277import com.android.internal.util.FastXmlSerializer;
278import com.android.internal.util.IndentingPrintWriter;
279import com.android.internal.util.Preconditions;
280import com.android.internal.util.XmlUtils;
281import com.android.server.AttributeCache;
282import com.android.server.DeviceIdleController;
283import com.android.server.EventLogTags;
284import com.android.server.FgThread;
285import com.android.server.IntentResolver;
286import com.android.server.LocalServices;
287import com.android.server.LockGuard;
288import com.android.server.ServiceThread;
289import com.android.server.SystemConfig;
290import com.android.server.SystemServerInitThreadPool;
291import com.android.server.Watchdog;
292import com.android.server.net.NetworkPolicyManagerInternal;
293import com.android.server.pm.Installer.InstallerException;
294import com.android.server.pm.Settings.DatabaseVersion;
295import com.android.server.pm.Settings.VersionInfo;
296import com.android.server.pm.dex.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<<1;
451    static final int SCAN_FORCE_DEX = 1<<2;
452    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
453    static final int SCAN_NEW_INSTALL = 1<<4;
454    static final int SCAN_UPDATE_TIME = 1<<5;
455    static final int SCAN_BOOTING = 1<<6;
456    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
457    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
458    static final int SCAN_REPLACING = 1<<9;
459    static final int SCAN_REQUIRE_KNOWN = 1<<10;
460    static final int SCAN_MOVE = 1<<11;
461    static final int SCAN_INITIAL = 1<<12;
462    static final int SCAN_CHECK_ONLY = 1<<13;
463    static final int SCAN_DONT_KILL_APP = 1<<14;
464    static final int SCAN_IGNORE_FROZEN = 1<<15;
465    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
466    static final int SCAN_AS_INSTANT_APP = 1<<17;
467    static final int SCAN_AS_FULL_APP = 1<<18;
468    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
469    /** Should not be with the scan flags */
470    static final int FLAGS_REMOVE_CHATTY = 1<<31;
471
472    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
473    /** Extension of the compressed packages */
474    public final static String COMPRESSED_EXTENSION = ".gz";
475    /** Suffix of stub packages on the system partition */
476    public final static String STUB_SUFFIX = "-Stub";
477
478    private static final int[] EMPTY_INT_ARRAY = new int[0];
479
480    private static final int TYPE_UNKNOWN = 0;
481    private static final int TYPE_ACTIVITY = 1;
482    private static final int TYPE_RECEIVER = 2;
483    private static final int TYPE_SERVICE = 3;
484    private static final int TYPE_PROVIDER = 4;
485    @IntDef(prefix = { "TYPE_" }, value = {
486            TYPE_UNKNOWN,
487            TYPE_ACTIVITY,
488            TYPE_RECEIVER,
489            TYPE_SERVICE,
490            TYPE_PROVIDER,
491    })
492    @Retention(RetentionPolicy.SOURCE)
493    public @interface ComponentType {}
494
495    /**
496     * Timeout (in milliseconds) after which the watchdog should declare that
497     * our handler thread is wedged.  The usual default for such things is one
498     * minute but we sometimes do very lengthy I/O operations on this thread,
499     * such as installing multi-gigabyte applications, so ours needs to be longer.
500     */
501    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
502
503    /**
504     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
505     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
506     * settings entry if available, otherwise we use the hardcoded default.  If it's been
507     * more than this long since the last fstrim, we force one during the boot sequence.
508     *
509     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
510     * one gets run at the next available charging+idle time.  This final mandatory
511     * no-fstrim check kicks in only of the other scheduling criteria is never met.
512     */
513    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
514
515    /**
516     * Whether verification is enabled by default.
517     */
518    private static final boolean DEFAULT_VERIFY_ENABLE = true;
519
520    /**
521     * The default maximum time to wait for the verification agent to return in
522     * milliseconds.
523     */
524    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
525
526    /**
527     * The default response for package verification timeout.
528     *
529     * This can be either PackageManager.VERIFICATION_ALLOW or
530     * PackageManager.VERIFICATION_REJECT.
531     */
532    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
533
534    public static final String PLATFORM_PACKAGE_NAME = "android";
535
536    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
537
538    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
539            DEFAULT_CONTAINER_PACKAGE,
540            "com.android.defcontainer.DefaultContainerService");
541
542    private static final String KILL_APP_REASON_GIDS_CHANGED =
543            "permission grant or revoke changed gids";
544
545    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
546            "permissions revoked";
547
548    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
549
550    private static final String PACKAGE_SCHEME = "package";
551
552    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
553
554    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
555
556    /** Canonical intent used to identify what counts as a "web browser" app */
557    private static final Intent sBrowserIntent;
558    static {
559        sBrowserIntent = new Intent();
560        sBrowserIntent.setAction(Intent.ACTION_VIEW);
561        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
562        sBrowserIntent.setData(Uri.parse("http:"));
563    }
564
565    /**
566     * The set of all protected actions [i.e. those actions for which a high priority
567     * intent filter is disallowed].
568     */
569    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
570    static {
571        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
572        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
574        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
575    }
576
577    // Compilation reasons.
578    public static final int REASON_FIRST_BOOT = 0;
579    public static final int REASON_BOOT = 1;
580    public static final int REASON_INSTALL = 2;
581    public static final int REASON_BACKGROUND_DEXOPT = 3;
582    public static final int REASON_AB_OTA = 4;
583    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
584    public static final int REASON_SHARED = 6;
585
586    public static final int REASON_LAST = REASON_SHARED;
587
588    /**
589     * Version number for the package parser cache. Increment this whenever the format or
590     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
591     */
592    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
593
594    /**
595     * Whether the package parser cache is enabled.
596     */
597    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
598
599    final ServiceThread mHandlerThread;
600
601    final PackageHandler mHandler;
602
603    private final ProcessLoggingHandler mProcessLoggingHandler;
604
605    /**
606     * Messages for {@link #mHandler} that need to wait for system ready before
607     * being dispatched.
608     */
609    private ArrayList<Message> mPostSystemReadyMessages;
610
611    final int mSdkVersion = Build.VERSION.SDK_INT;
612
613    final Context mContext;
614    final boolean mFactoryTest;
615    final boolean mOnlyCore;
616    final DisplayMetrics mMetrics;
617    final int mDefParseFlags;
618    final String[] mSeparateProcesses;
619    final boolean mIsUpgrade;
620    final boolean mIsPreNUpgrade;
621    final boolean mIsPreNMR1Upgrade;
622
623    // Have we told the Activity Manager to whitelist the default container service by uid yet?
624    @GuardedBy("mPackages")
625    boolean mDefaultContainerWhitelisted = false;
626
627    @GuardedBy("mPackages")
628    private boolean mDexOptDialogShown;
629
630    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
631    // LOCK HELD.  Can be called with mInstallLock held.
632    @GuardedBy("mInstallLock")
633    final Installer mInstaller;
634
635    /** Directory where installed third-party apps stored */
636    final File mAppInstallDir;
637
638    /**
639     * Directory to which applications installed internally have their
640     * 32 bit native libraries copied.
641     */
642    private File mAppLib32InstallDir;
643
644    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
645    // apps.
646    final File mDrmAppPrivateInstallDir;
647
648    // ----------------------------------------------------------------
649
650    // Lock for state used when installing and doing other long running
651    // operations.  Methods that must be called with this lock held have
652    // the suffix "LI".
653    final Object mInstallLock = new Object();
654
655    // ----------------------------------------------------------------
656
657    // Keys are String (package name), values are Package.  This also serves
658    // as the lock for the global state.  Methods that must be called with
659    // this lock held have the prefix "LP".
660    @GuardedBy("mPackages")
661    final ArrayMap<String, PackageParser.Package> mPackages =
662            new ArrayMap<String, PackageParser.Package>();
663
664    final ArrayMap<String, Set<String>> mKnownCodebase =
665            new ArrayMap<String, Set<String>>();
666
667    // Keys are isolated uids and values are the uid of the application
668    // that created the isolated proccess.
669    @GuardedBy("mPackages")
670    final SparseIntArray mIsolatedOwners = new SparseIntArray();
671
672    /**
673     * Tracks new system packages [received in an OTA] that we expect to
674     * find updated user-installed versions. Keys are package name, values
675     * are package location.
676     */
677    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
678    /**
679     * Tracks high priority intent filters for protected actions. During boot, certain
680     * filter actions are protected and should never be allowed to have a high priority
681     * intent filter for them. However, there is one, and only one exception -- the
682     * setup wizard. It must be able to define a high priority intent filter for these
683     * actions to ensure there are no escapes from the wizard. We need to delay processing
684     * of these during boot as we need to look at all of the system packages in order
685     * to know which component is the setup wizard.
686     */
687    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
688    /**
689     * Whether or not processing protected filters should be deferred.
690     */
691    private boolean mDeferProtectedFilters = true;
692
693    /**
694     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
695     */
696    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
697    /**
698     * Whether or not system app permissions should be promoted from install to runtime.
699     */
700    boolean mPromoteSystemApps;
701
702    @GuardedBy("mPackages")
703    final Settings mSettings;
704
705    /**
706     * Set of package names that are currently "frozen", which means active
707     * surgery is being done on the code/data for that package. The platform
708     * will refuse to launch frozen packages to avoid race conditions.
709     *
710     * @see PackageFreezer
711     */
712    @GuardedBy("mPackages")
713    final ArraySet<String> mFrozenPackages = new ArraySet<>();
714
715    final ProtectedPackages mProtectedPackages;
716
717    @GuardedBy("mLoadedVolumes")
718    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
719
720    boolean mFirstBoot;
721
722    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
723
724    @GuardedBy("mAvailableFeatures")
725    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
726
727    // If mac_permissions.xml was found for seinfo labeling.
728    boolean mFoundPolicyFile;
729
730    private final InstantAppRegistry mInstantAppRegistry;
731
732    @GuardedBy("mPackages")
733    int mChangedPackagesSequenceNumber;
734    /**
735     * List of changed [installed, removed or updated] packages.
736     * mapping from user id -> sequence number -> package name
737     */
738    @GuardedBy("mPackages")
739    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
740    /**
741     * The sequence number of the last change to a package.
742     * mapping from user id -> package name -> sequence number
743     */
744    @GuardedBy("mPackages")
745    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
746
747    class PackageParserCallback implements PackageParser.Callback {
748        @Override public final boolean hasFeature(String feature) {
749            return PackageManagerService.this.hasSystemFeature(feature, 0);
750        }
751
752        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
753                Collection<PackageParser.Package> allPackages, String targetPackageName) {
754            List<PackageParser.Package> overlayPackages = null;
755            for (PackageParser.Package p : allPackages) {
756                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
757                    if (overlayPackages == null) {
758                        overlayPackages = new ArrayList<PackageParser.Package>();
759                    }
760                    overlayPackages.add(p);
761                }
762            }
763            if (overlayPackages != null) {
764                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
765                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
766                        return p1.mOverlayPriority - p2.mOverlayPriority;
767                    }
768                };
769                Collections.sort(overlayPackages, cmp);
770            }
771            return overlayPackages;
772        }
773
774        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
775                String targetPackageName, String targetPath) {
776            if ("android".equals(targetPackageName)) {
777                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
778                // native AssetManager.
779                return null;
780            }
781            List<PackageParser.Package> overlayPackages =
782                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
783            if (overlayPackages == null || overlayPackages.isEmpty()) {
784                return null;
785            }
786            List<String> overlayPathList = null;
787            for (PackageParser.Package overlayPackage : overlayPackages) {
788                if (targetPath == null) {
789                    if (overlayPathList == null) {
790                        overlayPathList = new ArrayList<String>();
791                    }
792                    overlayPathList.add(overlayPackage.baseCodePath);
793                    continue;
794                }
795
796                try {
797                    // Creates idmaps for system to parse correctly the Android manifest of the
798                    // target package.
799                    //
800                    // OverlayManagerService will update each of them with a correct gid from its
801                    // target package app id.
802                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
803                            UserHandle.getSharedAppGid(
804                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
805                    if (overlayPathList == null) {
806                        overlayPathList = new ArrayList<String>();
807                    }
808                    overlayPathList.add(overlayPackage.baseCodePath);
809                } catch (InstallerException e) {
810                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
811                            overlayPackage.baseCodePath);
812                }
813            }
814            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
815        }
816
817        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
818            synchronized (mPackages) {
819                return getStaticOverlayPathsLocked(
820                        mPackages.values(), targetPackageName, targetPath);
821            }
822        }
823
824        @Override public final String[] getOverlayApks(String targetPackageName) {
825            return getStaticOverlayPaths(targetPackageName, null);
826        }
827
828        @Override public final String[] getOverlayPaths(String targetPackageName,
829                String targetPath) {
830            return getStaticOverlayPaths(targetPackageName, targetPath);
831        }
832    }
833
834    class ParallelPackageParserCallback extends PackageParserCallback {
835        List<PackageParser.Package> mOverlayPackages = null;
836
837        void findStaticOverlayPackages() {
838            synchronized (mPackages) {
839                for (PackageParser.Package p : mPackages.values()) {
840                    if (p.mIsStaticOverlay) {
841                        if (mOverlayPackages == null) {
842                            mOverlayPackages = new ArrayList<PackageParser.Package>();
843                        }
844                        mOverlayPackages.add(p);
845                    }
846                }
847            }
848        }
849
850        @Override
851        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
852            // We can trust mOverlayPackages without holding mPackages because package uninstall
853            // can't happen while running parallel parsing.
854            // Moreover holding mPackages on each parsing thread causes dead-lock.
855            return mOverlayPackages == null ? null :
856                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
857        }
858    }
859
860    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
861    final ParallelPackageParserCallback mParallelPackageParserCallback =
862            new ParallelPackageParserCallback();
863
864    public static final class SharedLibraryEntry {
865        public final @Nullable String path;
866        public final @Nullable String apk;
867        public final @NonNull SharedLibraryInfo info;
868
869        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
870                String declaringPackageName, int declaringPackageVersionCode) {
871            path = _path;
872            apk = _apk;
873            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
874                    declaringPackageName, declaringPackageVersionCode), null);
875        }
876    }
877
878    // Currently known shared libraries.
879    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
880    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
881            new ArrayMap<>();
882
883    // All available activities, for your resolving pleasure.
884    final ActivityIntentResolver mActivities =
885            new ActivityIntentResolver();
886
887    // All available receivers, for your resolving pleasure.
888    final ActivityIntentResolver mReceivers =
889            new ActivityIntentResolver();
890
891    // All available services, for your resolving pleasure.
892    final ServiceIntentResolver mServices = new ServiceIntentResolver();
893
894    // All available providers, for your resolving pleasure.
895    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
896
897    // Mapping from provider base names (first directory in content URI codePath)
898    // to the provider information.
899    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
900            new ArrayMap<String, PackageParser.Provider>();
901
902    // Mapping from instrumentation class names to info about them.
903    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
904            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
905
906    // Packages whose data we have transfered into another package, thus
907    // should no longer exist.
908    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
909
910    // Broadcast actions that are only available to the system.
911    @GuardedBy("mProtectedBroadcasts")
912    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
913
914    /** List of packages waiting for verification. */
915    final SparseArray<PackageVerificationState> mPendingVerification
916            = new SparseArray<PackageVerificationState>();
917
918    final PackageInstallerService mInstallerService;
919
920    private final PackageDexOptimizer mPackageDexOptimizer;
921    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
922    // is used by other apps).
923    private final DexManager mDexManager;
924
925    private AtomicInteger mNextMoveId = new AtomicInteger();
926    private final MoveCallbacks mMoveCallbacks;
927
928    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
929
930    // Cache of users who need badging.
931    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
932
933    /** Token for keys in mPendingVerification. */
934    private int mPendingVerificationToken = 0;
935
936    volatile boolean mSystemReady;
937    volatile boolean mSafeMode;
938    volatile boolean mHasSystemUidErrors;
939    private volatile boolean mEphemeralAppsDisabled;
940
941    ApplicationInfo mAndroidApplication;
942    final ActivityInfo mResolveActivity = new ActivityInfo();
943    final ResolveInfo mResolveInfo = new ResolveInfo();
944    ComponentName mResolveComponentName;
945    PackageParser.Package mPlatformPackage;
946    ComponentName mCustomResolverComponentName;
947
948    boolean mResolverReplaced = false;
949
950    private final @Nullable ComponentName mIntentFilterVerifierComponent;
951    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
952
953    private int mIntentFilterVerificationToken = 0;
954
955    /** The service connection to the ephemeral resolver */
956    final EphemeralResolverConnection mInstantAppResolverConnection;
957    /** Component used to show resolver settings for Instant Apps */
958    final ComponentName mInstantAppResolverSettingsComponent;
959
960    /** Activity used to install instant applications */
961    ActivityInfo mInstantAppInstallerActivity;
962    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
963
964    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
965            = new SparseArray<IntentFilterVerificationState>();
966
967    // TODO remove this and go through mPermissonManager directly
968    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
969    private final PermissionManagerInternal mPermissionManager;
970
971    // List of packages names to keep cached, even if they are uninstalled for all users
972    private List<String> mKeepUninstalledPackages;
973
974    private UserManagerInternal mUserManagerInternal;
975
976    private DeviceIdleController.LocalService mDeviceIdleController;
977
978    private File mCacheDir;
979
980    private Future<?> mPrepareAppDataFuture;
981
982    private static class IFVerificationParams {
983        PackageParser.Package pkg;
984        boolean replacing;
985        int userId;
986        int verifierUid;
987
988        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
989                int _userId, int _verifierUid) {
990            pkg = _pkg;
991            replacing = _replacing;
992            userId = _userId;
993            replacing = _replacing;
994            verifierUid = _verifierUid;
995        }
996    }
997
998    private interface IntentFilterVerifier<T extends IntentFilter> {
999        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1000                                               T filter, String packageName);
1001        void startVerifications(int userId);
1002        void receiveVerificationResponse(int verificationId);
1003    }
1004
1005    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1006        private Context mContext;
1007        private ComponentName mIntentFilterVerifierComponent;
1008        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1009
1010        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1011            mContext = context;
1012            mIntentFilterVerifierComponent = verifierComponent;
1013        }
1014
1015        private String getDefaultScheme() {
1016            return IntentFilter.SCHEME_HTTPS;
1017        }
1018
1019        @Override
1020        public void startVerifications(int userId) {
1021            // Launch verifications requests
1022            int count = mCurrentIntentFilterVerifications.size();
1023            for (int n=0; n<count; n++) {
1024                int verificationId = mCurrentIntentFilterVerifications.get(n);
1025                final IntentFilterVerificationState ivs =
1026                        mIntentFilterVerificationStates.get(verificationId);
1027
1028                String packageName = ivs.getPackageName();
1029
1030                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1031                final int filterCount = filters.size();
1032                ArraySet<String> domainsSet = new ArraySet<>();
1033                for (int m=0; m<filterCount; m++) {
1034                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1035                    domainsSet.addAll(filter.getHostsList());
1036                }
1037                synchronized (mPackages) {
1038                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1039                            packageName, domainsSet) != null) {
1040                        scheduleWriteSettingsLocked();
1041                    }
1042                }
1043                sendVerificationRequest(verificationId, ivs);
1044            }
1045            mCurrentIntentFilterVerifications.clear();
1046        }
1047
1048        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1049            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1050            verificationIntent.putExtra(
1051                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1052                    verificationId);
1053            verificationIntent.putExtra(
1054                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1055                    getDefaultScheme());
1056            verificationIntent.putExtra(
1057                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1058                    ivs.getHostsString());
1059            verificationIntent.putExtra(
1060                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1061                    ivs.getPackageName());
1062            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1063            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1064
1065            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1066            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1067                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1068                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1069
1070            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1071            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1072                    "Sending IntentFilter verification broadcast");
1073        }
1074
1075        public void receiveVerificationResponse(int verificationId) {
1076            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1077
1078            final boolean verified = ivs.isVerified();
1079
1080            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1081            final int count = filters.size();
1082            if (DEBUG_DOMAIN_VERIFICATION) {
1083                Slog.i(TAG, "Received verification response " + verificationId
1084                        + " for " + count + " filters, verified=" + verified);
1085            }
1086            for (int n=0; n<count; n++) {
1087                PackageParser.ActivityIntentInfo filter = filters.get(n);
1088                filter.setVerified(verified);
1089
1090                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1091                        + " verified with result:" + verified + " and hosts:"
1092                        + ivs.getHostsString());
1093            }
1094
1095            mIntentFilterVerificationStates.remove(verificationId);
1096
1097            final String packageName = ivs.getPackageName();
1098            IntentFilterVerificationInfo ivi = null;
1099
1100            synchronized (mPackages) {
1101                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1102            }
1103            if (ivi == null) {
1104                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1105                        + verificationId + " packageName:" + packageName);
1106                return;
1107            }
1108            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1109                    "Updating IntentFilterVerificationInfo for package " + packageName
1110                            +" verificationId:" + verificationId);
1111
1112            synchronized (mPackages) {
1113                if (verified) {
1114                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1115                } else {
1116                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1117                }
1118                scheduleWriteSettingsLocked();
1119
1120                final int userId = ivs.getUserId();
1121                if (userId != UserHandle.USER_ALL) {
1122                    final int userStatus =
1123                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1124
1125                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1126                    boolean needUpdate = false;
1127
1128                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1129                    // already been set by the User thru the Disambiguation dialog
1130                    switch (userStatus) {
1131                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1132                            if (verified) {
1133                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1134                            } else {
1135                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1136                            }
1137                            needUpdate = true;
1138                            break;
1139
1140                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1141                            if (verified) {
1142                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1143                                needUpdate = true;
1144                            }
1145                            break;
1146
1147                        default:
1148                            // Nothing to do
1149                    }
1150
1151                    if (needUpdate) {
1152                        mSettings.updateIntentFilterVerificationStatusLPw(
1153                                packageName, updatedStatus, userId);
1154                        scheduleWritePackageRestrictionsLocked(userId);
1155                    }
1156                }
1157            }
1158        }
1159
1160        @Override
1161        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1162                    ActivityIntentInfo filter, String packageName) {
1163            if (!hasValidDomains(filter)) {
1164                return false;
1165            }
1166            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1167            if (ivs == null) {
1168                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1169                        packageName);
1170            }
1171            if (DEBUG_DOMAIN_VERIFICATION) {
1172                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1173            }
1174            ivs.addFilter(filter);
1175            return true;
1176        }
1177
1178        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1179                int userId, int verificationId, String packageName) {
1180            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1181                    verifierUid, userId, packageName);
1182            ivs.setPendingState();
1183            synchronized (mPackages) {
1184                mIntentFilterVerificationStates.append(verificationId, ivs);
1185                mCurrentIntentFilterVerifications.add(verificationId);
1186            }
1187            return ivs;
1188        }
1189    }
1190
1191    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1192        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1193                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1194                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1195    }
1196
1197    // Set of pending broadcasts for aggregating enable/disable of components.
1198    static class PendingPackageBroadcasts {
1199        // for each user id, a map of <package name -> components within that package>
1200        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1201
1202        public PendingPackageBroadcasts() {
1203            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1204        }
1205
1206        public ArrayList<String> get(int userId, String packageName) {
1207            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1208            return packages.get(packageName);
1209        }
1210
1211        public void put(int userId, String packageName, ArrayList<String> components) {
1212            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1213            packages.put(packageName, components);
1214        }
1215
1216        public void remove(int userId, String packageName) {
1217            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1218            if (packages != null) {
1219                packages.remove(packageName);
1220            }
1221        }
1222
1223        public void remove(int userId) {
1224            mUidMap.remove(userId);
1225        }
1226
1227        public int userIdCount() {
1228            return mUidMap.size();
1229        }
1230
1231        public int userIdAt(int n) {
1232            return mUidMap.keyAt(n);
1233        }
1234
1235        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1236            return mUidMap.get(userId);
1237        }
1238
1239        public int size() {
1240            // total number of pending broadcast entries across all userIds
1241            int num = 0;
1242            for (int i = 0; i< mUidMap.size(); i++) {
1243                num += mUidMap.valueAt(i).size();
1244            }
1245            return num;
1246        }
1247
1248        public void clear() {
1249            mUidMap.clear();
1250        }
1251
1252        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1253            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1254            if (map == null) {
1255                map = new ArrayMap<String, ArrayList<String>>();
1256                mUidMap.put(userId, map);
1257            }
1258            return map;
1259        }
1260    }
1261    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1262
1263    // Service Connection to remote media container service to copy
1264    // package uri's from external media onto secure containers
1265    // or internal storage.
1266    private IMediaContainerService mContainerService = null;
1267
1268    static final int SEND_PENDING_BROADCAST = 1;
1269    static final int MCS_BOUND = 3;
1270    static final int END_COPY = 4;
1271    static final int INIT_COPY = 5;
1272    static final int MCS_UNBIND = 6;
1273    static final int START_CLEANING_PACKAGE = 7;
1274    static final int FIND_INSTALL_LOC = 8;
1275    static final int POST_INSTALL = 9;
1276    static final int MCS_RECONNECT = 10;
1277    static final int MCS_GIVE_UP = 11;
1278    static final int WRITE_SETTINGS = 13;
1279    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1280    static final int PACKAGE_VERIFIED = 15;
1281    static final int CHECK_PENDING_VERIFICATION = 16;
1282    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1283    static final int INTENT_FILTER_VERIFIED = 18;
1284    static final int WRITE_PACKAGE_LIST = 19;
1285    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1286
1287    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1288
1289    // Delay time in millisecs
1290    static final int BROADCAST_DELAY = 10 * 1000;
1291
1292    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1293            2 * 60 * 60 * 1000L; /* two hours */
1294
1295    static UserManagerService sUserManager;
1296
1297    // Stores a list of users whose package restrictions file needs to be updated
1298    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1299
1300    final private DefaultContainerConnection mDefContainerConn =
1301            new DefaultContainerConnection();
1302    class DefaultContainerConnection implements ServiceConnection {
1303        public void onServiceConnected(ComponentName name, IBinder service) {
1304            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1305            final IMediaContainerService imcs = IMediaContainerService.Stub
1306                    .asInterface(Binder.allowBlocking(service));
1307            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1308        }
1309
1310        public void onServiceDisconnected(ComponentName name) {
1311            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1312        }
1313    }
1314
1315    // Recordkeeping of restore-after-install operations that are currently in flight
1316    // between the Package Manager and the Backup Manager
1317    static class PostInstallData {
1318        public InstallArgs args;
1319        public PackageInstalledInfo res;
1320
1321        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1322            args = _a;
1323            res = _r;
1324        }
1325    }
1326
1327    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1328    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1329
1330    // XML tags for backup/restore of various bits of state
1331    private static final String TAG_PREFERRED_BACKUP = "pa";
1332    private static final String TAG_DEFAULT_APPS = "da";
1333    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1334
1335    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1336    private static final String TAG_ALL_GRANTS = "rt-grants";
1337    private static final String TAG_GRANT = "grant";
1338    private static final String ATTR_PACKAGE_NAME = "pkg";
1339
1340    private static final String TAG_PERMISSION = "perm";
1341    private static final String ATTR_PERMISSION_NAME = "name";
1342    private static final String ATTR_IS_GRANTED = "g";
1343    private static final String ATTR_USER_SET = "set";
1344    private static final String ATTR_USER_FIXED = "fixed";
1345    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1346
1347    // System/policy permission grants are not backed up
1348    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1349            FLAG_PERMISSION_POLICY_FIXED
1350            | FLAG_PERMISSION_SYSTEM_FIXED
1351            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1352
1353    // And we back up these user-adjusted states
1354    private static final int USER_RUNTIME_GRANT_MASK =
1355            FLAG_PERMISSION_USER_SET
1356            | FLAG_PERMISSION_USER_FIXED
1357            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1358
1359    final @Nullable String mRequiredVerifierPackage;
1360    final @NonNull String mRequiredInstallerPackage;
1361    final @NonNull String mRequiredUninstallerPackage;
1362    final @Nullable String mSetupWizardPackage;
1363    final @Nullable String mStorageManagerPackage;
1364    final @NonNull String mServicesSystemSharedLibraryPackageName;
1365    final @NonNull String mSharedSystemSharedLibraryPackageName;
1366
1367    private final PackageUsage mPackageUsage = new PackageUsage();
1368    private final CompilerStats mCompilerStats = new CompilerStats();
1369
1370    class PackageHandler extends Handler {
1371        private boolean mBound = false;
1372        final ArrayList<HandlerParams> mPendingInstalls =
1373            new ArrayList<HandlerParams>();
1374
1375        private boolean connectToService() {
1376            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1377                    " DefaultContainerService");
1378            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1379            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1380            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1381                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1382                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1383                mBound = true;
1384                return true;
1385            }
1386            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387            return false;
1388        }
1389
1390        private void disconnectService() {
1391            mContainerService = null;
1392            mBound = false;
1393            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394            mContext.unbindService(mDefContainerConn);
1395            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1396        }
1397
1398        PackageHandler(Looper looper) {
1399            super(looper);
1400        }
1401
1402        public void handleMessage(Message msg) {
1403            try {
1404                doHandleMessage(msg);
1405            } finally {
1406                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1407            }
1408        }
1409
1410        void doHandleMessage(Message msg) {
1411            switch (msg.what) {
1412                case INIT_COPY: {
1413                    HandlerParams params = (HandlerParams) msg.obj;
1414                    int idx = mPendingInstalls.size();
1415                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1416                    // If a bind was already initiated we dont really
1417                    // need to do anything. The pending install
1418                    // will be processed later on.
1419                    if (!mBound) {
1420                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1421                                System.identityHashCode(mHandler));
1422                        // If this is the only one pending we might
1423                        // have to bind to the service again.
1424                        if (!connectToService()) {
1425                            Slog.e(TAG, "Failed to bind to media container service");
1426                            params.serviceError();
1427                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1428                                    System.identityHashCode(mHandler));
1429                            if (params.traceMethod != null) {
1430                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1431                                        params.traceCookie);
1432                            }
1433                            return;
1434                        } else {
1435                            // Once we bind to the service, the first
1436                            // pending request will be processed.
1437                            mPendingInstalls.add(idx, params);
1438                        }
1439                    } else {
1440                        mPendingInstalls.add(idx, params);
1441                        // Already bound to the service. Just make
1442                        // sure we trigger off processing the first request.
1443                        if (idx == 0) {
1444                            mHandler.sendEmptyMessage(MCS_BOUND);
1445                        }
1446                    }
1447                    break;
1448                }
1449                case MCS_BOUND: {
1450                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1451                    if (msg.obj != null) {
1452                        mContainerService = (IMediaContainerService) msg.obj;
1453                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                System.identityHashCode(mHandler));
1455                    }
1456                    if (mContainerService == null) {
1457                        if (!mBound) {
1458                            // Something seriously wrong since we are not bound and we are not
1459                            // waiting for connection. Bail out.
1460                            Slog.e(TAG, "Cannot bind to media container service");
1461                            for (HandlerParams params : mPendingInstalls) {
1462                                // Indicate service bind error
1463                                params.serviceError();
1464                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1465                                        System.identityHashCode(params));
1466                                if (params.traceMethod != null) {
1467                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1468                                            params.traceMethod, params.traceCookie);
1469                                }
1470                                return;
1471                            }
1472                            mPendingInstalls.clear();
1473                        } else {
1474                            Slog.w(TAG, "Waiting to connect to media container service");
1475                        }
1476                    } else if (mPendingInstalls.size() > 0) {
1477                        HandlerParams params = mPendingInstalls.get(0);
1478                        if (params != null) {
1479                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1480                                    System.identityHashCode(params));
1481                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1482                            if (params.startCopy()) {
1483                                // We are done...  look for more work or to
1484                                // go idle.
1485                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1486                                        "Checking for more work or unbind...");
1487                                // Delete pending install
1488                                if (mPendingInstalls.size() > 0) {
1489                                    mPendingInstalls.remove(0);
1490                                }
1491                                if (mPendingInstalls.size() == 0) {
1492                                    if (mBound) {
1493                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1494                                                "Posting delayed MCS_UNBIND");
1495                                        removeMessages(MCS_UNBIND);
1496                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1497                                        // Unbind after a little delay, to avoid
1498                                        // continual thrashing.
1499                                        sendMessageDelayed(ubmsg, 10000);
1500                                    }
1501                                } else {
1502                                    // There are more pending requests in queue.
1503                                    // Just post MCS_BOUND message to trigger processing
1504                                    // of next pending install.
1505                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1506                                            "Posting MCS_BOUND for next work");
1507                                    mHandler.sendEmptyMessage(MCS_BOUND);
1508                                }
1509                            }
1510                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1511                        }
1512                    } else {
1513                        // Should never happen ideally.
1514                        Slog.w(TAG, "Empty queue");
1515                    }
1516                    break;
1517                }
1518                case MCS_RECONNECT: {
1519                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1520                    if (mPendingInstalls.size() > 0) {
1521                        if (mBound) {
1522                            disconnectService();
1523                        }
1524                        if (!connectToService()) {
1525                            Slog.e(TAG, "Failed to bind to media container service");
1526                            for (HandlerParams params : mPendingInstalls) {
1527                                // Indicate service bind error
1528                                params.serviceError();
1529                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1530                                        System.identityHashCode(params));
1531                            }
1532                            mPendingInstalls.clear();
1533                        }
1534                    }
1535                    break;
1536                }
1537                case MCS_UNBIND: {
1538                    // If there is no actual work left, then time to unbind.
1539                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1540
1541                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1542                        if (mBound) {
1543                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1544
1545                            disconnectService();
1546                        }
1547                    } else if (mPendingInstalls.size() > 0) {
1548                        // There are more pending requests in queue.
1549                        // Just post MCS_BOUND message to trigger processing
1550                        // of next pending install.
1551                        mHandler.sendEmptyMessage(MCS_BOUND);
1552                    }
1553
1554                    break;
1555                }
1556                case MCS_GIVE_UP: {
1557                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1558                    HandlerParams params = mPendingInstalls.remove(0);
1559                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1560                            System.identityHashCode(params));
1561                    break;
1562                }
1563                case SEND_PENDING_BROADCAST: {
1564                    String packages[];
1565                    ArrayList<String> components[];
1566                    int size = 0;
1567                    int uids[];
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1569                    synchronized (mPackages) {
1570                        if (mPendingBroadcasts == null) {
1571                            return;
1572                        }
1573                        size = mPendingBroadcasts.size();
1574                        if (size <= 0) {
1575                            // Nothing to be done. Just return
1576                            return;
1577                        }
1578                        packages = new String[size];
1579                        components = new ArrayList[size];
1580                        uids = new int[size];
1581                        int i = 0;  // filling out the above arrays
1582
1583                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1584                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1585                            Iterator<Map.Entry<String, ArrayList<String>>> it
1586                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1587                                            .entrySet().iterator();
1588                            while (it.hasNext() && i < size) {
1589                                Map.Entry<String, ArrayList<String>> ent = it.next();
1590                                packages[i] = ent.getKey();
1591                                components[i] = ent.getValue();
1592                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1593                                uids[i] = (ps != null)
1594                                        ? UserHandle.getUid(packageUserId, ps.appId)
1595                                        : -1;
1596                                i++;
1597                            }
1598                        }
1599                        size = i;
1600                        mPendingBroadcasts.clear();
1601                    }
1602                    // Send broadcasts
1603                    for (int i = 0; i < size; i++) {
1604                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1605                    }
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1607                    break;
1608                }
1609                case START_CLEANING_PACKAGE: {
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    final String packageName = (String)msg.obj;
1612                    final int userId = msg.arg1;
1613                    final boolean andCode = msg.arg2 != 0;
1614                    synchronized (mPackages) {
1615                        if (userId == UserHandle.USER_ALL) {
1616                            int[] users = sUserManager.getUserIds();
1617                            for (int user : users) {
1618                                mSettings.addPackageToCleanLPw(
1619                                        new PackageCleanItem(user, packageName, andCode));
1620                            }
1621                        } else {
1622                            mSettings.addPackageToCleanLPw(
1623                                    new PackageCleanItem(userId, packageName, andCode));
1624                        }
1625                    }
1626                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1627                    startCleaningPackages();
1628                } break;
1629                case POST_INSTALL: {
1630                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1631
1632                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1633                    final boolean didRestore = (msg.arg2 != 0);
1634                    mRunningInstalls.delete(msg.arg1);
1635
1636                    if (data != null) {
1637                        InstallArgs args = data.args;
1638                        PackageInstalledInfo parentRes = data.res;
1639
1640                        final boolean grantPermissions = (args.installFlags
1641                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1642                        final boolean killApp = (args.installFlags
1643                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1644                        final boolean virtualPreload = ((args.installFlags
1645                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1646                        final String[] grantedPermissions = args.installGrantPermissions;
1647
1648                        // Handle the parent package
1649                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1650                                virtualPreload, grantedPermissions, didRestore,
1651                                args.installerPackageName, args.observer);
1652
1653                        // Handle the child packages
1654                        final int childCount = (parentRes.addedChildPackages != null)
1655                                ? parentRes.addedChildPackages.size() : 0;
1656                        for (int i = 0; i < childCount; i++) {
1657                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1658                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1659                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1660                                    args.installerPackageName, args.observer);
1661                        }
1662
1663                        // Log tracing if needed
1664                        if (args.traceMethod != null) {
1665                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1666                                    args.traceCookie);
1667                        }
1668                    } else {
1669                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1670                    }
1671
1672                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1673                } break;
1674                case WRITE_SETTINGS: {
1675                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1676                    synchronized (mPackages) {
1677                        removeMessages(WRITE_SETTINGS);
1678                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1679                        mSettings.writeLPr();
1680                        mDirtyUsers.clear();
1681                    }
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1683                } break;
1684                case WRITE_PACKAGE_RESTRICTIONS: {
1685                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1686                    synchronized (mPackages) {
1687                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1688                        for (int userId : mDirtyUsers) {
1689                            mSettings.writePackageRestrictionsLPr(userId);
1690                        }
1691                        mDirtyUsers.clear();
1692                    }
1693                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1694                } break;
1695                case WRITE_PACKAGE_LIST: {
1696                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1697                    synchronized (mPackages) {
1698                        removeMessages(WRITE_PACKAGE_LIST);
1699                        mSettings.writePackageListLPr(msg.arg1);
1700                    }
1701                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1702                } break;
1703                case CHECK_PENDING_VERIFICATION: {
1704                    final int verificationId = msg.arg1;
1705                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1706
1707                    if ((state != null) && !state.timeoutExtended()) {
1708                        final InstallArgs args = state.getInstallArgs();
1709                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1710
1711                        Slog.i(TAG, "Verification timed out for " + originUri);
1712                        mPendingVerification.remove(verificationId);
1713
1714                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1715
1716                        final UserHandle user = args.getUser();
1717                        if (getDefaultVerificationResponse(user)
1718                                == PackageManager.VERIFICATION_ALLOW) {
1719                            Slog.i(TAG, "Continuing with installation of " + originUri);
1720                            state.setVerifierResponse(Binder.getCallingUid(),
1721                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1722                            broadcastPackageVerified(verificationId, originUri,
1723                                    PackageManager.VERIFICATION_ALLOW, user);
1724                            try {
1725                                ret = args.copyApk(mContainerService, true);
1726                            } catch (RemoteException e) {
1727                                Slog.e(TAG, "Could not contact the ContainerService");
1728                            }
1729                        } else {
1730                            broadcastPackageVerified(verificationId, originUri,
1731                                    PackageManager.VERIFICATION_REJECT, user);
1732                        }
1733
1734                        Trace.asyncTraceEnd(
1735                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1736
1737                        processPendingInstall(args, ret);
1738                        mHandler.sendEmptyMessage(MCS_UNBIND);
1739                    }
1740                    break;
1741                }
1742                case PACKAGE_VERIFIED: {
1743                    final int verificationId = msg.arg1;
1744
1745                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1746                    if (state == null) {
1747                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1748                        break;
1749                    }
1750
1751                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1752
1753                    state.setVerifierResponse(response.callerUid, response.code);
1754
1755                    if (state.isVerificationComplete()) {
1756                        mPendingVerification.remove(verificationId);
1757
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        int ret;
1762                        if (state.isInstallAllowed()) {
1763                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1764                            broadcastPackageVerified(verificationId, originUri,
1765                                    response.code, state.getInstallArgs().getUser());
1766                            try {
1767                                ret = args.copyApk(mContainerService, true);
1768                            } catch (RemoteException e) {
1769                                Slog.e(TAG, "Could not contact the ContainerService");
1770                            }
1771                        } else {
1772                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1773                        }
1774
1775                        Trace.asyncTraceEnd(
1776                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1777
1778                        processPendingInstall(args, ret);
1779                        mHandler.sendEmptyMessage(MCS_UNBIND);
1780                    }
1781
1782                    break;
1783                }
1784                case START_INTENT_FILTER_VERIFICATIONS: {
1785                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1786                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1787                            params.replacing, params.pkg);
1788                    break;
1789                }
1790                case INTENT_FILTER_VERIFIED: {
1791                    final int verificationId = msg.arg1;
1792
1793                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1794                            verificationId);
1795                    if (state == null) {
1796                        Slog.w(TAG, "Invalid IntentFilter verification token "
1797                                + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final int userId = state.getUserId();
1802
1803                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1804                            "Processing IntentFilter verification with token:"
1805                            + verificationId + " and userId:" + userId);
1806
1807                    final IntentFilterVerificationResponse response =
1808                            (IntentFilterVerificationResponse) msg.obj;
1809
1810                    state.setVerifierResponse(response.callerUid, response.code);
1811
1812                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1813                            "IntentFilter verification with token:" + verificationId
1814                            + " and userId:" + userId
1815                            + " is settings verifier response with response code:"
1816                            + response.code);
1817
1818                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1819                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1820                                + response.getFailedDomainsString());
1821                    }
1822
1823                    if (state.isVerificationComplete()) {
1824                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1825                    } else {
1826                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1827                                "IntentFilter verification with token:" + verificationId
1828                                + " was not said to be complete");
1829                    }
1830
1831                    break;
1832                }
1833                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1834                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1835                            mInstantAppResolverConnection,
1836                            (InstantAppRequest) msg.obj,
1837                            mInstantAppInstallerActivity,
1838                            mHandler);
1839                }
1840            }
1841        }
1842    }
1843
1844    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1845        @Override
1846        public void onGidsChanged(int appId, int userId) {
1847            mHandler.post(new Runnable() {
1848                @Override
1849                public void run() {
1850                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1851                }
1852            });
1853        }
1854        @Override
1855        public void onPermissionGranted(int uid, int userId) {
1856            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1857
1858            // Not critical; if this is lost, the application has to request again.
1859            synchronized (mPackages) {
1860                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1861            }
1862        }
1863        @Override
1864        public void onInstallPermissionGranted() {
1865            synchronized (mPackages) {
1866                scheduleWriteSettingsLocked();
1867            }
1868        }
1869        @Override
1870        public void onPermissionRevoked(int uid, int userId) {
1871            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1872
1873            synchronized (mPackages) {
1874                // Critical; after this call the application should never have the permission
1875                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1876            }
1877
1878            final int appId = UserHandle.getAppId(uid);
1879            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1880        }
1881        @Override
1882        public void onInstallPermissionRevoked() {
1883            synchronized (mPackages) {
1884                scheduleWriteSettingsLocked();
1885            }
1886        }
1887        @Override
1888        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1889            synchronized (mPackages) {
1890                for (int userId : updatedUserIds) {
1891                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1892                }
1893            }
1894        }
1895        @Override
1896        public void onInstallPermissionUpdated() {
1897            synchronized (mPackages) {
1898                scheduleWriteSettingsLocked();
1899            }
1900        }
1901        @Override
1902        public void onPermissionRemoved() {
1903            synchronized (mPackages) {
1904                mSettings.writeLPr();
1905            }
1906        }
1907    };
1908
1909    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1910            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1911            boolean launchedForRestore, String installerPackage,
1912            IPackageInstallObserver2 installObserver) {
1913        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1914            // Send the removed broadcasts
1915            if (res.removedInfo != null) {
1916                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1917            }
1918
1919            // Now that we successfully installed the package, grant runtime
1920            // permissions if requested before broadcasting the install. Also
1921            // for legacy apps in permission review mode we clear the permission
1922            // review flag which is used to emulate runtime permissions for
1923            // legacy apps.
1924            if (grantPermissions) {
1925                final int callingUid = Binder.getCallingUid();
1926                mPermissionManager.grantRequestedRuntimePermissions(
1927                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1928                        mPermissionCallback);
1929            }
1930
1931            final boolean update = res.removedInfo != null
1932                    && res.removedInfo.removedPackage != null;
1933            final String installerPackageName =
1934                    res.installerPackageName != null
1935                            ? res.installerPackageName
1936                            : res.removedInfo != null
1937                                    ? res.removedInfo.installerPackageName
1938                                    : null;
1939
1940            // If this is the first time we have child packages for a disabled privileged
1941            // app that had no children, we grant requested runtime permissions to the new
1942            // children if the parent on the system image had them already granted.
1943            if (res.pkg.parentPackage != null) {
1944                final int callingUid = Binder.getCallingUid();
1945                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1946                        res.pkg, callingUid, mPermissionCallback);
1947            }
1948
1949            synchronized (mPackages) {
1950                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1951            }
1952
1953            final String packageName = res.pkg.applicationInfo.packageName;
1954
1955            // Determine the set of users who are adding this package for
1956            // the first time vs. those who are seeing an update.
1957            int[] firstUsers = EMPTY_INT_ARRAY;
1958            int[] updateUsers = EMPTY_INT_ARRAY;
1959            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1960            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1961            for (int newUser : res.newUsers) {
1962                if (ps.getInstantApp(newUser)) {
1963                    continue;
1964                }
1965                if (allNewUsers) {
1966                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1967                    continue;
1968                }
1969                boolean isNew = true;
1970                for (int origUser : res.origUsers) {
1971                    if (origUser == newUser) {
1972                        isNew = false;
1973                        break;
1974                    }
1975                }
1976                if (isNew) {
1977                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1978                } else {
1979                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1980                }
1981            }
1982
1983            // Send installed broadcasts if the package is not a static shared lib.
1984            if (res.pkg.staticSharedLibName == null) {
1985                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1986
1987                // Send added for users that see the package for the first time
1988                // sendPackageAddedForNewUsers also deals with system apps
1989                int appId = UserHandle.getAppId(res.uid);
1990                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1991                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1992                        virtualPreload /*startReceiver*/, appId, firstUsers);
1993
1994                // Send added for users that don't see the package for the first time
1995                Bundle extras = new Bundle(1);
1996                extras.putInt(Intent.EXTRA_UID, res.uid);
1997                if (update) {
1998                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1999                }
2000                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2001                        extras, 0 /*flags*/,
2002                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2003                if (installerPackageName != null) {
2004                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2005                            extras, 0 /*flags*/,
2006                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2007                }
2008
2009                // Send replaced for users that don't see the package for the first time
2010                if (update) {
2011                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2012                            packageName, extras, 0 /*flags*/,
2013                            null /*targetPackage*/, null /*finishedReceiver*/,
2014                            updateUsers);
2015                    if (installerPackageName != null) {
2016                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2017                                extras, 0 /*flags*/,
2018                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2019                    }
2020                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2021                            null /*package*/, null /*extras*/, 0 /*flags*/,
2022                            packageName /*targetPackage*/,
2023                            null /*finishedReceiver*/, updateUsers);
2024                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2025                    // First-install and we did a restore, so we're responsible for the
2026                    // first-launch broadcast.
2027                    if (DEBUG_BACKUP) {
2028                        Slog.i(TAG, "Post-restore of " + packageName
2029                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2030                    }
2031                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2032                }
2033
2034                // Send broadcast package appeared if forward locked/external for all users
2035                // treat asec-hosted packages like removable media on upgrade
2036                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2037                    if (DEBUG_INSTALL) {
2038                        Slog.i(TAG, "upgrading pkg " + res.pkg
2039                                + " is ASEC-hosted -> AVAILABLE");
2040                    }
2041                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2042                    ArrayList<String> pkgList = new ArrayList<>(1);
2043                    pkgList.add(packageName);
2044                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2045                }
2046            }
2047
2048            // Work that needs to happen on first install within each user
2049            if (firstUsers != null && firstUsers.length > 0) {
2050                synchronized (mPackages) {
2051                    for (int userId : firstUsers) {
2052                        // If this app is a browser and it's newly-installed for some
2053                        // users, clear any default-browser state in those users. The
2054                        // app's nature doesn't depend on the user, so we can just check
2055                        // its browser nature in any user and generalize.
2056                        if (packageIsBrowser(packageName, userId)) {
2057                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2058                        }
2059
2060                        // We may also need to apply pending (restored) runtime
2061                        // permission grants within these users.
2062                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2063                    }
2064                }
2065            }
2066
2067            // Log current value of "unknown sources" setting
2068            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2069                    getUnknownSourcesSettings());
2070
2071            // Remove the replaced package's older resources safely now
2072            // We delete after a gc for applications  on sdcard.
2073            if (res.removedInfo != null && res.removedInfo.args != null) {
2074                Runtime.getRuntime().gc();
2075                synchronized (mInstallLock) {
2076                    res.removedInfo.args.doPostDeleteLI(true);
2077                }
2078            } else {
2079                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2080                // and not block here.
2081                VMRuntime.getRuntime().requestConcurrentGC();
2082            }
2083
2084            // Notify DexManager that the package was installed for new users.
2085            // The updated users should already be indexed and the package code paths
2086            // should not change.
2087            // Don't notify the manager for ephemeral apps as they are not expected to
2088            // survive long enough to benefit of background optimizations.
2089            for (int userId : firstUsers) {
2090                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2091                // There's a race currently where some install events may interleave with an uninstall.
2092                // This can lead to package info being null (b/36642664).
2093                if (info != null) {
2094                    mDexManager.notifyPackageInstalled(info, userId);
2095                }
2096            }
2097        }
2098
2099        // If someone is watching installs - notify them
2100        if (installObserver != null) {
2101            try {
2102                Bundle extras = extrasForInstallResult(res);
2103                installObserver.onPackageInstalled(res.name, res.returnCode,
2104                        res.returnMsg, extras);
2105            } catch (RemoteException e) {
2106                Slog.i(TAG, "Observer no longer exists.");
2107            }
2108        }
2109    }
2110
2111    private StorageEventListener mStorageListener = new StorageEventListener() {
2112        @Override
2113        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2114            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2115                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2116                    final String volumeUuid = vol.getFsUuid();
2117
2118                    // Clean up any users or apps that were removed or recreated
2119                    // while this volume was missing
2120                    sUserManager.reconcileUsers(volumeUuid);
2121                    reconcileApps(volumeUuid);
2122
2123                    // Clean up any install sessions that expired or were
2124                    // cancelled while this volume was missing
2125                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2126
2127                    loadPrivatePackages(vol);
2128
2129                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2130                    unloadPrivatePackages(vol);
2131                }
2132            }
2133        }
2134
2135        @Override
2136        public void onVolumeForgotten(String fsUuid) {
2137            if (TextUtils.isEmpty(fsUuid)) {
2138                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2139                return;
2140            }
2141
2142            // Remove any apps installed on the forgotten volume
2143            synchronized (mPackages) {
2144                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2145                for (PackageSetting ps : packages) {
2146                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2147                    deletePackageVersioned(new VersionedPackage(ps.name,
2148                            PackageManager.VERSION_CODE_HIGHEST),
2149                            new LegacyPackageDeleteObserver(null).getBinder(),
2150                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2151                    // Try very hard to release any references to this package
2152                    // so we don't risk the system server being killed due to
2153                    // open FDs
2154                    AttributeCache.instance().removePackage(ps.name);
2155                }
2156
2157                mSettings.onVolumeForgotten(fsUuid);
2158                mSettings.writeLPr();
2159            }
2160        }
2161    };
2162
2163    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2164        Bundle extras = null;
2165        switch (res.returnCode) {
2166            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2167                extras = new Bundle();
2168                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2169                        res.origPermission);
2170                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2171                        res.origPackage);
2172                break;
2173            }
2174            case PackageManager.INSTALL_SUCCEEDED: {
2175                extras = new Bundle();
2176                extras.putBoolean(Intent.EXTRA_REPLACING,
2177                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2178                break;
2179            }
2180        }
2181        return extras;
2182    }
2183
2184    void scheduleWriteSettingsLocked() {
2185        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2186            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2187        }
2188    }
2189
2190    void scheduleWritePackageListLocked(int userId) {
2191        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2192            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2193            msg.arg1 = userId;
2194            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2195        }
2196    }
2197
2198    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2199        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2200        scheduleWritePackageRestrictionsLocked(userId);
2201    }
2202
2203    void scheduleWritePackageRestrictionsLocked(int userId) {
2204        final int[] userIds = (userId == UserHandle.USER_ALL)
2205                ? sUserManager.getUserIds() : new int[]{userId};
2206        for (int nextUserId : userIds) {
2207            if (!sUserManager.exists(nextUserId)) return;
2208            mDirtyUsers.add(nextUserId);
2209            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2210                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2211            }
2212        }
2213    }
2214
2215    public static PackageManagerService main(Context context, Installer installer,
2216            boolean factoryTest, boolean onlyCore) {
2217        // Self-check for initial settings.
2218        PackageManagerServiceCompilerMapping.checkProperties();
2219
2220        PackageManagerService m = new PackageManagerService(context, installer,
2221                factoryTest, onlyCore);
2222        m.enableSystemUserPackages();
2223        ServiceManager.addService("package", m);
2224        final PackageManagerNative pmn = m.new PackageManagerNative();
2225        ServiceManager.addService("package_native", pmn);
2226        return m;
2227    }
2228
2229    private void enableSystemUserPackages() {
2230        if (!UserManager.isSplitSystemUser()) {
2231            return;
2232        }
2233        // For system user, enable apps based on the following conditions:
2234        // - app is whitelisted or belong to one of these groups:
2235        //   -- system app which has no launcher icons
2236        //   -- system app which has INTERACT_ACROSS_USERS permission
2237        //   -- system IME app
2238        // - app is not in the blacklist
2239        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2240        Set<String> enableApps = new ArraySet<>();
2241        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2242                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2243                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2244        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2245        enableApps.addAll(wlApps);
2246        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2247                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2248        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2249        enableApps.removeAll(blApps);
2250        Log.i(TAG, "Applications installed for system user: " + enableApps);
2251        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2252                UserHandle.SYSTEM);
2253        final int allAppsSize = allAps.size();
2254        synchronized (mPackages) {
2255            for (int i = 0; i < allAppsSize; i++) {
2256                String pName = allAps.get(i);
2257                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2258                // Should not happen, but we shouldn't be failing if it does
2259                if (pkgSetting == null) {
2260                    continue;
2261                }
2262                boolean install = enableApps.contains(pName);
2263                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2264                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2265                            + " for system user");
2266                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2267                }
2268            }
2269            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2270        }
2271    }
2272
2273    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2274        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2275                Context.DISPLAY_SERVICE);
2276        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2277    }
2278
2279    /**
2280     * Requests that files preopted on a secondary system partition be copied to the data partition
2281     * if possible.  Note that the actual copying of the files is accomplished by init for security
2282     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2283     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2284     */
2285    private static void requestCopyPreoptedFiles() {
2286        final int WAIT_TIME_MS = 100;
2287        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2288        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2289            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2290            // We will wait for up to 100 seconds.
2291            final long timeStart = SystemClock.uptimeMillis();
2292            final long timeEnd = timeStart + 100 * 1000;
2293            long timeNow = timeStart;
2294            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2295                try {
2296                    Thread.sleep(WAIT_TIME_MS);
2297                } catch (InterruptedException e) {
2298                    // Do nothing
2299                }
2300                timeNow = SystemClock.uptimeMillis();
2301                if (timeNow > timeEnd) {
2302                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2303                    Slog.wtf(TAG, "cppreopt did not finish!");
2304                    break;
2305                }
2306            }
2307
2308            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2309        }
2310    }
2311
2312    public PackageManagerService(Context context, Installer installer,
2313            boolean factoryTest, boolean onlyCore) {
2314        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2315        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2316        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2317                SystemClock.uptimeMillis());
2318
2319        if (mSdkVersion <= 0) {
2320            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2321        }
2322
2323        mContext = context;
2324
2325        mFactoryTest = factoryTest;
2326        mOnlyCore = onlyCore;
2327        mMetrics = new DisplayMetrics();
2328        mInstaller = installer;
2329
2330        // Create sub-components that provide services / data. Order here is important.
2331        synchronized (mInstallLock) {
2332        synchronized (mPackages) {
2333            // Expose private service for system components to use.
2334            LocalServices.addService(
2335                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2336            sUserManager = new UserManagerService(context, this,
2337                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2338            mPermissionManager = PermissionManagerService.create(context,
2339                    new DefaultPermissionGrantedCallback() {
2340                        @Override
2341                        public void onDefaultRuntimePermissionsGranted(int userId) {
2342                            synchronized(mPackages) {
2343                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2344                            }
2345                        }
2346                    }, mPackages /*externalLock*/);
2347            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2348            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2349        }
2350        }
2351        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2352                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2353        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2354                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2355        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2356                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2357        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2358                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2359        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2360                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2361        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2362                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2363
2364        String separateProcesses = SystemProperties.get("debug.separate_processes");
2365        if (separateProcesses != null && separateProcesses.length() > 0) {
2366            if ("*".equals(separateProcesses)) {
2367                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2368                mSeparateProcesses = null;
2369                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2370            } else {
2371                mDefParseFlags = 0;
2372                mSeparateProcesses = separateProcesses.split(",");
2373                Slog.w(TAG, "Running with debug.separate_processes: "
2374                        + separateProcesses);
2375            }
2376        } else {
2377            mDefParseFlags = 0;
2378            mSeparateProcesses = null;
2379        }
2380
2381        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2382                "*dexopt*");
2383        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2384        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2385
2386        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2387                FgThread.get().getLooper());
2388
2389        getDefaultDisplayMetrics(context, mMetrics);
2390
2391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2392        SystemConfig systemConfig = SystemConfig.getInstance();
2393        mAvailableFeatures = systemConfig.getAvailableFeatures();
2394        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2395
2396        mProtectedPackages = new ProtectedPackages(mContext);
2397
2398        synchronized (mInstallLock) {
2399        // writer
2400        synchronized (mPackages) {
2401            mHandlerThread = new ServiceThread(TAG,
2402                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2403            mHandlerThread.start();
2404            mHandler = new PackageHandler(mHandlerThread.getLooper());
2405            mProcessLoggingHandler = new ProcessLoggingHandler();
2406            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2407            mInstantAppRegistry = new InstantAppRegistry(this);
2408
2409            File dataDir = Environment.getDataDirectory();
2410            mAppInstallDir = new File(dataDir, "app");
2411            mAppLib32InstallDir = new File(dataDir, "app-lib");
2412            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2413
2414            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2415            final int builtInLibCount = libConfig.size();
2416            for (int i = 0; i < builtInLibCount; i++) {
2417                String name = libConfig.keyAt(i);
2418                String path = libConfig.valueAt(i);
2419                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2420                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2421            }
2422
2423            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2424
2425            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2426            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2427            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2428
2429            // Clean up orphaned packages for which the code path doesn't exist
2430            // and they are an update to a system app - caused by bug/32321269
2431            final int packageSettingCount = mSettings.mPackages.size();
2432            for (int i = packageSettingCount - 1; i >= 0; i--) {
2433                PackageSetting ps = mSettings.mPackages.valueAt(i);
2434                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2435                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2436                    mSettings.mPackages.removeAt(i);
2437                    mSettings.enableSystemPackageLPw(ps.name);
2438                }
2439            }
2440
2441            if (mFirstBoot) {
2442                requestCopyPreoptedFiles();
2443            }
2444
2445            String customResolverActivity = Resources.getSystem().getString(
2446                    R.string.config_customResolverActivity);
2447            if (TextUtils.isEmpty(customResolverActivity)) {
2448                customResolverActivity = null;
2449            } else {
2450                mCustomResolverComponentName = ComponentName.unflattenFromString(
2451                        customResolverActivity);
2452            }
2453
2454            long startTime = SystemClock.uptimeMillis();
2455
2456            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2457                    startTime);
2458
2459            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2460            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2461
2462            if (bootClassPath == null) {
2463                Slog.w(TAG, "No BOOTCLASSPATH found!");
2464            }
2465
2466            if (systemServerClassPath == null) {
2467                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2468            }
2469
2470            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2471
2472            final VersionInfo ver = mSettings.getInternalVersion();
2473            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2474            if (mIsUpgrade) {
2475                logCriticalInfo(Log.INFO,
2476                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2477            }
2478
2479            // when upgrading from pre-M, promote system app permissions from install to runtime
2480            mPromoteSystemApps =
2481                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2482
2483            // When upgrading from pre-N, we need to handle package extraction like first boot,
2484            // as there is no profiling data available.
2485            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2486
2487            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2488
2489            // save off the names of pre-existing system packages prior to scanning; we don't
2490            // want to automatically grant runtime permissions for new system apps
2491            if (mPromoteSystemApps) {
2492                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2493                while (pkgSettingIter.hasNext()) {
2494                    PackageSetting ps = pkgSettingIter.next();
2495                    if (isSystemApp(ps)) {
2496                        mExistingSystemPackages.add(ps.name);
2497                    }
2498                }
2499            }
2500
2501            mCacheDir = preparePackageParserCache(mIsUpgrade);
2502
2503            // Set flag to monitor and not change apk file paths when
2504            // scanning install directories.
2505            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2506
2507            if (mIsUpgrade || mFirstBoot) {
2508                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2509            }
2510
2511            // Collect vendor overlay packages. (Do this before scanning any apps.)
2512            // For security and version matching reason, only consider
2513            // overlay packages if they reside in the right directory.
2514            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2515                    | PackageParser.PARSE_IS_SYSTEM
2516                    | PackageParser.PARSE_IS_SYSTEM_DIR
2517                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2518
2519            mParallelPackageParserCallback.findStaticOverlayPackages();
2520
2521            // Find base frameworks (resource packages without code).
2522            scanDirTracedLI(frameworkDir, mDefParseFlags
2523                    | PackageParser.PARSE_IS_SYSTEM
2524                    | PackageParser.PARSE_IS_SYSTEM_DIR
2525                    | PackageParser.PARSE_IS_PRIVILEGED,
2526                    scanFlags | SCAN_NO_DEX, 0);
2527
2528            // Collected privileged system packages.
2529            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2530            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2531                    | PackageParser.PARSE_IS_SYSTEM
2532                    | PackageParser.PARSE_IS_SYSTEM_DIR
2533                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2534
2535            // Collect ordinary system packages.
2536            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2537            scanDirTracedLI(systemAppDir, mDefParseFlags
2538                    | PackageParser.PARSE_IS_SYSTEM
2539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2540
2541            // Collect all vendor packages.
2542            File vendorAppDir = new File("/vendor/app");
2543            try {
2544                vendorAppDir = vendorAppDir.getCanonicalFile();
2545            } catch (IOException e) {
2546                // failed to look up canonical path, continue with original one
2547            }
2548            scanDirTracedLI(vendorAppDir, mDefParseFlags
2549                    | PackageParser.PARSE_IS_SYSTEM
2550                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2551
2552            // Collect all OEM packages.
2553            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2554            scanDirTracedLI(oemAppDir, mDefParseFlags
2555                    | PackageParser.PARSE_IS_SYSTEM
2556                    | PackageParser.PARSE_IS_SYSTEM_DIR
2557                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2558
2559            // Prune any system packages that no longer exist.
2560            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2561            // Stub packages must either be replaced with full versions in the /data
2562            // partition or be disabled.
2563            final List<String> stubSystemApps = new ArrayList<>();
2564            if (!mOnlyCore) {
2565                // do this first before mucking with mPackages for the "expecting better" case
2566                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2567                while (pkgIterator.hasNext()) {
2568                    final PackageParser.Package pkg = pkgIterator.next();
2569                    if (pkg.isStub) {
2570                        stubSystemApps.add(pkg.packageName);
2571                    }
2572                }
2573
2574                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2575                while (psit.hasNext()) {
2576                    PackageSetting ps = psit.next();
2577
2578                    /*
2579                     * If this is not a system app, it can't be a
2580                     * disable system app.
2581                     */
2582                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2583                        continue;
2584                    }
2585
2586                    /*
2587                     * If the package is scanned, it's not erased.
2588                     */
2589                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2590                    if (scannedPkg != null) {
2591                        /*
2592                         * If the system app is both scanned and in the
2593                         * disabled packages list, then it must have been
2594                         * added via OTA. Remove it from the currently
2595                         * scanned package so the previously user-installed
2596                         * application can be scanned.
2597                         */
2598                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2599                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2600                                    + ps.name + "; removing system app.  Last known codePath="
2601                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2602                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2603                                    + scannedPkg.mVersionCode);
2604                            removePackageLI(scannedPkg, true);
2605                            mExpectingBetter.put(ps.name, ps.codePath);
2606                        }
2607
2608                        continue;
2609                    }
2610
2611                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2612                        psit.remove();
2613                        logCriticalInfo(Log.WARN, "System package " + ps.name
2614                                + " no longer exists; it's data will be wiped");
2615                        // Actual deletion of code and data will be handled by later
2616                        // reconciliation step
2617                    } else {
2618                        // we still have a disabled system package, but, it still might have
2619                        // been removed. check the code path still exists and check there's
2620                        // still a package. the latter can happen if an OTA keeps the same
2621                        // code path, but, changes the package name.
2622                        final PackageSetting disabledPs =
2623                                mSettings.getDisabledSystemPkgLPr(ps.name);
2624                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2625                                || disabledPs.pkg == null) {
2626                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2627                        }
2628                    }
2629                }
2630            }
2631
2632            //look for any incomplete package installations
2633            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2634            for (int i = 0; i < deletePkgsList.size(); i++) {
2635                // Actual deletion of code and data will be handled by later
2636                // reconciliation step
2637                final String packageName = deletePkgsList.get(i).name;
2638                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2639                synchronized (mPackages) {
2640                    mSettings.removePackageLPw(packageName);
2641                }
2642            }
2643
2644            //delete tmp files
2645            deleteTempPackageFiles();
2646
2647            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2648
2649            // Remove any shared userIDs that have no associated packages
2650            mSettings.pruneSharedUsersLPw();
2651            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2652            final int systemPackagesCount = mPackages.size();
2653            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2654                    + " ms, packageCount: " + systemPackagesCount
2655                    + " , timePerPackage: "
2656                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2657                    + " , cached: " + cachedSystemApps);
2658            if (mIsUpgrade && systemPackagesCount > 0) {
2659                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2660                        ((int) systemScanTime) / systemPackagesCount);
2661            }
2662            if (!mOnlyCore) {
2663                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2664                        SystemClock.uptimeMillis());
2665                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2666
2667                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2668                        | PackageParser.PARSE_FORWARD_LOCK,
2669                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2670
2671                // Remove disable package settings for updated system apps that were
2672                // removed via an OTA. If the update is no longer present, remove the
2673                // app completely. Otherwise, revoke their system privileges.
2674                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2675                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2676                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2677
2678                    final String msg;
2679                    if (deletedPkg == null) {
2680                        // should have found an update, but, we didn't; remove everything
2681                        msg = "Updated system package " + deletedAppName
2682                                + " no longer exists; removing its data";
2683                        // Actual deletion of code and data will be handled by later
2684                        // reconciliation step
2685                    } else {
2686                        // found an update; revoke system privileges
2687                        msg = "Updated system package + " + deletedAppName
2688                                + " no longer exists; revoking system privileges";
2689
2690                        // Don't do anything if a stub is removed from the system image. If
2691                        // we were to remove the uncompressed version from the /data partition,
2692                        // this is where it'd be done.
2693
2694                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2695                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2696                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2697                    }
2698                    logCriticalInfo(Log.WARN, msg);
2699                }
2700
2701                /*
2702                 * Make sure all system apps that we expected to appear on
2703                 * the userdata partition actually showed up. If they never
2704                 * appeared, crawl back and revive the system version.
2705                 */
2706                for (int i = 0; i < mExpectingBetter.size(); i++) {
2707                    final String packageName = mExpectingBetter.keyAt(i);
2708                    if (!mPackages.containsKey(packageName)) {
2709                        final File scanFile = mExpectingBetter.valueAt(i);
2710
2711                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2712                                + " but never showed up; reverting to system");
2713
2714                        int reparseFlags = mDefParseFlags;
2715                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2716                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2717                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2718                                    | PackageParser.PARSE_IS_PRIVILEGED;
2719                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2720                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2721                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2722                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2723                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2724                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2725                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2726                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2727                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2728                                    | PackageParser.PARSE_IS_OEM;
2729                        } else {
2730                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2731                            continue;
2732                        }
2733
2734                        mSettings.enableSystemPackageLPw(packageName);
2735
2736                        try {
2737                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2738                        } catch (PackageManagerException e) {
2739                            Slog.e(TAG, "Failed to parse original system package: "
2740                                    + e.getMessage());
2741                        }
2742                    }
2743                }
2744
2745                // Uncompress and install any stubbed system applications.
2746                // This must be done last to ensure all stubs are replaced or disabled.
2747                decompressSystemApplications(stubSystemApps, scanFlags);
2748
2749                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2750                                - cachedSystemApps;
2751
2752                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2753                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2754                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2755                        + " ms, packageCount: " + dataPackagesCount
2756                        + " , timePerPackage: "
2757                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2758                        + " , cached: " + cachedNonSystemApps);
2759                if (mIsUpgrade && dataPackagesCount > 0) {
2760                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2761                            ((int) dataScanTime) / dataPackagesCount);
2762                }
2763            }
2764            mExpectingBetter.clear();
2765
2766            // Resolve the storage manager.
2767            mStorageManagerPackage = getStorageManagerPackageName();
2768
2769            // Resolve protected action filters. Only the setup wizard is allowed to
2770            // have a high priority filter for these actions.
2771            mSetupWizardPackage = getSetupWizardPackageName();
2772            if (mProtectedFilters.size() > 0) {
2773                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2774                    Slog.i(TAG, "No setup wizard;"
2775                        + " All protected intents capped to priority 0");
2776                }
2777                for (ActivityIntentInfo filter : mProtectedFilters) {
2778                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2779                        if (DEBUG_FILTERS) {
2780                            Slog.i(TAG, "Found setup wizard;"
2781                                + " allow priority " + filter.getPriority() + ";"
2782                                + " package: " + filter.activity.info.packageName
2783                                + " activity: " + filter.activity.className
2784                                + " priority: " + filter.getPriority());
2785                        }
2786                        // skip setup wizard; allow it to keep the high priority filter
2787                        continue;
2788                    }
2789                    if (DEBUG_FILTERS) {
2790                        Slog.i(TAG, "Protected action; cap priority to 0;"
2791                                + " package: " + filter.activity.info.packageName
2792                                + " activity: " + filter.activity.className
2793                                + " origPrio: " + filter.getPriority());
2794                    }
2795                    filter.setPriority(0);
2796                }
2797            }
2798            mDeferProtectedFilters = false;
2799            mProtectedFilters.clear();
2800
2801            // Now that we know all of the shared libraries, update all clients to have
2802            // the correct library paths.
2803            updateAllSharedLibrariesLPw(null);
2804
2805            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2806                // NOTE: We ignore potential failures here during a system scan (like
2807                // the rest of the commands above) because there's precious little we
2808                // can do about it. A settings error is reported, though.
2809                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2810            }
2811
2812            // Now that we know all the packages we are keeping,
2813            // read and update their last usage times.
2814            mPackageUsage.read(mPackages);
2815            mCompilerStats.read();
2816
2817            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2818                    SystemClock.uptimeMillis());
2819            Slog.i(TAG, "Time to scan packages: "
2820                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2821                    + " seconds");
2822
2823            // If the platform SDK has changed since the last time we booted,
2824            // we need to re-grant app permission to catch any new ones that
2825            // appear.  This is really a hack, and means that apps can in some
2826            // cases get permissions that the user didn't initially explicitly
2827            // allow...  it would be nice to have some better way to handle
2828            // this situation.
2829            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2830            if (sdkUpdated) {
2831                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2832                        + mSdkVersion + "; regranting permissions for internal storage");
2833            }
2834            mPermissionManager.updateAllPermissions(
2835                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2836                    mPermissionCallback);
2837            ver.sdkVersion = mSdkVersion;
2838
2839            // If this is the first boot or an update from pre-M, and it is a normal
2840            // boot, then we need to initialize the default preferred apps across
2841            // all defined users.
2842            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2843                for (UserInfo user : sUserManager.getUsers(true)) {
2844                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2845                    applyFactoryDefaultBrowserLPw(user.id);
2846                    primeDomainVerificationsLPw(user.id);
2847                }
2848            }
2849
2850            // Prepare storage for system user really early during boot,
2851            // since core system apps like SettingsProvider and SystemUI
2852            // can't wait for user to start
2853            final int storageFlags;
2854            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2855                storageFlags = StorageManager.FLAG_STORAGE_DE;
2856            } else {
2857                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2858            }
2859            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2860                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2861                    true /* onlyCoreApps */);
2862            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2863                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2864                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2865                traceLog.traceBegin("AppDataFixup");
2866                try {
2867                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2868                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2869                } catch (InstallerException e) {
2870                    Slog.w(TAG, "Trouble fixing GIDs", e);
2871                }
2872                traceLog.traceEnd();
2873
2874                traceLog.traceBegin("AppDataPrepare");
2875                if (deferPackages == null || deferPackages.isEmpty()) {
2876                    return;
2877                }
2878                int count = 0;
2879                for (String pkgName : deferPackages) {
2880                    PackageParser.Package pkg = null;
2881                    synchronized (mPackages) {
2882                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2883                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2884                            pkg = ps.pkg;
2885                        }
2886                    }
2887                    if (pkg != null) {
2888                        synchronized (mInstallLock) {
2889                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2890                                    true /* maybeMigrateAppData */);
2891                        }
2892                        count++;
2893                    }
2894                }
2895                traceLog.traceEnd();
2896                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2897            }, "prepareAppData");
2898
2899            // If this is first boot after an OTA, and a normal boot, then
2900            // we need to clear code cache directories.
2901            // Note that we do *not* clear the application profiles. These remain valid
2902            // across OTAs and are used to drive profile verification (post OTA) and
2903            // profile compilation (without waiting to collect a fresh set of profiles).
2904            if (mIsUpgrade && !onlyCore) {
2905                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2906                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2907                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2908                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2909                        // No apps are running this early, so no need to freeze
2910                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2911                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2912                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2913                    }
2914                }
2915                ver.fingerprint = Build.FINGERPRINT;
2916            }
2917
2918            checkDefaultBrowser();
2919
2920            // clear only after permissions and other defaults have been updated
2921            mExistingSystemPackages.clear();
2922            mPromoteSystemApps = false;
2923
2924            // All the changes are done during package scanning.
2925            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2926
2927            // can downgrade to reader
2928            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2929            mSettings.writeLPr();
2930            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2931            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2932                    SystemClock.uptimeMillis());
2933
2934            if (!mOnlyCore) {
2935                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2936                mRequiredInstallerPackage = getRequiredInstallerLPr();
2937                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2938                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2939                if (mIntentFilterVerifierComponent != null) {
2940                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2941                            mIntentFilterVerifierComponent);
2942                } else {
2943                    mIntentFilterVerifier = null;
2944                }
2945                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2946                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2947                        SharedLibraryInfo.VERSION_UNDEFINED);
2948                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2949                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2950                        SharedLibraryInfo.VERSION_UNDEFINED);
2951            } else {
2952                mRequiredVerifierPackage = null;
2953                mRequiredInstallerPackage = null;
2954                mRequiredUninstallerPackage = null;
2955                mIntentFilterVerifierComponent = null;
2956                mIntentFilterVerifier = null;
2957                mServicesSystemSharedLibraryPackageName = null;
2958                mSharedSystemSharedLibraryPackageName = null;
2959            }
2960
2961            mInstallerService = new PackageInstallerService(context, this);
2962            final Pair<ComponentName, String> instantAppResolverComponent =
2963                    getInstantAppResolverLPr();
2964            if (instantAppResolverComponent != null) {
2965                if (DEBUG_EPHEMERAL) {
2966                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2967                }
2968                mInstantAppResolverConnection = new EphemeralResolverConnection(
2969                        mContext, instantAppResolverComponent.first,
2970                        instantAppResolverComponent.second);
2971                mInstantAppResolverSettingsComponent =
2972                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2973            } else {
2974                mInstantAppResolverConnection = null;
2975                mInstantAppResolverSettingsComponent = null;
2976            }
2977            updateInstantAppInstallerLocked(null);
2978
2979            // Read and update the usage of dex files.
2980            // Do this at the end of PM init so that all the packages have their
2981            // data directory reconciled.
2982            // At this point we know the code paths of the packages, so we can validate
2983            // the disk file and build the internal cache.
2984            // The usage file is expected to be small so loading and verifying it
2985            // should take a fairly small time compare to the other activities (e.g. package
2986            // scanning).
2987            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2988            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2989            for (int userId : currentUserIds) {
2990                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2991            }
2992            mDexManager.load(userPackages);
2993            if (mIsUpgrade) {
2994                MetricsLogger.histogram(null, "ota_package_manager_init_time",
2995                        (int) (SystemClock.uptimeMillis() - startTime));
2996            }
2997        } // synchronized (mPackages)
2998        } // synchronized (mInstallLock)
2999
3000        // Now after opening every single application zip, make sure they
3001        // are all flushed.  Not really needed, but keeps things nice and
3002        // tidy.
3003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3004        Runtime.getRuntime().gc();
3005        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3006
3007        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3008        FallbackCategoryProvider.loadFallbacks();
3009        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3010
3011        // The initial scanning above does many calls into installd while
3012        // holding the mPackages lock, but we're mostly interested in yelling
3013        // once we have a booted system.
3014        mInstaller.setWarnIfHeld(mPackages);
3015
3016        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3017    }
3018
3019    /**
3020     * Uncompress and install stub applications.
3021     * <p>In order to save space on the system partition, some applications are shipped in a
3022     * compressed form. In addition the compressed bits for the full application, the
3023     * system image contains a tiny stub comprised of only the Android manifest.
3024     * <p>During the first boot, attempt to uncompress and install the full application. If
3025     * the application can't be installed for any reason, disable the stub and prevent
3026     * uncompressing the full application during future boots.
3027     * <p>In order to forcefully attempt an installation of a full application, go to app
3028     * settings and enable the application.
3029     */
3030    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3031        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3032            final String pkgName = stubSystemApps.get(i);
3033            // skip if the system package is already disabled
3034            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3035                stubSystemApps.remove(i);
3036                continue;
3037            }
3038            // skip if the package isn't installed (?!); this should never happen
3039            final PackageParser.Package pkg = mPackages.get(pkgName);
3040            if (pkg == null) {
3041                stubSystemApps.remove(i);
3042                continue;
3043            }
3044            // skip if the package has been disabled by the user
3045            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3046            if (ps != null) {
3047                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3048                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3049                    stubSystemApps.remove(i);
3050                    continue;
3051                }
3052            }
3053
3054            if (DEBUG_COMPRESSION) {
3055                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3056            }
3057
3058            // uncompress the binary to its eventual destination on /data
3059            final File scanFile = decompressPackage(pkg);
3060            if (scanFile == null) {
3061                continue;
3062            }
3063
3064            // install the package to replace the stub on /system
3065            try {
3066                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3067                removePackageLI(pkg, true /*chatty*/);
3068                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3069                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3070                        UserHandle.USER_SYSTEM, "android");
3071                stubSystemApps.remove(i);
3072                continue;
3073            } catch (PackageManagerException e) {
3074                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3075            }
3076
3077            // any failed attempt to install the package will be cleaned up later
3078        }
3079
3080        // disable any stub still left; these failed to install the full application
3081        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3082            final String pkgName = stubSystemApps.get(i);
3083            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3084            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3085                    UserHandle.USER_SYSTEM, "android");
3086            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3087        }
3088    }
3089
3090    /**
3091     * Decompresses the given package on the system image onto
3092     * the /data partition.
3093     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3094     */
3095    private File decompressPackage(PackageParser.Package pkg) {
3096        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3097        if (compressedFiles == null || compressedFiles.length == 0) {
3098            if (DEBUG_COMPRESSION) {
3099                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3100            }
3101            return null;
3102        }
3103        final File dstCodePath =
3104                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3105        int ret = PackageManager.INSTALL_SUCCEEDED;
3106        try {
3107            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3108            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3109            for (File srcFile : compressedFiles) {
3110                final String srcFileName = srcFile.getName();
3111                final String dstFileName = srcFileName.substring(
3112                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3113                final File dstFile = new File(dstCodePath, dstFileName);
3114                ret = decompressFile(srcFile, dstFile);
3115                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3116                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3117                            + "; pkg: " + pkg.packageName
3118                            + ", file: " + dstFileName);
3119                    break;
3120                }
3121            }
3122        } catch (ErrnoException e) {
3123            logCriticalInfo(Log.ERROR, "Failed to decompress"
3124                    + "; pkg: " + pkg.packageName
3125                    + ", err: " + e.errno);
3126        }
3127        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3128            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3129            NativeLibraryHelper.Handle handle = null;
3130            try {
3131                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3132                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3133                        null /*abiOverride*/);
3134            } catch (IOException e) {
3135                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3136                        + "; pkg: " + pkg.packageName);
3137                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3138            } finally {
3139                IoUtils.closeQuietly(handle);
3140            }
3141        }
3142        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3143            if (dstCodePath == null || !dstCodePath.exists()) {
3144                return null;
3145            }
3146            removeCodePathLI(dstCodePath);
3147            return null;
3148        }
3149
3150        return dstCodePath;
3151    }
3152
3153    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3154        // we're only interested in updating the installer appliction when 1) it's not
3155        // already set or 2) the modified package is the installer
3156        if (mInstantAppInstallerActivity != null
3157                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3158                        .equals(modifiedPackage)) {
3159            return;
3160        }
3161        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3162    }
3163
3164    private static File preparePackageParserCache(boolean isUpgrade) {
3165        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3166            return null;
3167        }
3168
3169        // Disable package parsing on eng builds to allow for faster incremental development.
3170        if (Build.IS_ENG) {
3171            return null;
3172        }
3173
3174        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3175            Slog.i(TAG, "Disabling package parser cache due to system property.");
3176            return null;
3177        }
3178
3179        // The base directory for the package parser cache lives under /data/system/.
3180        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3181                "package_cache");
3182        if (cacheBaseDir == null) {
3183            return null;
3184        }
3185
3186        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3187        // This also serves to "GC" unused entries when the package cache version changes (which
3188        // can only happen during upgrades).
3189        if (isUpgrade) {
3190            FileUtils.deleteContents(cacheBaseDir);
3191        }
3192
3193
3194        // Return the versioned package cache directory. This is something like
3195        // "/data/system/package_cache/1"
3196        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3197
3198        // The following is a workaround to aid development on non-numbered userdebug
3199        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3200        // the system partition is newer.
3201        //
3202        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3203        // that starts with "eng." to signify that this is an engineering build and not
3204        // destined for release.
3205        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3206            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3207
3208            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3209            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3210            // in general and should not be used for production changes. In this specific case,
3211            // we know that they will work.
3212            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3213            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3214                FileUtils.deleteContents(cacheBaseDir);
3215                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3216            }
3217        }
3218
3219        return cacheDir;
3220    }
3221
3222    @Override
3223    public boolean isFirstBoot() {
3224        // allow instant applications
3225        return mFirstBoot;
3226    }
3227
3228    @Override
3229    public boolean isOnlyCoreApps() {
3230        // allow instant applications
3231        return mOnlyCore;
3232    }
3233
3234    @Override
3235    public boolean isUpgrade() {
3236        // allow instant applications
3237        // The system property allows testing ota flow when upgraded to the same image.
3238        return mIsUpgrade || SystemProperties.getBoolean(
3239                "persist.pm.mock-upgrade", false /* default */);
3240    }
3241
3242    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3243        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3244
3245        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3246                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3247                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3248        if (matches.size() == 1) {
3249            return matches.get(0).getComponentInfo().packageName;
3250        } else if (matches.size() == 0) {
3251            Log.e(TAG, "There should probably be a verifier, but, none were found");
3252            return null;
3253        }
3254        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3255    }
3256
3257    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3258        synchronized (mPackages) {
3259            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3260            if (libraryEntry == null) {
3261                throw new IllegalStateException("Missing required shared library:" + name);
3262            }
3263            return libraryEntry.apk;
3264        }
3265    }
3266
3267    private @NonNull String getRequiredInstallerLPr() {
3268        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3269        intent.addCategory(Intent.CATEGORY_DEFAULT);
3270        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3271
3272        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3273                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3274                UserHandle.USER_SYSTEM);
3275        if (matches.size() == 1) {
3276            ResolveInfo resolveInfo = matches.get(0);
3277            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3278                throw new RuntimeException("The installer must be a privileged app");
3279            }
3280            return matches.get(0).getComponentInfo().packageName;
3281        } else {
3282            throw new RuntimeException("There must be exactly one installer; found " + matches);
3283        }
3284    }
3285
3286    private @NonNull String getRequiredUninstallerLPr() {
3287        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3288        intent.addCategory(Intent.CATEGORY_DEFAULT);
3289        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3290
3291        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3292                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3293                UserHandle.USER_SYSTEM);
3294        if (resolveInfo == null ||
3295                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3296            throw new RuntimeException("There must be exactly one uninstaller; found "
3297                    + resolveInfo);
3298        }
3299        return resolveInfo.getComponentInfo().packageName;
3300    }
3301
3302    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3303        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3304
3305        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3306                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3307                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3308        ResolveInfo best = null;
3309        final int N = matches.size();
3310        for (int i = 0; i < N; i++) {
3311            final ResolveInfo cur = matches.get(i);
3312            final String packageName = cur.getComponentInfo().packageName;
3313            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3314                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3315                continue;
3316            }
3317
3318            if (best == null || cur.priority > best.priority) {
3319                best = cur;
3320            }
3321        }
3322
3323        if (best != null) {
3324            return best.getComponentInfo().getComponentName();
3325        }
3326        Slog.w(TAG, "Intent filter verifier not found");
3327        return null;
3328    }
3329
3330    @Override
3331    public @Nullable ComponentName getInstantAppResolverComponent() {
3332        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3333            return null;
3334        }
3335        synchronized (mPackages) {
3336            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3337            if (instantAppResolver == null) {
3338                return null;
3339            }
3340            return instantAppResolver.first;
3341        }
3342    }
3343
3344    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3345        final String[] packageArray =
3346                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3347        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3348            if (DEBUG_EPHEMERAL) {
3349                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3350            }
3351            return null;
3352        }
3353
3354        final int callingUid = Binder.getCallingUid();
3355        final int resolveFlags =
3356                MATCH_DIRECT_BOOT_AWARE
3357                | MATCH_DIRECT_BOOT_UNAWARE
3358                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3359        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3360        final Intent resolverIntent = new Intent(actionName);
3361        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3362                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3363        // temporarily look for the old action
3364        if (resolvers.size() == 0) {
3365            if (DEBUG_EPHEMERAL) {
3366                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3367            }
3368            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3369            resolverIntent.setAction(actionName);
3370            resolvers = queryIntentServicesInternal(resolverIntent, null,
3371                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3372        }
3373        final int N = resolvers.size();
3374        if (N == 0) {
3375            if (DEBUG_EPHEMERAL) {
3376                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3377            }
3378            return null;
3379        }
3380
3381        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3382        for (int i = 0; i < N; i++) {
3383            final ResolveInfo info = resolvers.get(i);
3384
3385            if (info.serviceInfo == null) {
3386                continue;
3387            }
3388
3389            final String packageName = info.serviceInfo.packageName;
3390            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3391                if (DEBUG_EPHEMERAL) {
3392                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3393                            + " pkg: " + packageName + ", info:" + info);
3394                }
3395                continue;
3396            }
3397
3398            if (DEBUG_EPHEMERAL) {
3399                Slog.v(TAG, "Ephemeral resolver found;"
3400                        + " pkg: " + packageName + ", info:" + info);
3401            }
3402            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3403        }
3404        if (DEBUG_EPHEMERAL) {
3405            Slog.v(TAG, "Ephemeral resolver NOT found");
3406        }
3407        return null;
3408    }
3409
3410    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3411        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3412        intent.addCategory(Intent.CATEGORY_DEFAULT);
3413        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3414
3415        final int resolveFlags =
3416                MATCH_DIRECT_BOOT_AWARE
3417                | MATCH_DIRECT_BOOT_UNAWARE
3418                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3419        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3420                resolveFlags, UserHandle.USER_SYSTEM);
3421        // temporarily look for the old action
3422        if (matches.isEmpty()) {
3423            if (DEBUG_EPHEMERAL) {
3424                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3425            }
3426            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3427            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3428                    resolveFlags, UserHandle.USER_SYSTEM);
3429        }
3430        Iterator<ResolveInfo> iter = matches.iterator();
3431        while (iter.hasNext()) {
3432            final ResolveInfo rInfo = iter.next();
3433            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3434            if (ps != null) {
3435                final PermissionsState permissionsState = ps.getPermissionsState();
3436                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3437                    continue;
3438                }
3439            }
3440            iter.remove();
3441        }
3442        if (matches.size() == 0) {
3443            return null;
3444        } else if (matches.size() == 1) {
3445            return (ActivityInfo) matches.get(0).getComponentInfo();
3446        } else {
3447            throw new RuntimeException(
3448                    "There must be at most one ephemeral installer; found " + matches);
3449        }
3450    }
3451
3452    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3453            @NonNull ComponentName resolver) {
3454        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3455                .addCategory(Intent.CATEGORY_DEFAULT)
3456                .setPackage(resolver.getPackageName());
3457        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3458        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3459                UserHandle.USER_SYSTEM);
3460        // temporarily look for the old action
3461        if (matches.isEmpty()) {
3462            if (DEBUG_EPHEMERAL) {
3463                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3464            }
3465            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3466            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3467                    UserHandle.USER_SYSTEM);
3468        }
3469        if (matches.isEmpty()) {
3470            return null;
3471        }
3472        return matches.get(0).getComponentInfo().getComponentName();
3473    }
3474
3475    private void primeDomainVerificationsLPw(int userId) {
3476        if (DEBUG_DOMAIN_VERIFICATION) {
3477            Slog.d(TAG, "Priming domain verifications in user " + userId);
3478        }
3479
3480        SystemConfig systemConfig = SystemConfig.getInstance();
3481        ArraySet<String> packages = systemConfig.getLinkedApps();
3482
3483        for (String packageName : packages) {
3484            PackageParser.Package pkg = mPackages.get(packageName);
3485            if (pkg != null) {
3486                if (!pkg.isSystem()) {
3487                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3488                    continue;
3489                }
3490
3491                ArraySet<String> domains = null;
3492                for (PackageParser.Activity a : pkg.activities) {
3493                    for (ActivityIntentInfo filter : a.intents) {
3494                        if (hasValidDomains(filter)) {
3495                            if (domains == null) {
3496                                domains = new ArraySet<String>();
3497                            }
3498                            domains.addAll(filter.getHostsList());
3499                        }
3500                    }
3501                }
3502
3503                if (domains != null && domains.size() > 0) {
3504                    if (DEBUG_DOMAIN_VERIFICATION) {
3505                        Slog.v(TAG, "      + " + packageName);
3506                    }
3507                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3508                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3509                    // and then 'always' in the per-user state actually used for intent resolution.
3510                    final IntentFilterVerificationInfo ivi;
3511                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3512                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3513                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3514                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3515                } else {
3516                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3517                            + "' does not handle web links");
3518                }
3519            } else {
3520                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3521            }
3522        }
3523
3524        scheduleWritePackageRestrictionsLocked(userId);
3525        scheduleWriteSettingsLocked();
3526    }
3527
3528    private void applyFactoryDefaultBrowserLPw(int userId) {
3529        // The default browser app's package name is stored in a string resource,
3530        // with a product-specific overlay used for vendor customization.
3531        String browserPkg = mContext.getResources().getString(
3532                com.android.internal.R.string.default_browser);
3533        if (!TextUtils.isEmpty(browserPkg)) {
3534            // non-empty string => required to be a known package
3535            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3536            if (ps == null) {
3537                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3538                browserPkg = null;
3539            } else {
3540                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3541            }
3542        }
3543
3544        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3545        // default.  If there's more than one, just leave everything alone.
3546        if (browserPkg == null) {
3547            calculateDefaultBrowserLPw(userId);
3548        }
3549    }
3550
3551    private void calculateDefaultBrowserLPw(int userId) {
3552        List<String> allBrowsers = resolveAllBrowserApps(userId);
3553        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3554        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3555    }
3556
3557    private List<String> resolveAllBrowserApps(int userId) {
3558        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3559        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3560                PackageManager.MATCH_ALL, userId);
3561
3562        final int count = list.size();
3563        List<String> result = new ArrayList<String>(count);
3564        for (int i=0; i<count; i++) {
3565            ResolveInfo info = list.get(i);
3566            if (info.activityInfo == null
3567                    || !info.handleAllWebDataURI
3568                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3569                    || result.contains(info.activityInfo.packageName)) {
3570                continue;
3571            }
3572            result.add(info.activityInfo.packageName);
3573        }
3574
3575        return result;
3576    }
3577
3578    private boolean packageIsBrowser(String packageName, int userId) {
3579        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3580                PackageManager.MATCH_ALL, userId);
3581        final int N = list.size();
3582        for (int i = 0; i < N; i++) {
3583            ResolveInfo info = list.get(i);
3584            if (packageName.equals(info.activityInfo.packageName)) {
3585                return true;
3586            }
3587        }
3588        return false;
3589    }
3590
3591    private void checkDefaultBrowser() {
3592        final int myUserId = UserHandle.myUserId();
3593        final String packageName = getDefaultBrowserPackageName(myUserId);
3594        if (packageName != null) {
3595            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3596            if (info == null) {
3597                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3598                synchronized (mPackages) {
3599                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3600                }
3601            }
3602        }
3603    }
3604
3605    @Override
3606    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3607            throws RemoteException {
3608        try {
3609            return super.onTransact(code, data, reply, flags);
3610        } catch (RuntimeException e) {
3611            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3612                Slog.wtf(TAG, "Package Manager Crash", e);
3613            }
3614            throw e;
3615        }
3616    }
3617
3618    static int[] appendInts(int[] cur, int[] add) {
3619        if (add == null) return cur;
3620        if (cur == null) return add;
3621        final int N = add.length;
3622        for (int i=0; i<N; i++) {
3623            cur = appendInt(cur, add[i]);
3624        }
3625        return cur;
3626    }
3627
3628    /**
3629     * Returns whether or not a full application can see an instant application.
3630     * <p>
3631     * Currently, there are three cases in which this can occur:
3632     * <ol>
3633     * <li>The calling application is a "special" process. Special processes
3634     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3635     * <li>The calling application has the permission
3636     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3637     * <li>The calling application is the default launcher on the
3638     *     system partition.</li>
3639     * </ol>
3640     */
3641    private boolean canViewInstantApps(int callingUid, int userId) {
3642        if (callingUid < Process.FIRST_APPLICATION_UID) {
3643            return true;
3644        }
3645        if (mContext.checkCallingOrSelfPermission(
3646                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3647            return true;
3648        }
3649        if (mContext.checkCallingOrSelfPermission(
3650                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3651            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3652            if (homeComponent != null
3653                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3654                return true;
3655            }
3656        }
3657        return false;
3658    }
3659
3660    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3661        if (!sUserManager.exists(userId)) return null;
3662        if (ps == null) {
3663            return null;
3664        }
3665        PackageParser.Package p = ps.pkg;
3666        if (p == null) {
3667            return null;
3668        }
3669        final int callingUid = Binder.getCallingUid();
3670        // Filter out ephemeral app metadata:
3671        //   * The system/shell/root can see metadata for any app
3672        //   * An installed app can see metadata for 1) other installed apps
3673        //     and 2) ephemeral apps that have explicitly interacted with it
3674        //   * Ephemeral apps can only see their own data and exposed installed apps
3675        //   * Holding a signature permission allows seeing instant apps
3676        if (filterAppAccessLPr(ps, callingUid, userId)) {
3677            return null;
3678        }
3679
3680        final PermissionsState permissionsState = ps.getPermissionsState();
3681
3682        // Compute GIDs only if requested
3683        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3684                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3685        // Compute granted permissions only if package has requested permissions
3686        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3687                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3688        final PackageUserState state = ps.readUserState(userId);
3689
3690        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3691                && ps.isSystem()) {
3692            flags |= MATCH_ANY_USER;
3693        }
3694
3695        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3696                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3697
3698        if (packageInfo == null) {
3699            return null;
3700        }
3701
3702        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3703                resolveExternalPackageNameLPr(p);
3704
3705        return packageInfo;
3706    }
3707
3708    @Override
3709    public void checkPackageStartable(String packageName, int userId) {
3710        final int callingUid = Binder.getCallingUid();
3711        if (getInstantAppPackageName(callingUid) != null) {
3712            throw new SecurityException("Instant applications don't have access to this method");
3713        }
3714        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3715        synchronized (mPackages) {
3716            final PackageSetting ps = mSettings.mPackages.get(packageName);
3717            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3718                throw new SecurityException("Package " + packageName + " was not found!");
3719            }
3720
3721            if (!ps.getInstalled(userId)) {
3722                throw new SecurityException(
3723                        "Package " + packageName + " was not installed for user " + userId + "!");
3724            }
3725
3726            if (mSafeMode && !ps.isSystem()) {
3727                throw new SecurityException("Package " + packageName + " not a system app!");
3728            }
3729
3730            if (mFrozenPackages.contains(packageName)) {
3731                throw new SecurityException("Package " + packageName + " is currently frozen!");
3732            }
3733
3734            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3735                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3736            }
3737        }
3738    }
3739
3740    @Override
3741    public boolean isPackageAvailable(String packageName, int userId) {
3742        if (!sUserManager.exists(userId)) return false;
3743        final int callingUid = Binder.getCallingUid();
3744        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3745                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3746        synchronized (mPackages) {
3747            PackageParser.Package p = mPackages.get(packageName);
3748            if (p != null) {
3749                final PackageSetting ps = (PackageSetting) p.mExtras;
3750                if (filterAppAccessLPr(ps, callingUid, userId)) {
3751                    return false;
3752                }
3753                if (ps != null) {
3754                    final PackageUserState state = ps.readUserState(userId);
3755                    if (state != null) {
3756                        return PackageParser.isAvailable(state);
3757                    }
3758                }
3759            }
3760        }
3761        return false;
3762    }
3763
3764    @Override
3765    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3766        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3767                flags, Binder.getCallingUid(), userId);
3768    }
3769
3770    @Override
3771    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3772            int flags, int userId) {
3773        return getPackageInfoInternal(versionedPackage.getPackageName(),
3774                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3775    }
3776
3777    /**
3778     * Important: The provided filterCallingUid is used exclusively to filter out packages
3779     * that can be seen based on user state. It's typically the original caller uid prior
3780     * to clearing. Because it can only be provided by trusted code, it's value can be
3781     * trusted and will be used as-is; unlike userId which will be validated by this method.
3782     */
3783    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3784            int flags, int filterCallingUid, int userId) {
3785        if (!sUserManager.exists(userId)) return null;
3786        flags = updateFlagsForPackage(flags, userId, packageName);
3787        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3788                false /* requireFullPermission */, false /* checkShell */, "get package info");
3789
3790        // reader
3791        synchronized (mPackages) {
3792            // Normalize package name to handle renamed packages and static libs
3793            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3794
3795            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3796            if (matchFactoryOnly) {
3797                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3798                if (ps != null) {
3799                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3800                        return null;
3801                    }
3802                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3803                        return null;
3804                    }
3805                    return generatePackageInfo(ps, flags, userId);
3806                }
3807            }
3808
3809            PackageParser.Package p = mPackages.get(packageName);
3810            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3811                return null;
3812            }
3813            if (DEBUG_PACKAGE_INFO)
3814                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3815            if (p != null) {
3816                final PackageSetting ps = (PackageSetting) p.mExtras;
3817                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3818                    return null;
3819                }
3820                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3821                    return null;
3822                }
3823                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3824            }
3825            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3826                final PackageSetting ps = mSettings.mPackages.get(packageName);
3827                if (ps == null) return null;
3828                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3829                    return null;
3830                }
3831                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3832                    return null;
3833                }
3834                return generatePackageInfo(ps, flags, userId);
3835            }
3836        }
3837        return null;
3838    }
3839
3840    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3841        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3842            return true;
3843        }
3844        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3845            return true;
3846        }
3847        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3848            return true;
3849        }
3850        return false;
3851    }
3852
3853    private boolean isComponentVisibleToInstantApp(
3854            @Nullable ComponentName component, @ComponentType int type) {
3855        if (type == TYPE_ACTIVITY) {
3856            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3857            return activity != null
3858                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3859                    : false;
3860        } else if (type == TYPE_RECEIVER) {
3861            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3862            return activity != null
3863                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3864                    : false;
3865        } else if (type == TYPE_SERVICE) {
3866            final PackageParser.Service service = mServices.mServices.get(component);
3867            return service != null
3868                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3869                    : false;
3870        } else if (type == TYPE_PROVIDER) {
3871            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3872            return provider != null
3873                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3874                    : false;
3875        } else if (type == TYPE_UNKNOWN) {
3876            return isComponentVisibleToInstantApp(component);
3877        }
3878        return false;
3879    }
3880
3881    /**
3882     * Returns whether or not access to the application should be filtered.
3883     * <p>
3884     * Access may be limited based upon whether the calling or target applications
3885     * are instant applications.
3886     *
3887     * @see #canAccessInstantApps(int)
3888     */
3889    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3890            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3891        // if we're in an isolated process, get the real calling UID
3892        if (Process.isIsolated(callingUid)) {
3893            callingUid = mIsolatedOwners.get(callingUid);
3894        }
3895        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3896        final boolean callerIsInstantApp = instantAppPkgName != null;
3897        if (ps == null) {
3898            if (callerIsInstantApp) {
3899                // pretend the application exists, but, needs to be filtered
3900                return true;
3901            }
3902            return false;
3903        }
3904        // if the target and caller are the same application, don't filter
3905        if (isCallerSameApp(ps.name, callingUid)) {
3906            return false;
3907        }
3908        if (callerIsInstantApp) {
3909            // request for a specific component; if it hasn't been explicitly exposed, filter
3910            if (component != null) {
3911                return !isComponentVisibleToInstantApp(component, componentType);
3912            }
3913            // request for application; if no components have been explicitly exposed, filter
3914            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3915        }
3916        if (ps.getInstantApp(userId)) {
3917            // caller can see all components of all instant applications, don't filter
3918            if (canViewInstantApps(callingUid, userId)) {
3919                return false;
3920            }
3921            // request for a specific instant application component, filter
3922            if (component != null) {
3923                return true;
3924            }
3925            // request for an instant application; if the caller hasn't been granted access, filter
3926            return !mInstantAppRegistry.isInstantAccessGranted(
3927                    userId, UserHandle.getAppId(callingUid), ps.appId);
3928        }
3929        return false;
3930    }
3931
3932    /**
3933     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3934     */
3935    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3936        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3937    }
3938
3939    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3940            int flags) {
3941        // Callers can access only the libs they depend on, otherwise they need to explicitly
3942        // ask for the shared libraries given the caller is allowed to access all static libs.
3943        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3944            // System/shell/root get to see all static libs
3945            final int appId = UserHandle.getAppId(uid);
3946            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3947                    || appId == Process.ROOT_UID) {
3948                return false;
3949            }
3950        }
3951
3952        // No package means no static lib as it is always on internal storage
3953        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3954            return false;
3955        }
3956
3957        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3958                ps.pkg.staticSharedLibVersion);
3959        if (libEntry == null) {
3960            return false;
3961        }
3962
3963        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3964        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3965        if (uidPackageNames == null) {
3966            return true;
3967        }
3968
3969        for (String uidPackageName : uidPackageNames) {
3970            if (ps.name.equals(uidPackageName)) {
3971                return false;
3972            }
3973            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3974            if (uidPs != null) {
3975                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3976                        libEntry.info.getName());
3977                if (index < 0) {
3978                    continue;
3979                }
3980                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3981                    return false;
3982                }
3983            }
3984        }
3985        return true;
3986    }
3987
3988    @Override
3989    public String[] currentToCanonicalPackageNames(String[] names) {
3990        final int callingUid = Binder.getCallingUid();
3991        if (getInstantAppPackageName(callingUid) != null) {
3992            return names;
3993        }
3994        final String[] out = new String[names.length];
3995        // reader
3996        synchronized (mPackages) {
3997            final int callingUserId = UserHandle.getUserId(callingUid);
3998            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3999            for (int i=names.length-1; i>=0; i--) {
4000                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4001                boolean translateName = false;
4002                if (ps != null && ps.realName != null) {
4003                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4004                    translateName = !targetIsInstantApp
4005                            || canViewInstantApps
4006                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4007                                    UserHandle.getAppId(callingUid), ps.appId);
4008                }
4009                out[i] = translateName ? ps.realName : names[i];
4010            }
4011        }
4012        return out;
4013    }
4014
4015    @Override
4016    public String[] canonicalToCurrentPackageNames(String[] names) {
4017        final int callingUid = Binder.getCallingUid();
4018        if (getInstantAppPackageName(callingUid) != null) {
4019            return names;
4020        }
4021        final String[] out = new String[names.length];
4022        // reader
4023        synchronized (mPackages) {
4024            final int callingUserId = UserHandle.getUserId(callingUid);
4025            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4026            for (int i=names.length-1; i>=0; i--) {
4027                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4028                boolean translateName = false;
4029                if (cur != null) {
4030                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4031                    final boolean targetIsInstantApp =
4032                            ps != null && ps.getInstantApp(callingUserId);
4033                    translateName = !targetIsInstantApp
4034                            || canViewInstantApps
4035                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4036                                    UserHandle.getAppId(callingUid), ps.appId);
4037                }
4038                out[i] = translateName ? cur : names[i];
4039            }
4040        }
4041        return out;
4042    }
4043
4044    @Override
4045    public int getPackageUid(String packageName, int flags, int userId) {
4046        if (!sUserManager.exists(userId)) return -1;
4047        final int callingUid = Binder.getCallingUid();
4048        flags = updateFlagsForPackage(flags, userId, packageName);
4049        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4050                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4051
4052        // reader
4053        synchronized (mPackages) {
4054            final PackageParser.Package p = mPackages.get(packageName);
4055            if (p != null && p.isMatch(flags)) {
4056                PackageSetting ps = (PackageSetting) p.mExtras;
4057                if (filterAppAccessLPr(ps, callingUid, userId)) {
4058                    return -1;
4059                }
4060                return UserHandle.getUid(userId, p.applicationInfo.uid);
4061            }
4062            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4063                final PackageSetting ps = mSettings.mPackages.get(packageName);
4064                if (ps != null && ps.isMatch(flags)
4065                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4066                    return UserHandle.getUid(userId, ps.appId);
4067                }
4068            }
4069        }
4070
4071        return -1;
4072    }
4073
4074    @Override
4075    public int[] getPackageGids(String packageName, int flags, int userId) {
4076        if (!sUserManager.exists(userId)) return null;
4077        final int callingUid = Binder.getCallingUid();
4078        flags = updateFlagsForPackage(flags, userId, packageName);
4079        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4080                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4081
4082        // reader
4083        synchronized (mPackages) {
4084            final PackageParser.Package p = mPackages.get(packageName);
4085            if (p != null && p.isMatch(flags)) {
4086                PackageSetting ps = (PackageSetting) p.mExtras;
4087                if (filterAppAccessLPr(ps, callingUid, userId)) {
4088                    return null;
4089                }
4090                // TODO: Shouldn't this be checking for package installed state for userId and
4091                // return null?
4092                return ps.getPermissionsState().computeGids(userId);
4093            }
4094            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4095                final PackageSetting ps = mSettings.mPackages.get(packageName);
4096                if (ps != null && ps.isMatch(flags)
4097                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4098                    return ps.getPermissionsState().computeGids(userId);
4099                }
4100            }
4101        }
4102
4103        return null;
4104    }
4105
4106    @Override
4107    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4108        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4109    }
4110
4111    @Override
4112    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4113            int flags) {
4114        final List<PermissionInfo> permissionList =
4115                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4116        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4117    }
4118
4119    @Override
4120    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4121        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4122    }
4123
4124    @Override
4125    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4126        final List<PermissionGroupInfo> permissionList =
4127                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4128        return (permissionList == null)
4129                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4130    }
4131
4132    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4133            int filterCallingUid, int userId) {
4134        if (!sUserManager.exists(userId)) return null;
4135        PackageSetting ps = mSettings.mPackages.get(packageName);
4136        if (ps != null) {
4137            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4138                return null;
4139            }
4140            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4141                return null;
4142            }
4143            if (ps.pkg == null) {
4144                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4145                if (pInfo != null) {
4146                    return pInfo.applicationInfo;
4147                }
4148                return null;
4149            }
4150            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4151                    ps.readUserState(userId), userId);
4152            if (ai != null) {
4153                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4154            }
4155            return ai;
4156        }
4157        return null;
4158    }
4159
4160    @Override
4161    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4162        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4163    }
4164
4165    /**
4166     * Important: The provided filterCallingUid is used exclusively to filter out applications
4167     * that can be seen based on user state. It's typically the original caller uid prior
4168     * to clearing. Because it can only be provided by trusted code, it's value can be
4169     * trusted and will be used as-is; unlike userId which will be validated by this method.
4170     */
4171    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4172            int filterCallingUid, int userId) {
4173        if (!sUserManager.exists(userId)) return null;
4174        flags = updateFlagsForApplication(flags, userId, packageName);
4175        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4176                false /* requireFullPermission */, false /* checkShell */, "get application info");
4177
4178        // writer
4179        synchronized (mPackages) {
4180            // Normalize package name to handle renamed packages and static libs
4181            packageName = resolveInternalPackageNameLPr(packageName,
4182                    PackageManager.VERSION_CODE_HIGHEST);
4183
4184            PackageParser.Package p = mPackages.get(packageName);
4185            if (DEBUG_PACKAGE_INFO) Log.v(
4186                    TAG, "getApplicationInfo " + packageName
4187                    + ": " + p);
4188            if (p != null) {
4189                PackageSetting ps = mSettings.mPackages.get(packageName);
4190                if (ps == null) return null;
4191                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4192                    return null;
4193                }
4194                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4195                    return null;
4196                }
4197                // Note: isEnabledLP() does not apply here - always return info
4198                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4199                        p, flags, ps.readUserState(userId), userId);
4200                if (ai != null) {
4201                    ai.packageName = resolveExternalPackageNameLPr(p);
4202                }
4203                return ai;
4204            }
4205            if ("android".equals(packageName)||"system".equals(packageName)) {
4206                return mAndroidApplication;
4207            }
4208            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4209                // Already generates the external package name
4210                return generateApplicationInfoFromSettingsLPw(packageName,
4211                        flags, filterCallingUid, userId);
4212            }
4213        }
4214        return null;
4215    }
4216
4217    private String normalizePackageNameLPr(String packageName) {
4218        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4219        return normalizedPackageName != null ? normalizedPackageName : packageName;
4220    }
4221
4222    @Override
4223    public void deletePreloadsFileCache() {
4224        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4225            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4226        }
4227        File dir = Environment.getDataPreloadsFileCacheDirectory();
4228        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4229        FileUtils.deleteContents(dir);
4230    }
4231
4232    @Override
4233    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4234            final int storageFlags, final IPackageDataObserver observer) {
4235        mContext.enforceCallingOrSelfPermission(
4236                android.Manifest.permission.CLEAR_APP_CACHE, null);
4237        mHandler.post(() -> {
4238            boolean success = false;
4239            try {
4240                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4241                success = true;
4242            } catch (IOException e) {
4243                Slog.w(TAG, e);
4244            }
4245            if (observer != null) {
4246                try {
4247                    observer.onRemoveCompleted(null, success);
4248                } catch (RemoteException e) {
4249                    Slog.w(TAG, e);
4250                }
4251            }
4252        });
4253    }
4254
4255    @Override
4256    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4257            final int storageFlags, final IntentSender pi) {
4258        mContext.enforceCallingOrSelfPermission(
4259                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4260        mHandler.post(() -> {
4261            boolean success = false;
4262            try {
4263                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4264                success = true;
4265            } catch (IOException e) {
4266                Slog.w(TAG, e);
4267            }
4268            if (pi != null) {
4269                try {
4270                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4271                } catch (SendIntentException e) {
4272                    Slog.w(TAG, e);
4273                }
4274            }
4275        });
4276    }
4277
4278    /**
4279     * Blocking call to clear various types of cached data across the system
4280     * until the requested bytes are available.
4281     */
4282    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4283        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4284        final File file = storage.findPathForUuid(volumeUuid);
4285        if (file.getUsableSpace() >= bytes) return;
4286
4287        if (ENABLE_FREE_CACHE_V2) {
4288            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4289                    volumeUuid);
4290            final boolean aggressive = (storageFlags
4291                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4292            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4293
4294            // 1. Pre-flight to determine if we have any chance to succeed
4295            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4296            if (internalVolume && (aggressive || SystemProperties
4297                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4298                deletePreloadsFileCache();
4299                if (file.getUsableSpace() >= bytes) return;
4300            }
4301
4302            // 3. Consider parsed APK data (aggressive only)
4303            if (internalVolume && aggressive) {
4304                FileUtils.deleteContents(mCacheDir);
4305                if (file.getUsableSpace() >= bytes) return;
4306            }
4307
4308            // 4. Consider cached app data (above quotas)
4309            try {
4310                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4311                        Installer.FLAG_FREE_CACHE_V2);
4312            } catch (InstallerException ignored) {
4313            }
4314            if (file.getUsableSpace() >= bytes) return;
4315
4316            // 5. Consider shared libraries with refcount=0 and age>min cache period
4317            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4318                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4319                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4320                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4321                return;
4322            }
4323
4324            // 6. Consider dexopt output (aggressive only)
4325            // TODO: Implement
4326
4327            // 7. Consider installed instant apps unused longer than min cache period
4328            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4329                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4330                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4331                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4332                return;
4333            }
4334
4335            // 8. Consider cached app data (below quotas)
4336            try {
4337                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4338                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4339            } catch (InstallerException ignored) {
4340            }
4341            if (file.getUsableSpace() >= bytes) return;
4342
4343            // 9. Consider DropBox entries
4344            // TODO: Implement
4345
4346            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4347            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4348                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4349                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4350                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4351                return;
4352            }
4353        } else {
4354            try {
4355                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4356            } catch (InstallerException ignored) {
4357            }
4358            if (file.getUsableSpace() >= bytes) return;
4359        }
4360
4361        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4362    }
4363
4364    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4365            throws IOException {
4366        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4367        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4368
4369        List<VersionedPackage> packagesToDelete = null;
4370        final long now = System.currentTimeMillis();
4371
4372        synchronized (mPackages) {
4373            final int[] allUsers = sUserManager.getUserIds();
4374            final int libCount = mSharedLibraries.size();
4375            for (int i = 0; i < libCount; i++) {
4376                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4377                if (versionedLib == null) {
4378                    continue;
4379                }
4380                final int versionCount = versionedLib.size();
4381                for (int j = 0; j < versionCount; j++) {
4382                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4383                    // Skip packages that are not static shared libs.
4384                    if (!libInfo.isStatic()) {
4385                        break;
4386                    }
4387                    // Important: We skip static shared libs used for some user since
4388                    // in such a case we need to keep the APK on the device. The check for
4389                    // a lib being used for any user is performed by the uninstall call.
4390                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4391                    // Resolve the package name - we use synthetic package names internally
4392                    final String internalPackageName = resolveInternalPackageNameLPr(
4393                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4394                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4395                    // Skip unused static shared libs cached less than the min period
4396                    // to prevent pruning a lib needed by a subsequently installed package.
4397                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4398                        continue;
4399                    }
4400                    if (packagesToDelete == null) {
4401                        packagesToDelete = new ArrayList<>();
4402                    }
4403                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4404                            declaringPackage.getVersionCode()));
4405                }
4406            }
4407        }
4408
4409        if (packagesToDelete != null) {
4410            final int packageCount = packagesToDelete.size();
4411            for (int i = 0; i < packageCount; i++) {
4412                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4413                // Delete the package synchronously (will fail of the lib used for any user).
4414                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4415                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4416                                == PackageManager.DELETE_SUCCEEDED) {
4417                    if (volume.getUsableSpace() >= neededSpace) {
4418                        return true;
4419                    }
4420                }
4421            }
4422        }
4423
4424        return false;
4425    }
4426
4427    /**
4428     * Update given flags based on encryption status of current user.
4429     */
4430    private int updateFlags(int flags, int userId) {
4431        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4432                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4433            // Caller expressed an explicit opinion about what encryption
4434            // aware/unaware components they want to see, so fall through and
4435            // give them what they want
4436        } else {
4437            // Caller expressed no opinion, so match based on user state
4438            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4439                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4440            } else {
4441                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4442            }
4443        }
4444        return flags;
4445    }
4446
4447    private UserManagerInternal getUserManagerInternal() {
4448        if (mUserManagerInternal == null) {
4449            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4450        }
4451        return mUserManagerInternal;
4452    }
4453
4454    private DeviceIdleController.LocalService getDeviceIdleController() {
4455        if (mDeviceIdleController == null) {
4456            mDeviceIdleController =
4457                    LocalServices.getService(DeviceIdleController.LocalService.class);
4458        }
4459        return mDeviceIdleController;
4460    }
4461
4462    /**
4463     * Update given flags when being used to request {@link PackageInfo}.
4464     */
4465    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4466        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4467        boolean triaged = true;
4468        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4469                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4470            // Caller is asking for component details, so they'd better be
4471            // asking for specific encryption matching behavior, or be triaged
4472            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4473                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4474                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4475                triaged = false;
4476            }
4477        }
4478        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4479                | PackageManager.MATCH_SYSTEM_ONLY
4480                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4481            triaged = false;
4482        }
4483        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4484            mPermissionManager.enforceCrossUserPermission(
4485                    Binder.getCallingUid(), userId, false, false,
4486                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4487                    + Debug.getCallers(5));
4488        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4489                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4490            // If the caller wants all packages and has a restricted profile associated with it,
4491            // then match all users. This is to make sure that launchers that need to access work
4492            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4493            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4494            flags |= PackageManager.MATCH_ANY_USER;
4495        }
4496        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4497            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4498                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4499        }
4500        return updateFlags(flags, userId);
4501    }
4502
4503    /**
4504     * Update given flags when being used to request {@link ApplicationInfo}.
4505     */
4506    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4507        return updateFlagsForPackage(flags, userId, cookie);
4508    }
4509
4510    /**
4511     * Update given flags when being used to request {@link ComponentInfo}.
4512     */
4513    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4514        if (cookie instanceof Intent) {
4515            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4516                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4517            }
4518        }
4519
4520        boolean triaged = true;
4521        // Caller is asking for component details, so they'd better be
4522        // asking for specific encryption matching behavior, or be triaged
4523        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4524                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4525                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4526            triaged = false;
4527        }
4528        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4529            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4530                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4531        }
4532
4533        return updateFlags(flags, userId);
4534    }
4535
4536    /**
4537     * Update given intent when being used to request {@link ResolveInfo}.
4538     */
4539    private Intent updateIntentForResolve(Intent intent) {
4540        if (intent.getSelector() != null) {
4541            intent = intent.getSelector();
4542        }
4543        if (DEBUG_PREFERRED) {
4544            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4545        }
4546        return intent;
4547    }
4548
4549    /**
4550     * Update given flags when being used to request {@link ResolveInfo}.
4551     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4552     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4553     * flag set. However, this flag is only honoured in three circumstances:
4554     * <ul>
4555     * <li>when called from a system process</li>
4556     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4557     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4558     * action and a {@code android.intent.category.BROWSABLE} category</li>
4559     * </ul>
4560     */
4561    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4562        return updateFlagsForResolve(flags, userId, intent, callingUid,
4563                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4564    }
4565    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4566            boolean wantInstantApps) {
4567        return updateFlagsForResolve(flags, userId, intent, callingUid,
4568                wantInstantApps, false /*onlyExposedExplicitly*/);
4569    }
4570    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4571            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4572        // Safe mode means we shouldn't match any third-party components
4573        if (mSafeMode) {
4574            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4575        }
4576        if (getInstantAppPackageName(callingUid) != null) {
4577            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4578            if (onlyExposedExplicitly) {
4579                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4580            }
4581            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4582            flags |= PackageManager.MATCH_INSTANT;
4583        } else {
4584            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4585            final boolean allowMatchInstant =
4586                    (wantInstantApps
4587                            && Intent.ACTION_VIEW.equals(intent.getAction())
4588                            && hasWebURI(intent))
4589                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4590            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4591                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4592            if (!allowMatchInstant) {
4593                flags &= ~PackageManager.MATCH_INSTANT;
4594            }
4595        }
4596        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4597    }
4598
4599    @Override
4600    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4601        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4602    }
4603
4604    /**
4605     * Important: The provided filterCallingUid is used exclusively to filter out activities
4606     * that can be seen based on user state. It's typically the original caller uid prior
4607     * to clearing. Because it can only be provided by trusted code, it's value can be
4608     * trusted and will be used as-is; unlike userId which will be validated by this method.
4609     */
4610    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4611            int filterCallingUid, int userId) {
4612        if (!sUserManager.exists(userId)) return null;
4613        flags = updateFlagsForComponent(flags, userId, component);
4614        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4615                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4616        synchronized (mPackages) {
4617            PackageParser.Activity a = mActivities.mActivities.get(component);
4618
4619            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4620            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4622                if (ps == null) return null;
4623                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4624                    return null;
4625                }
4626                return PackageParser.generateActivityInfo(
4627                        a, flags, ps.readUserState(userId), userId);
4628            }
4629            if (mResolveComponentName.equals(component)) {
4630                return PackageParser.generateActivityInfo(
4631                        mResolveActivity, flags, new PackageUserState(), userId);
4632            }
4633        }
4634        return null;
4635    }
4636
4637    @Override
4638    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4639            String resolvedType) {
4640        synchronized (mPackages) {
4641            if (component.equals(mResolveComponentName)) {
4642                // The resolver supports EVERYTHING!
4643                return true;
4644            }
4645            final int callingUid = Binder.getCallingUid();
4646            final int callingUserId = UserHandle.getUserId(callingUid);
4647            PackageParser.Activity a = mActivities.mActivities.get(component);
4648            if (a == null) {
4649                return false;
4650            }
4651            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4652            if (ps == null) {
4653                return false;
4654            }
4655            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4656                return false;
4657            }
4658            for (int i=0; i<a.intents.size(); i++) {
4659                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4660                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4661                    return true;
4662                }
4663            }
4664            return false;
4665        }
4666    }
4667
4668    @Override
4669    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4670        if (!sUserManager.exists(userId)) return null;
4671        final int callingUid = Binder.getCallingUid();
4672        flags = updateFlagsForComponent(flags, userId, component);
4673        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4674                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4675        synchronized (mPackages) {
4676            PackageParser.Activity a = mReceivers.mActivities.get(component);
4677            if (DEBUG_PACKAGE_INFO) Log.v(
4678                TAG, "getReceiverInfo " + 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, callingUid, component, TYPE_RECEIVER, userId)) {
4683                    return null;
4684                }
4685                return PackageParser.generateActivityInfo(
4686                        a, flags, ps.readUserState(userId), userId);
4687            }
4688        }
4689        return null;
4690    }
4691
4692    @Override
4693    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4694            int flags, int userId) {
4695        if (!sUserManager.exists(userId)) return null;
4696        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4697        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4698            return null;
4699        }
4700
4701        flags = updateFlagsForPackage(flags, userId, null);
4702
4703        final boolean canSeeStaticLibraries =
4704                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4705                        == PERMISSION_GRANTED
4706                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4707                        == PERMISSION_GRANTED
4708                || canRequestPackageInstallsInternal(packageName,
4709                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4710                        false  /* throwIfPermNotDeclared*/)
4711                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4712                        == PERMISSION_GRANTED;
4713
4714        synchronized (mPackages) {
4715            List<SharedLibraryInfo> result = null;
4716
4717            final int libCount = mSharedLibraries.size();
4718            for (int i = 0; i < libCount; i++) {
4719                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4720                if (versionedLib == null) {
4721                    continue;
4722                }
4723
4724                final int versionCount = versionedLib.size();
4725                for (int j = 0; j < versionCount; j++) {
4726                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4727                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4728                        break;
4729                    }
4730                    final long identity = Binder.clearCallingIdentity();
4731                    try {
4732                        PackageInfo packageInfo = getPackageInfoVersioned(
4733                                libInfo.getDeclaringPackage(), flags
4734                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4735                        if (packageInfo == null) {
4736                            continue;
4737                        }
4738                    } finally {
4739                        Binder.restoreCallingIdentity(identity);
4740                    }
4741
4742                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4743                            libInfo.getVersion(), libInfo.getType(),
4744                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4745                            flags, userId));
4746
4747                    if (result == null) {
4748                        result = new ArrayList<>();
4749                    }
4750                    result.add(resLibInfo);
4751                }
4752            }
4753
4754            return result != null ? new ParceledListSlice<>(result) : null;
4755        }
4756    }
4757
4758    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4759            SharedLibraryInfo libInfo, int flags, int userId) {
4760        List<VersionedPackage> versionedPackages = null;
4761        final int packageCount = mSettings.mPackages.size();
4762        for (int i = 0; i < packageCount; i++) {
4763            PackageSetting ps = mSettings.mPackages.valueAt(i);
4764
4765            if (ps == null) {
4766                continue;
4767            }
4768
4769            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4770                continue;
4771            }
4772
4773            final String libName = libInfo.getName();
4774            if (libInfo.isStatic()) {
4775                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4776                if (libIdx < 0) {
4777                    continue;
4778                }
4779                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4780                    continue;
4781                }
4782                if (versionedPackages == null) {
4783                    versionedPackages = new ArrayList<>();
4784                }
4785                // If the dependent is a static shared lib, use the public package name
4786                String dependentPackageName = ps.name;
4787                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4788                    dependentPackageName = ps.pkg.manifestPackageName;
4789                }
4790                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4791            } else if (ps.pkg != null) {
4792                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4793                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4794                    if (versionedPackages == null) {
4795                        versionedPackages = new ArrayList<>();
4796                    }
4797                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4798                }
4799            }
4800        }
4801
4802        return versionedPackages;
4803    }
4804
4805    @Override
4806    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4807        if (!sUserManager.exists(userId)) return null;
4808        final int callingUid = Binder.getCallingUid();
4809        flags = updateFlagsForComponent(flags, userId, component);
4810        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4811                false /* requireFullPermission */, false /* checkShell */, "get service info");
4812        synchronized (mPackages) {
4813            PackageParser.Service s = mServices.mServices.get(component);
4814            if (DEBUG_PACKAGE_INFO) Log.v(
4815                TAG, "getServiceInfo " + component + ": " + s);
4816            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4817                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4818                if (ps == null) return null;
4819                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4820                    return null;
4821                }
4822                return PackageParser.generateServiceInfo(
4823                        s, flags, ps.readUserState(userId), userId);
4824            }
4825        }
4826        return null;
4827    }
4828
4829    @Override
4830    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4831        if (!sUserManager.exists(userId)) return null;
4832        final int callingUid = Binder.getCallingUid();
4833        flags = updateFlagsForComponent(flags, userId, component);
4834        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4835                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4836        synchronized (mPackages) {
4837            PackageParser.Provider p = mProviders.mProviders.get(component);
4838            if (DEBUG_PACKAGE_INFO) Log.v(
4839                TAG, "getProviderInfo " + component + ": " + p);
4840            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4841                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4842                if (ps == null) return null;
4843                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4844                    return null;
4845                }
4846                return PackageParser.generateProviderInfo(
4847                        p, flags, ps.readUserState(userId), userId);
4848            }
4849        }
4850        return null;
4851    }
4852
4853    @Override
4854    public String[] getSystemSharedLibraryNames() {
4855        // allow instant applications
4856        synchronized (mPackages) {
4857            Set<String> libs = null;
4858            final int libCount = mSharedLibraries.size();
4859            for (int i = 0; i < libCount; i++) {
4860                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4861                if (versionedLib == null) {
4862                    continue;
4863                }
4864                final int versionCount = versionedLib.size();
4865                for (int j = 0; j < versionCount; j++) {
4866                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4867                    if (!libEntry.info.isStatic()) {
4868                        if (libs == null) {
4869                            libs = new ArraySet<>();
4870                        }
4871                        libs.add(libEntry.info.getName());
4872                        break;
4873                    }
4874                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4875                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4876                            UserHandle.getUserId(Binder.getCallingUid()),
4877                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4878                        if (libs == null) {
4879                            libs = new ArraySet<>();
4880                        }
4881                        libs.add(libEntry.info.getName());
4882                        break;
4883                    }
4884                }
4885            }
4886
4887            if (libs != null) {
4888                String[] libsArray = new String[libs.size()];
4889                libs.toArray(libsArray);
4890                return libsArray;
4891            }
4892
4893            return null;
4894        }
4895    }
4896
4897    @Override
4898    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4899        // allow instant applications
4900        synchronized (mPackages) {
4901            return mServicesSystemSharedLibraryPackageName;
4902        }
4903    }
4904
4905    @Override
4906    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4907        // allow instant applications
4908        synchronized (mPackages) {
4909            return mSharedSystemSharedLibraryPackageName;
4910        }
4911    }
4912
4913    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4914        for (int i = userList.length - 1; i >= 0; --i) {
4915            final int userId = userList[i];
4916            // don't add instant app to the list of updates
4917            if (pkgSetting.getInstantApp(userId)) {
4918                continue;
4919            }
4920            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4921            if (changedPackages == null) {
4922                changedPackages = new SparseArray<>();
4923                mChangedPackages.put(userId, changedPackages);
4924            }
4925            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4926            if (sequenceNumbers == null) {
4927                sequenceNumbers = new HashMap<>();
4928                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4929            }
4930            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4931            if (sequenceNumber != null) {
4932                changedPackages.remove(sequenceNumber);
4933            }
4934            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4935            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4936        }
4937        mChangedPackagesSequenceNumber++;
4938    }
4939
4940    @Override
4941    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4942        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4943            return null;
4944        }
4945        synchronized (mPackages) {
4946            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4947                return null;
4948            }
4949            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4950            if (changedPackages == null) {
4951                return null;
4952            }
4953            final List<String> packageNames =
4954                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4955            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4956                final String packageName = changedPackages.get(i);
4957                if (packageName != null) {
4958                    packageNames.add(packageName);
4959                }
4960            }
4961            return packageNames.isEmpty()
4962                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4963        }
4964    }
4965
4966    @Override
4967    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4968        // allow instant applications
4969        ArrayList<FeatureInfo> res;
4970        synchronized (mAvailableFeatures) {
4971            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4972            res.addAll(mAvailableFeatures.values());
4973        }
4974        final FeatureInfo fi = new FeatureInfo();
4975        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4976                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4977        res.add(fi);
4978
4979        return new ParceledListSlice<>(res);
4980    }
4981
4982    @Override
4983    public boolean hasSystemFeature(String name, int version) {
4984        // allow instant applications
4985        synchronized (mAvailableFeatures) {
4986            final FeatureInfo feat = mAvailableFeatures.get(name);
4987            if (feat == null) {
4988                return false;
4989            } else {
4990                return feat.version >= version;
4991            }
4992        }
4993    }
4994
4995    @Override
4996    public int checkPermission(String permName, String pkgName, int userId) {
4997        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
4998    }
4999
5000    @Override
5001    public int checkUidPermission(String permName, int uid) {
5002        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5003    }
5004
5005    @Override
5006    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5007        if (UserHandle.getCallingUserId() != userId) {
5008            mContext.enforceCallingPermission(
5009                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5010                    "isPermissionRevokedByPolicy for user " + userId);
5011        }
5012
5013        if (checkPermission(permission, packageName, userId)
5014                == PackageManager.PERMISSION_GRANTED) {
5015            return false;
5016        }
5017
5018        final int callingUid = Binder.getCallingUid();
5019        if (getInstantAppPackageName(callingUid) != null) {
5020            if (!isCallerSameApp(packageName, callingUid)) {
5021                return false;
5022            }
5023        } else {
5024            if (isInstantApp(packageName, userId)) {
5025                return false;
5026            }
5027        }
5028
5029        final long identity = Binder.clearCallingIdentity();
5030        try {
5031            final int flags = getPermissionFlags(permission, packageName, userId);
5032            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5033        } finally {
5034            Binder.restoreCallingIdentity(identity);
5035        }
5036    }
5037
5038    @Override
5039    public String getPermissionControllerPackageName() {
5040        synchronized (mPackages) {
5041            return mRequiredInstallerPackage;
5042        }
5043    }
5044
5045    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5046        return mPermissionManager.addDynamicPermission(
5047                info, async, getCallingUid(), new PermissionCallback() {
5048                    @Override
5049                    public void onPermissionChanged() {
5050                        if (!async) {
5051                            mSettings.writeLPr();
5052                        } else {
5053                            scheduleWriteSettingsLocked();
5054                        }
5055                    }
5056                });
5057    }
5058
5059    @Override
5060    public boolean addPermission(PermissionInfo info) {
5061        synchronized (mPackages) {
5062            return addDynamicPermission(info, false);
5063        }
5064    }
5065
5066    @Override
5067    public boolean addPermissionAsync(PermissionInfo info) {
5068        synchronized (mPackages) {
5069            return addDynamicPermission(info, true);
5070        }
5071    }
5072
5073    @Override
5074    public void removePermission(String permName) {
5075        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5076    }
5077
5078    @Override
5079    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5080        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5081                getCallingUid(), userId, mPermissionCallback);
5082    }
5083
5084    @Override
5085    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5086        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5087                getCallingUid(), userId, mPermissionCallback);
5088    }
5089
5090    @Override
5091    public void resetRuntimePermissions() {
5092        mContext.enforceCallingOrSelfPermission(
5093                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5094                "revokeRuntimePermission");
5095
5096        int callingUid = Binder.getCallingUid();
5097        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5098            mContext.enforceCallingOrSelfPermission(
5099                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5100                    "resetRuntimePermissions");
5101        }
5102
5103        synchronized (mPackages) {
5104            mPermissionManager.updateAllPermissions(
5105                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5106                    mPermissionCallback);
5107            for (int userId : UserManagerService.getInstance().getUserIds()) {
5108                final int packageCount = mPackages.size();
5109                for (int i = 0; i < packageCount; i++) {
5110                    PackageParser.Package pkg = mPackages.valueAt(i);
5111                    if (!(pkg.mExtras instanceof PackageSetting)) {
5112                        continue;
5113                    }
5114                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5115                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5116                }
5117            }
5118        }
5119    }
5120
5121    @Override
5122    public int getPermissionFlags(String permName, String packageName, int userId) {
5123        return mPermissionManager.getPermissionFlags(
5124                permName, packageName, getCallingUid(), userId);
5125    }
5126
5127    @Override
5128    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5129            int flagValues, int userId) {
5130        mPermissionManager.updatePermissionFlags(
5131                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5132                mPermissionCallback);
5133    }
5134
5135    /**
5136     * Update the permission flags for all packages and runtime permissions of a user in order
5137     * to allow device or profile owner to remove POLICY_FIXED.
5138     */
5139    @Override
5140    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5141        synchronized (mPackages) {
5142            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5143                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5144                    mPermissionCallback);
5145            if (changed) {
5146                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5147            }
5148        }
5149    }
5150
5151    @Override
5152    public boolean shouldShowRequestPermissionRationale(String permissionName,
5153            String packageName, int userId) {
5154        if (UserHandle.getCallingUserId() != userId) {
5155            mContext.enforceCallingPermission(
5156                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5157                    "canShowRequestPermissionRationale for user " + userId);
5158        }
5159
5160        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5161        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5162            return false;
5163        }
5164
5165        if (checkPermission(permissionName, packageName, userId)
5166                == PackageManager.PERMISSION_GRANTED) {
5167            return false;
5168        }
5169
5170        final int flags;
5171
5172        final long identity = Binder.clearCallingIdentity();
5173        try {
5174            flags = getPermissionFlags(permissionName,
5175                    packageName, userId);
5176        } finally {
5177            Binder.restoreCallingIdentity(identity);
5178        }
5179
5180        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5181                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5182                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5183
5184        if ((flags & fixedFlags) != 0) {
5185            return false;
5186        }
5187
5188        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5189    }
5190
5191    @Override
5192    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5193        mContext.enforceCallingOrSelfPermission(
5194                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5195                "addOnPermissionsChangeListener");
5196
5197        synchronized (mPackages) {
5198            mOnPermissionChangeListeners.addListenerLocked(listener);
5199        }
5200    }
5201
5202    @Override
5203    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5204        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5205            throw new SecurityException("Instant applications don't have access to this method");
5206        }
5207        synchronized (mPackages) {
5208            mOnPermissionChangeListeners.removeListenerLocked(listener);
5209        }
5210    }
5211
5212    @Override
5213    public boolean isProtectedBroadcast(String actionName) {
5214        // allow instant applications
5215        synchronized (mProtectedBroadcasts) {
5216            if (mProtectedBroadcasts.contains(actionName)) {
5217                return true;
5218            } else if (actionName != null) {
5219                // TODO: remove these terrible hacks
5220                if (actionName.startsWith("android.net.netmon.lingerExpired")
5221                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5222                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5223                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5224                    return true;
5225                }
5226            }
5227        }
5228        return false;
5229    }
5230
5231    @Override
5232    public int checkSignatures(String pkg1, String pkg2) {
5233        synchronized (mPackages) {
5234            final PackageParser.Package p1 = mPackages.get(pkg1);
5235            final PackageParser.Package p2 = mPackages.get(pkg2);
5236            if (p1 == null || p1.mExtras == null
5237                    || p2 == null || p2.mExtras == null) {
5238                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5239            }
5240            final int callingUid = Binder.getCallingUid();
5241            final int callingUserId = UserHandle.getUserId(callingUid);
5242            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5243            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5244            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5245                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5246                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5247            }
5248            return compareSignatures(p1.mSignatures, p2.mSignatures);
5249        }
5250    }
5251
5252    @Override
5253    public int checkUidSignatures(int uid1, int uid2) {
5254        final int callingUid = Binder.getCallingUid();
5255        final int callingUserId = UserHandle.getUserId(callingUid);
5256        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5257        // Map to base uids.
5258        uid1 = UserHandle.getAppId(uid1);
5259        uid2 = UserHandle.getAppId(uid2);
5260        // reader
5261        synchronized (mPackages) {
5262            Signature[] s1;
5263            Signature[] s2;
5264            Object obj = mSettings.getUserIdLPr(uid1);
5265            if (obj != null) {
5266                if (obj instanceof SharedUserSetting) {
5267                    if (isCallerInstantApp) {
5268                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5269                    }
5270                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5271                } else if (obj instanceof PackageSetting) {
5272                    final PackageSetting ps = (PackageSetting) obj;
5273                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5274                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5275                    }
5276                    s1 = ps.signatures.mSignatures;
5277                } else {
5278                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5279                }
5280            } else {
5281                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5282            }
5283            obj = mSettings.getUserIdLPr(uid2);
5284            if (obj != null) {
5285                if (obj instanceof SharedUserSetting) {
5286                    if (isCallerInstantApp) {
5287                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5288                    }
5289                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5290                } else if (obj instanceof PackageSetting) {
5291                    final PackageSetting ps = (PackageSetting) obj;
5292                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5293                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5294                    }
5295                    s2 = ps.signatures.mSignatures;
5296                } else {
5297                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5298                }
5299            } else {
5300                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5301            }
5302            return compareSignatures(s1, s2);
5303        }
5304    }
5305
5306    /**
5307     * This method should typically only be used when granting or revoking
5308     * permissions, since the app may immediately restart after this call.
5309     * <p>
5310     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5311     * guard your work against the app being relaunched.
5312     */
5313    private void killUid(int appId, int userId, String reason) {
5314        final long identity = Binder.clearCallingIdentity();
5315        try {
5316            IActivityManager am = ActivityManager.getService();
5317            if (am != null) {
5318                try {
5319                    am.killUid(appId, userId, reason);
5320                } catch (RemoteException e) {
5321                    /* ignore - same process */
5322                }
5323            }
5324        } finally {
5325            Binder.restoreCallingIdentity(identity);
5326        }
5327    }
5328
5329    /**
5330     * If the database version for this type of package (internal storage or
5331     * external storage) is less than the version where package signatures
5332     * were updated, return true.
5333     */
5334    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5335        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5336        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5337    }
5338
5339    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5340        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5341        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5342    }
5343
5344    @Override
5345    public List<String> getAllPackages() {
5346        final int callingUid = Binder.getCallingUid();
5347        final int callingUserId = UserHandle.getUserId(callingUid);
5348        synchronized (mPackages) {
5349            if (canViewInstantApps(callingUid, callingUserId)) {
5350                return new ArrayList<String>(mPackages.keySet());
5351            }
5352            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5353            final List<String> result = new ArrayList<>();
5354            if (instantAppPkgName != null) {
5355                // caller is an instant application; filter unexposed applications
5356                for (PackageParser.Package pkg : mPackages.values()) {
5357                    if (!pkg.visibleToInstantApps) {
5358                        continue;
5359                    }
5360                    result.add(pkg.packageName);
5361                }
5362            } else {
5363                // caller is a normal application; filter instant applications
5364                for (PackageParser.Package pkg : mPackages.values()) {
5365                    final PackageSetting ps =
5366                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5367                    if (ps != null
5368                            && ps.getInstantApp(callingUserId)
5369                            && !mInstantAppRegistry.isInstantAccessGranted(
5370                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5371                        continue;
5372                    }
5373                    result.add(pkg.packageName);
5374                }
5375            }
5376            return result;
5377        }
5378    }
5379
5380    @Override
5381    public String[] getPackagesForUid(int uid) {
5382        final int callingUid = Binder.getCallingUid();
5383        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5384        final int userId = UserHandle.getUserId(uid);
5385        uid = UserHandle.getAppId(uid);
5386        // reader
5387        synchronized (mPackages) {
5388            Object obj = mSettings.getUserIdLPr(uid);
5389            if (obj instanceof SharedUserSetting) {
5390                if (isCallerInstantApp) {
5391                    return null;
5392                }
5393                final SharedUserSetting sus = (SharedUserSetting) obj;
5394                final int N = sus.packages.size();
5395                String[] res = new String[N];
5396                final Iterator<PackageSetting> it = sus.packages.iterator();
5397                int i = 0;
5398                while (it.hasNext()) {
5399                    PackageSetting ps = it.next();
5400                    if (ps.getInstalled(userId)) {
5401                        res[i++] = ps.name;
5402                    } else {
5403                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5404                    }
5405                }
5406                return res;
5407            } else if (obj instanceof PackageSetting) {
5408                final PackageSetting ps = (PackageSetting) obj;
5409                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5410                    return new String[]{ps.name};
5411                }
5412            }
5413        }
5414        return null;
5415    }
5416
5417    @Override
5418    public String getNameForUid(int uid) {
5419        final int callingUid = Binder.getCallingUid();
5420        if (getInstantAppPackageName(callingUid) != null) {
5421            return null;
5422        }
5423        synchronized (mPackages) {
5424            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5425            if (obj instanceof SharedUserSetting) {
5426                final SharedUserSetting sus = (SharedUserSetting) obj;
5427                return sus.name + ":" + sus.userId;
5428            } else if (obj instanceof PackageSetting) {
5429                final PackageSetting ps = (PackageSetting) obj;
5430                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5431                    return null;
5432                }
5433                return ps.name;
5434            }
5435            return null;
5436        }
5437    }
5438
5439    @Override
5440    public String[] getNamesForUids(int[] uids) {
5441        if (uids == null || uids.length == 0) {
5442            return null;
5443        }
5444        final int callingUid = Binder.getCallingUid();
5445        if (getInstantAppPackageName(callingUid) != null) {
5446            return null;
5447        }
5448        final String[] names = new String[uids.length];
5449        synchronized (mPackages) {
5450            for (int i = uids.length - 1; i >= 0; i--) {
5451                final int uid = uids[i];
5452                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5453                if (obj instanceof SharedUserSetting) {
5454                    final SharedUserSetting sus = (SharedUserSetting) obj;
5455                    names[i] = "shared:" + sus.name;
5456                } else if (obj instanceof PackageSetting) {
5457                    final PackageSetting ps = (PackageSetting) obj;
5458                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5459                        names[i] = null;
5460                    } else {
5461                        names[i] = ps.name;
5462                    }
5463                } else {
5464                    names[i] = null;
5465                }
5466            }
5467        }
5468        return names;
5469    }
5470
5471    @Override
5472    public int getUidForSharedUser(String sharedUserName) {
5473        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5474            return -1;
5475        }
5476        if (sharedUserName == null) {
5477            return -1;
5478        }
5479        // reader
5480        synchronized (mPackages) {
5481            SharedUserSetting suid;
5482            try {
5483                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5484                if (suid != null) {
5485                    return suid.userId;
5486                }
5487            } catch (PackageManagerException ignore) {
5488                // can't happen, but, still need to catch it
5489            }
5490            return -1;
5491        }
5492    }
5493
5494    @Override
5495    public int getFlagsForUid(int uid) {
5496        final int callingUid = Binder.getCallingUid();
5497        if (getInstantAppPackageName(callingUid) != null) {
5498            return 0;
5499        }
5500        synchronized (mPackages) {
5501            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5502            if (obj instanceof SharedUserSetting) {
5503                final SharedUserSetting sus = (SharedUserSetting) obj;
5504                return sus.pkgFlags;
5505            } else if (obj instanceof PackageSetting) {
5506                final PackageSetting ps = (PackageSetting) obj;
5507                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5508                    return 0;
5509                }
5510                return ps.pkgFlags;
5511            }
5512        }
5513        return 0;
5514    }
5515
5516    @Override
5517    public int getPrivateFlagsForUid(int uid) {
5518        final int callingUid = Binder.getCallingUid();
5519        if (getInstantAppPackageName(callingUid) != null) {
5520            return 0;
5521        }
5522        synchronized (mPackages) {
5523            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5524            if (obj instanceof SharedUserSetting) {
5525                final SharedUserSetting sus = (SharedUserSetting) obj;
5526                return sus.pkgPrivateFlags;
5527            } else if (obj instanceof PackageSetting) {
5528                final PackageSetting ps = (PackageSetting) obj;
5529                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5530                    return 0;
5531                }
5532                return ps.pkgPrivateFlags;
5533            }
5534        }
5535        return 0;
5536    }
5537
5538    @Override
5539    public boolean isUidPrivileged(int uid) {
5540        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5541            return false;
5542        }
5543        uid = UserHandle.getAppId(uid);
5544        // reader
5545        synchronized (mPackages) {
5546            Object obj = mSettings.getUserIdLPr(uid);
5547            if (obj instanceof SharedUserSetting) {
5548                final SharedUserSetting sus = (SharedUserSetting) obj;
5549                final Iterator<PackageSetting> it = sus.packages.iterator();
5550                while (it.hasNext()) {
5551                    if (it.next().isPrivileged()) {
5552                        return true;
5553                    }
5554                }
5555            } else if (obj instanceof PackageSetting) {
5556                final PackageSetting ps = (PackageSetting) obj;
5557                return ps.isPrivileged();
5558            }
5559        }
5560        return false;
5561    }
5562
5563    @Override
5564    public String[] getAppOpPermissionPackages(String permName) {
5565        return mPermissionManager.getAppOpPermissionPackages(permName);
5566    }
5567
5568    @Override
5569    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5570            int flags, int userId) {
5571        return resolveIntentInternal(
5572                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5573    }
5574
5575    /**
5576     * Normally instant apps can only be resolved when they're visible to the caller.
5577     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5578     * since we need to allow the system to start any installed application.
5579     */
5580    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5581            int flags, int userId, boolean resolveForStart) {
5582        try {
5583            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5584
5585            if (!sUserManager.exists(userId)) return null;
5586            final int callingUid = Binder.getCallingUid();
5587            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5588            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5589                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5590
5591            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5592            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5593                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5594            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5595
5596            final ResolveInfo bestChoice =
5597                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5598            return bestChoice;
5599        } finally {
5600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5601        }
5602    }
5603
5604    @Override
5605    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5606        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5607            throw new SecurityException(
5608                    "findPersistentPreferredActivity can only be run by the system");
5609        }
5610        if (!sUserManager.exists(userId)) {
5611            return null;
5612        }
5613        final int callingUid = Binder.getCallingUid();
5614        intent = updateIntentForResolve(intent);
5615        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5616        final int flags = updateFlagsForResolve(
5617                0, userId, intent, callingUid, false /*includeInstantApps*/);
5618        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5619                userId);
5620        synchronized (mPackages) {
5621            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5622                    userId);
5623        }
5624    }
5625
5626    @Override
5627    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5628            IntentFilter filter, int match, ComponentName activity) {
5629        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5630            return;
5631        }
5632        final int userId = UserHandle.getCallingUserId();
5633        if (DEBUG_PREFERRED) {
5634            Log.v(TAG, "setLastChosenActivity intent=" + intent
5635                + " resolvedType=" + resolvedType
5636                + " flags=" + flags
5637                + " filter=" + filter
5638                + " match=" + match
5639                + " activity=" + activity);
5640            filter.dump(new PrintStreamPrinter(System.out), "    ");
5641        }
5642        intent.setComponent(null);
5643        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5644                userId);
5645        // Find any earlier preferred or last chosen entries and nuke them
5646        findPreferredActivity(intent, resolvedType,
5647                flags, query, 0, false, true, false, userId);
5648        // Add the new activity as the last chosen for this filter
5649        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5650                "Setting last chosen");
5651    }
5652
5653    @Override
5654    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5655        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5656            return null;
5657        }
5658        final int userId = UserHandle.getCallingUserId();
5659        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5660        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5661                userId);
5662        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5663                false, false, false, userId);
5664    }
5665
5666    /**
5667     * Returns whether or not instant apps have been disabled remotely.
5668     */
5669    private boolean isEphemeralDisabled() {
5670        return mEphemeralAppsDisabled;
5671    }
5672
5673    private boolean isInstantAppAllowed(
5674            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5675            boolean skipPackageCheck) {
5676        if (mInstantAppResolverConnection == null) {
5677            return false;
5678        }
5679        if (mInstantAppInstallerActivity == null) {
5680            return false;
5681        }
5682        if (intent.getComponent() != null) {
5683            return false;
5684        }
5685        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5686            return false;
5687        }
5688        if (!skipPackageCheck && intent.getPackage() != null) {
5689            return false;
5690        }
5691        final boolean isWebUri = hasWebURI(intent);
5692        if (!isWebUri || intent.getData().getHost() == null) {
5693            return false;
5694        }
5695        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5696        // Or if there's already an ephemeral app installed that handles the action
5697        synchronized (mPackages) {
5698            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5699            for (int n = 0; n < count; n++) {
5700                final ResolveInfo info = resolvedActivities.get(n);
5701                final String packageName = info.activityInfo.packageName;
5702                final PackageSetting ps = mSettings.mPackages.get(packageName);
5703                if (ps != null) {
5704                    // only check domain verification status if the app is not a browser
5705                    if (!info.handleAllWebDataURI) {
5706                        // Try to get the status from User settings first
5707                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5708                        final int status = (int) (packedStatus >> 32);
5709                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5710                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5711                            if (DEBUG_EPHEMERAL) {
5712                                Slog.v(TAG, "DENY instant app;"
5713                                    + " pkg: " + packageName + ", status: " + status);
5714                            }
5715                            return false;
5716                        }
5717                    }
5718                    if (ps.getInstantApp(userId)) {
5719                        if (DEBUG_EPHEMERAL) {
5720                            Slog.v(TAG, "DENY instant app installed;"
5721                                    + " pkg: " + packageName);
5722                        }
5723                        return false;
5724                    }
5725                }
5726            }
5727        }
5728        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5729        return true;
5730    }
5731
5732    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5733            Intent origIntent, String resolvedType, String callingPackage,
5734            Bundle verificationBundle, int userId) {
5735        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5736                new InstantAppRequest(responseObj, origIntent, resolvedType,
5737                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5738        mHandler.sendMessage(msg);
5739    }
5740
5741    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5742            int flags, List<ResolveInfo> query, int userId) {
5743        if (query != null) {
5744            final int N = query.size();
5745            if (N == 1) {
5746                return query.get(0);
5747            } else if (N > 1) {
5748                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5749                // If there is more than one activity with the same priority,
5750                // then let the user decide between them.
5751                ResolveInfo r0 = query.get(0);
5752                ResolveInfo r1 = query.get(1);
5753                if (DEBUG_INTENT_MATCHING || debug) {
5754                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5755                            + r1.activityInfo.name + "=" + r1.priority);
5756                }
5757                // If the first activity has a higher priority, or a different
5758                // default, then it is always desirable to pick it.
5759                if (r0.priority != r1.priority
5760                        || r0.preferredOrder != r1.preferredOrder
5761                        || r0.isDefault != r1.isDefault) {
5762                    return query.get(0);
5763                }
5764                // If we have saved a preference for a preferred activity for
5765                // this Intent, use that.
5766                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5767                        flags, query, r0.priority, true, false, debug, userId);
5768                if (ri != null) {
5769                    return ri;
5770                }
5771                // If we have an ephemeral app, use it
5772                for (int i = 0; i < N; i++) {
5773                    ri = query.get(i);
5774                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5775                        final String packageName = ri.activityInfo.packageName;
5776                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5777                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5778                        final int status = (int)(packedStatus >> 32);
5779                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5780                            return ri;
5781                        }
5782                    }
5783                }
5784                ri = new ResolveInfo(mResolveInfo);
5785                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5786                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5787                // If all of the options come from the same package, show the application's
5788                // label and icon instead of the generic resolver's.
5789                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5790                // and then throw away the ResolveInfo itself, meaning that the caller loses
5791                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5792                // a fallback for this case; we only set the target package's resources on
5793                // the ResolveInfo, not the ActivityInfo.
5794                final String intentPackage = intent.getPackage();
5795                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5796                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5797                    ri.resolvePackageName = intentPackage;
5798                    if (userNeedsBadging(userId)) {
5799                        ri.noResourceId = true;
5800                    } else {
5801                        ri.icon = appi.icon;
5802                    }
5803                    ri.iconResourceId = appi.icon;
5804                    ri.labelRes = appi.labelRes;
5805                }
5806                ri.activityInfo.applicationInfo = new ApplicationInfo(
5807                        ri.activityInfo.applicationInfo);
5808                if (userId != 0) {
5809                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5810                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5811                }
5812                // Make sure that the resolver is displayable in car mode
5813                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5814                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5815                return ri;
5816            }
5817        }
5818        return null;
5819    }
5820
5821    /**
5822     * Return true if the given list is not empty and all of its contents have
5823     * an activityInfo with the given package name.
5824     */
5825    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5826        if (ArrayUtils.isEmpty(list)) {
5827            return false;
5828        }
5829        for (int i = 0, N = list.size(); i < N; i++) {
5830            final ResolveInfo ri = list.get(i);
5831            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5832            if (ai == null || !packageName.equals(ai.packageName)) {
5833                return false;
5834            }
5835        }
5836        return true;
5837    }
5838
5839    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5840            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5841        final int N = query.size();
5842        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5843                .get(userId);
5844        // Get the list of persistent preferred activities that handle the intent
5845        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5846        List<PersistentPreferredActivity> pprefs = ppir != null
5847                ? ppir.queryIntent(intent, resolvedType,
5848                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5849                        userId)
5850                : null;
5851        if (pprefs != null && pprefs.size() > 0) {
5852            final int M = pprefs.size();
5853            for (int i=0; i<M; i++) {
5854                final PersistentPreferredActivity ppa = pprefs.get(i);
5855                if (DEBUG_PREFERRED || debug) {
5856                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5857                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5858                            + "\n  component=" + ppa.mComponent);
5859                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5860                }
5861                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5862                        flags | MATCH_DISABLED_COMPONENTS, userId);
5863                if (DEBUG_PREFERRED || debug) {
5864                    Slog.v(TAG, "Found persistent preferred activity:");
5865                    if (ai != null) {
5866                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5867                    } else {
5868                        Slog.v(TAG, "  null");
5869                    }
5870                }
5871                if (ai == null) {
5872                    // This previously registered persistent preferred activity
5873                    // component is no longer known. Ignore it and do NOT remove it.
5874                    continue;
5875                }
5876                for (int j=0; j<N; j++) {
5877                    final ResolveInfo ri = query.get(j);
5878                    if (!ri.activityInfo.applicationInfo.packageName
5879                            .equals(ai.applicationInfo.packageName)) {
5880                        continue;
5881                    }
5882                    if (!ri.activityInfo.name.equals(ai.name)) {
5883                        continue;
5884                    }
5885                    //  Found a persistent preference that can handle the intent.
5886                    if (DEBUG_PREFERRED || debug) {
5887                        Slog.v(TAG, "Returning persistent preferred activity: " +
5888                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5889                    }
5890                    return ri;
5891                }
5892            }
5893        }
5894        return null;
5895    }
5896
5897    // TODO: handle preferred activities missing while user has amnesia
5898    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5899            List<ResolveInfo> query, int priority, boolean always,
5900            boolean removeMatches, boolean debug, int userId) {
5901        if (!sUserManager.exists(userId)) return null;
5902        final int callingUid = Binder.getCallingUid();
5903        flags = updateFlagsForResolve(
5904                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5905        intent = updateIntentForResolve(intent);
5906        // writer
5907        synchronized (mPackages) {
5908            // Try to find a matching persistent preferred activity.
5909            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5910                    debug, userId);
5911
5912            // If a persistent preferred activity matched, use it.
5913            if (pri != null) {
5914                return pri;
5915            }
5916
5917            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5918            // Get the list of preferred activities that handle the intent
5919            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5920            List<PreferredActivity> prefs = pir != null
5921                    ? pir.queryIntent(intent, resolvedType,
5922                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5923                            userId)
5924                    : null;
5925            if (prefs != null && prefs.size() > 0) {
5926                boolean changed = false;
5927                try {
5928                    // First figure out how good the original match set is.
5929                    // We will only allow preferred activities that came
5930                    // from the same match quality.
5931                    int match = 0;
5932
5933                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5934
5935                    final int N = query.size();
5936                    for (int j=0; j<N; j++) {
5937                        final ResolveInfo ri = query.get(j);
5938                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5939                                + ": 0x" + Integer.toHexString(match));
5940                        if (ri.match > match) {
5941                            match = ri.match;
5942                        }
5943                    }
5944
5945                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5946                            + Integer.toHexString(match));
5947
5948                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5949                    final int M = prefs.size();
5950                    for (int i=0; i<M; i++) {
5951                        final PreferredActivity pa = prefs.get(i);
5952                        if (DEBUG_PREFERRED || debug) {
5953                            Slog.v(TAG, "Checking PreferredActivity ds="
5954                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5955                                    + "\n  component=" + pa.mPref.mComponent);
5956                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5957                        }
5958                        if (pa.mPref.mMatch != match) {
5959                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5960                                    + Integer.toHexString(pa.mPref.mMatch));
5961                            continue;
5962                        }
5963                        // If it's not an "always" type preferred activity and that's what we're
5964                        // looking for, skip it.
5965                        if (always && !pa.mPref.mAlways) {
5966                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5967                            continue;
5968                        }
5969                        final ActivityInfo ai = getActivityInfo(
5970                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5971                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5972                                userId);
5973                        if (DEBUG_PREFERRED || debug) {
5974                            Slog.v(TAG, "Found preferred activity:");
5975                            if (ai != null) {
5976                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5977                            } else {
5978                                Slog.v(TAG, "  null");
5979                            }
5980                        }
5981                        if (ai == null) {
5982                            // This previously registered preferred activity
5983                            // component is no longer known.  Most likely an update
5984                            // to the app was installed and in the new version this
5985                            // component no longer exists.  Clean it up by removing
5986                            // it from the preferred activities list, and skip it.
5987                            Slog.w(TAG, "Removing dangling preferred activity: "
5988                                    + pa.mPref.mComponent);
5989                            pir.removeFilter(pa);
5990                            changed = true;
5991                            continue;
5992                        }
5993                        for (int j=0; j<N; j++) {
5994                            final ResolveInfo ri = query.get(j);
5995                            if (!ri.activityInfo.applicationInfo.packageName
5996                                    .equals(ai.applicationInfo.packageName)) {
5997                                continue;
5998                            }
5999                            if (!ri.activityInfo.name.equals(ai.name)) {
6000                                continue;
6001                            }
6002
6003                            if (removeMatches) {
6004                                pir.removeFilter(pa);
6005                                changed = true;
6006                                if (DEBUG_PREFERRED) {
6007                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6008                                }
6009                                break;
6010                            }
6011
6012                            // Okay we found a previously set preferred or last chosen app.
6013                            // If the result set is different from when this
6014                            // was created, and is not a subset of the preferred set, we need to
6015                            // clear it and re-ask the user their preference, if we're looking for
6016                            // an "always" type entry.
6017                            if (always && !pa.mPref.sameSet(query)) {
6018                                if (pa.mPref.isSuperset(query)) {
6019                                    // some components of the set are no longer present in
6020                                    // the query, but the preferred activity can still be reused
6021                                    if (DEBUG_PREFERRED) {
6022                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6023                                                + " still valid as only non-preferred components"
6024                                                + " were removed for " + intent + " type "
6025                                                + resolvedType);
6026                                    }
6027                                    // remove obsolete components and re-add the up-to-date filter
6028                                    PreferredActivity freshPa = new PreferredActivity(pa,
6029                                            pa.mPref.mMatch,
6030                                            pa.mPref.discardObsoleteComponents(query),
6031                                            pa.mPref.mComponent,
6032                                            pa.mPref.mAlways);
6033                                    pir.removeFilter(pa);
6034                                    pir.addFilter(freshPa);
6035                                    changed = true;
6036                                } else {
6037                                    Slog.i(TAG,
6038                                            "Result set changed, dropping preferred activity for "
6039                                                    + intent + " type " + resolvedType);
6040                                    if (DEBUG_PREFERRED) {
6041                                        Slog.v(TAG, "Removing preferred activity since set changed "
6042                                                + pa.mPref.mComponent);
6043                                    }
6044                                    pir.removeFilter(pa);
6045                                    // Re-add the filter as a "last chosen" entry (!always)
6046                                    PreferredActivity lastChosen = new PreferredActivity(
6047                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6048                                    pir.addFilter(lastChosen);
6049                                    changed = true;
6050                                    return null;
6051                                }
6052                            }
6053
6054                            // Yay! Either the set matched or we're looking for the last chosen
6055                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6056                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6057                            return ri;
6058                        }
6059                    }
6060                } finally {
6061                    if (changed) {
6062                        if (DEBUG_PREFERRED) {
6063                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6064                        }
6065                        scheduleWritePackageRestrictionsLocked(userId);
6066                    }
6067                }
6068            }
6069        }
6070        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6071        return null;
6072    }
6073
6074    /*
6075     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6076     */
6077    @Override
6078    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6079            int targetUserId) {
6080        mContext.enforceCallingOrSelfPermission(
6081                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6082        List<CrossProfileIntentFilter> matches =
6083                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6084        if (matches != null) {
6085            int size = matches.size();
6086            for (int i = 0; i < size; i++) {
6087                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6088            }
6089        }
6090        if (hasWebURI(intent)) {
6091            // cross-profile app linking works only towards the parent.
6092            final int callingUid = Binder.getCallingUid();
6093            final UserInfo parent = getProfileParent(sourceUserId);
6094            synchronized(mPackages) {
6095                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6096                        false /*includeInstantApps*/);
6097                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6098                        intent, resolvedType, flags, sourceUserId, parent.id);
6099                return xpDomainInfo != null;
6100            }
6101        }
6102        return false;
6103    }
6104
6105    private UserInfo getProfileParent(int userId) {
6106        final long identity = Binder.clearCallingIdentity();
6107        try {
6108            return sUserManager.getProfileParent(userId);
6109        } finally {
6110            Binder.restoreCallingIdentity(identity);
6111        }
6112    }
6113
6114    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6115            String resolvedType, int userId) {
6116        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6117        if (resolver != null) {
6118            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6119        }
6120        return null;
6121    }
6122
6123    @Override
6124    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6125            String resolvedType, int flags, int userId) {
6126        try {
6127            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6128
6129            return new ParceledListSlice<>(
6130                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6131        } finally {
6132            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6133        }
6134    }
6135
6136    /**
6137     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6138     * instant, returns {@code null}.
6139     */
6140    private String getInstantAppPackageName(int callingUid) {
6141        synchronized (mPackages) {
6142            // If the caller is an isolated app use the owner's uid for the lookup.
6143            if (Process.isIsolated(callingUid)) {
6144                callingUid = mIsolatedOwners.get(callingUid);
6145            }
6146            final int appId = UserHandle.getAppId(callingUid);
6147            final Object obj = mSettings.getUserIdLPr(appId);
6148            if (obj instanceof PackageSetting) {
6149                final PackageSetting ps = (PackageSetting) obj;
6150                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6151                return isInstantApp ? ps.pkg.packageName : null;
6152            }
6153        }
6154        return null;
6155    }
6156
6157    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6158            String resolvedType, int flags, int userId) {
6159        return queryIntentActivitiesInternal(
6160                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6161                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6162    }
6163
6164    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6165            String resolvedType, int flags, int filterCallingUid, int userId,
6166            boolean resolveForStart, boolean allowDynamicSplits) {
6167        if (!sUserManager.exists(userId)) return Collections.emptyList();
6168        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6169        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6170                false /* requireFullPermission */, false /* checkShell */,
6171                "query intent activities");
6172        final String pkgName = intent.getPackage();
6173        ComponentName comp = intent.getComponent();
6174        if (comp == null) {
6175            if (intent.getSelector() != null) {
6176                intent = intent.getSelector();
6177                comp = intent.getComponent();
6178            }
6179        }
6180
6181        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6182                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6183        if (comp != null) {
6184            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6185            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6186            if (ai != null) {
6187                // When specifying an explicit component, we prevent the activity from being
6188                // used when either 1) the calling package is normal and the activity is within
6189                // an ephemeral application or 2) the calling package is ephemeral and the
6190                // activity is not visible to ephemeral applications.
6191                final boolean matchInstantApp =
6192                        (flags & PackageManager.MATCH_INSTANT) != 0;
6193                final boolean matchVisibleToInstantAppOnly =
6194                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6195                final boolean matchExplicitlyVisibleOnly =
6196                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6197                final boolean isCallerInstantApp =
6198                        instantAppPkgName != null;
6199                final boolean isTargetSameInstantApp =
6200                        comp.getPackageName().equals(instantAppPkgName);
6201                final boolean isTargetInstantApp =
6202                        (ai.applicationInfo.privateFlags
6203                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6204                final boolean isTargetVisibleToInstantApp =
6205                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6206                final boolean isTargetExplicitlyVisibleToInstantApp =
6207                        isTargetVisibleToInstantApp
6208                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6209                final boolean isTargetHiddenFromInstantApp =
6210                        !isTargetVisibleToInstantApp
6211                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6212                final boolean blockResolution =
6213                        !isTargetSameInstantApp
6214                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6215                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6216                                        && isTargetHiddenFromInstantApp));
6217                if (!blockResolution) {
6218                    final ResolveInfo ri = new ResolveInfo();
6219                    ri.activityInfo = ai;
6220                    list.add(ri);
6221                }
6222            }
6223            return applyPostResolutionFilter(
6224                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6225        }
6226
6227        // reader
6228        boolean sortResult = false;
6229        boolean addEphemeral = false;
6230        List<ResolveInfo> result;
6231        final boolean ephemeralDisabled = isEphemeralDisabled();
6232        synchronized (mPackages) {
6233            if (pkgName == null) {
6234                List<CrossProfileIntentFilter> matchingFilters =
6235                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6236                // Check for results that need to skip the current profile.
6237                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6238                        resolvedType, flags, userId);
6239                if (xpResolveInfo != null) {
6240                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6241                    xpResult.add(xpResolveInfo);
6242                    return applyPostResolutionFilter(
6243                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6244                            allowDynamicSplits, filterCallingUid, userId);
6245                }
6246
6247                // Check for results in the current profile.
6248                result = filterIfNotSystemUser(mActivities.queryIntent(
6249                        intent, resolvedType, flags, userId), userId);
6250                addEphemeral = !ephemeralDisabled
6251                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6252                // Check for cross profile results.
6253                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6254                xpResolveInfo = queryCrossProfileIntents(
6255                        matchingFilters, intent, resolvedType, flags, userId,
6256                        hasNonNegativePriorityResult);
6257                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6258                    boolean isVisibleToUser = filterIfNotSystemUser(
6259                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6260                    if (isVisibleToUser) {
6261                        result.add(xpResolveInfo);
6262                        sortResult = true;
6263                    }
6264                }
6265                if (hasWebURI(intent)) {
6266                    CrossProfileDomainInfo xpDomainInfo = null;
6267                    final UserInfo parent = getProfileParent(userId);
6268                    if (parent != null) {
6269                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6270                                flags, userId, parent.id);
6271                    }
6272                    if (xpDomainInfo != null) {
6273                        if (xpResolveInfo != null) {
6274                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6275                            // in the result.
6276                            result.remove(xpResolveInfo);
6277                        }
6278                        if (result.size() == 0 && !addEphemeral) {
6279                            // No result in current profile, but found candidate in parent user.
6280                            // And we are not going to add emphemeral app, so we can return the
6281                            // result straight away.
6282                            result.add(xpDomainInfo.resolveInfo);
6283                            return applyPostResolutionFilter(result, instantAppPkgName,
6284                                    allowDynamicSplits, filterCallingUid, userId);
6285                        }
6286                    } else if (result.size() <= 1 && !addEphemeral) {
6287                        // No result in parent user and <= 1 result in current profile, and we
6288                        // are not going to add emphemeral app, so we can return the result without
6289                        // further processing.
6290                        return applyPostResolutionFilter(result, instantAppPkgName,
6291                                allowDynamicSplits, filterCallingUid, userId);
6292                    }
6293                    // We have more than one candidate (combining results from current and parent
6294                    // profile), so we need filtering and sorting.
6295                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6296                            intent, flags, result, xpDomainInfo, userId);
6297                    sortResult = true;
6298                }
6299            } else {
6300                final PackageParser.Package pkg = mPackages.get(pkgName);
6301                result = null;
6302                if (pkg != null) {
6303                    result = filterIfNotSystemUser(
6304                            mActivities.queryIntentForPackage(
6305                                    intent, resolvedType, flags, pkg.activities, userId),
6306                            userId);
6307                }
6308                if (result == null || result.size() == 0) {
6309                    // the caller wants to resolve for a particular package; however, there
6310                    // were no installed results, so, try to find an ephemeral result
6311                    addEphemeral = !ephemeralDisabled
6312                            && isInstantAppAllowed(
6313                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6314                    if (result == null) {
6315                        result = new ArrayList<>();
6316                    }
6317                }
6318            }
6319        }
6320        if (addEphemeral) {
6321            result = maybeAddInstantAppInstaller(
6322                    result, intent, resolvedType, flags, userId, resolveForStart);
6323        }
6324        if (sortResult) {
6325            Collections.sort(result, mResolvePrioritySorter);
6326        }
6327        return applyPostResolutionFilter(
6328                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6329    }
6330
6331    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6332            String resolvedType, int flags, int userId, boolean resolveForStart) {
6333        // first, check to see if we've got an instant app already installed
6334        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6335        ResolveInfo localInstantApp = null;
6336        boolean blockResolution = false;
6337        if (!alreadyResolvedLocally) {
6338            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6339                    flags
6340                        | PackageManager.GET_RESOLVED_FILTER
6341                        | PackageManager.MATCH_INSTANT
6342                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6343                    userId);
6344            for (int i = instantApps.size() - 1; i >= 0; --i) {
6345                final ResolveInfo info = instantApps.get(i);
6346                final String packageName = info.activityInfo.packageName;
6347                final PackageSetting ps = mSettings.mPackages.get(packageName);
6348                if (ps.getInstantApp(userId)) {
6349                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6350                    final int status = (int)(packedStatus >> 32);
6351                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6352                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6353                        // there's a local instant application installed, but, the user has
6354                        // chosen to never use it; skip resolution and don't acknowledge
6355                        // an instant application is even available
6356                        if (DEBUG_EPHEMERAL) {
6357                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6358                        }
6359                        blockResolution = true;
6360                        break;
6361                    } else {
6362                        // we have a locally installed instant application; skip resolution
6363                        // but acknowledge there's an instant application available
6364                        if (DEBUG_EPHEMERAL) {
6365                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6366                        }
6367                        localInstantApp = info;
6368                        break;
6369                    }
6370                }
6371            }
6372        }
6373        // no app installed, let's see if one's available
6374        AuxiliaryResolveInfo auxiliaryResponse = null;
6375        if (!blockResolution) {
6376            if (localInstantApp == null) {
6377                // we don't have an instant app locally, resolve externally
6378                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6379                final InstantAppRequest requestObject = new InstantAppRequest(
6380                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6381                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6382                        resolveForStart);
6383                auxiliaryResponse =
6384                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6385                                mContext, mInstantAppResolverConnection, requestObject);
6386                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6387            } else {
6388                // we have an instant application locally, but, we can't admit that since
6389                // callers shouldn't be able to determine prior browsing. create a dummy
6390                // auxiliary response so the downstream code behaves as if there's an
6391                // instant application available externally. when it comes time to start
6392                // the instant application, we'll do the right thing.
6393                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6394                auxiliaryResponse = new AuxiliaryResolveInfo(
6395                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6396                        ai.versionCode, null /*failureIntent*/);
6397            }
6398        }
6399        if (auxiliaryResponse != null) {
6400            if (DEBUG_EPHEMERAL) {
6401                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6402            }
6403            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6404            final PackageSetting ps =
6405                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6406            if (ps != null) {
6407                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6408                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6409                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6410                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6411                // make sure this resolver is the default
6412                ephemeralInstaller.isDefault = true;
6413                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6414                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6415                // add a non-generic filter
6416                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6417                ephemeralInstaller.filter.addDataPath(
6418                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6419                ephemeralInstaller.isInstantAppAvailable = true;
6420                result.add(ephemeralInstaller);
6421            }
6422        }
6423        return result;
6424    }
6425
6426    private static class CrossProfileDomainInfo {
6427        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6428        ResolveInfo resolveInfo;
6429        /* Best domain verification status of the activities found in the other profile */
6430        int bestDomainVerificationStatus;
6431    }
6432
6433    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6434            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6435        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6436                sourceUserId)) {
6437            return null;
6438        }
6439        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6440                resolvedType, flags, parentUserId);
6441
6442        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6443            return null;
6444        }
6445        CrossProfileDomainInfo result = null;
6446        int size = resultTargetUser.size();
6447        for (int i = 0; i < size; i++) {
6448            ResolveInfo riTargetUser = resultTargetUser.get(i);
6449            // Intent filter verification is only for filters that specify a host. So don't return
6450            // those that handle all web uris.
6451            if (riTargetUser.handleAllWebDataURI) {
6452                continue;
6453            }
6454            String packageName = riTargetUser.activityInfo.packageName;
6455            PackageSetting ps = mSettings.mPackages.get(packageName);
6456            if (ps == null) {
6457                continue;
6458            }
6459            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6460            int status = (int)(verificationState >> 32);
6461            if (result == null) {
6462                result = new CrossProfileDomainInfo();
6463                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6464                        sourceUserId, parentUserId);
6465                result.bestDomainVerificationStatus = status;
6466            } else {
6467                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6468                        result.bestDomainVerificationStatus);
6469            }
6470        }
6471        // Don't consider matches with status NEVER across profiles.
6472        if (result != null && result.bestDomainVerificationStatus
6473                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6474            return null;
6475        }
6476        return result;
6477    }
6478
6479    /**
6480     * Verification statuses are ordered from the worse to the best, except for
6481     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6482     */
6483    private int bestDomainVerificationStatus(int status1, int status2) {
6484        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6485            return status2;
6486        }
6487        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6488            return status1;
6489        }
6490        return (int) MathUtils.max(status1, status2);
6491    }
6492
6493    private boolean isUserEnabled(int userId) {
6494        long callingId = Binder.clearCallingIdentity();
6495        try {
6496            UserInfo userInfo = sUserManager.getUserInfo(userId);
6497            return userInfo != null && userInfo.isEnabled();
6498        } finally {
6499            Binder.restoreCallingIdentity(callingId);
6500        }
6501    }
6502
6503    /**
6504     * Filter out activities with systemUserOnly flag set, when current user is not System.
6505     *
6506     * @return filtered list
6507     */
6508    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6509        if (userId == UserHandle.USER_SYSTEM) {
6510            return resolveInfos;
6511        }
6512        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6513            ResolveInfo info = resolveInfos.get(i);
6514            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6515                resolveInfos.remove(i);
6516            }
6517        }
6518        return resolveInfos;
6519    }
6520
6521    /**
6522     * Filters out ephemeral activities.
6523     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6524     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6525     *
6526     * @param resolveInfos The pre-filtered list of resolved activities
6527     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6528     *          is performed.
6529     * @return A filtered list of resolved activities.
6530     */
6531    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6532            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6533        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6534            final ResolveInfo info = resolveInfos.get(i);
6535            // allow activities that are defined in the provided package
6536            if (allowDynamicSplits
6537                    && info.activityInfo.splitName != null
6538                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6539                            info.activityInfo.splitName)) {
6540                if (mInstantAppInstallerInfo == null) {
6541                    if (DEBUG_INSTALL) {
6542                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6543                    }
6544                    resolveInfos.remove(i);
6545                    continue;
6546                }
6547                // requested activity is defined in a split that hasn't been installed yet.
6548                // add the installer to the resolve list
6549                if (DEBUG_INSTALL) {
6550                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6551                }
6552                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6553                final ComponentName installFailureActivity = findInstallFailureActivity(
6554                        info.activityInfo.packageName,  filterCallingUid, userId);
6555                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6556                        info.activityInfo.packageName, info.activityInfo.splitName,
6557                        installFailureActivity,
6558                        info.activityInfo.applicationInfo.versionCode,
6559                        null /*failureIntent*/);
6560                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6561                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6562                // add a non-generic filter
6563                installerInfo.filter = new IntentFilter();
6564
6565                // This resolve info may appear in the chooser UI, so let us make it
6566                // look as the one it replaces as far as the user is concerned which
6567                // requires loading the correct label and icon for the resolve info.
6568                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6569                installerInfo.labelRes = info.resolveLabelResId();
6570                installerInfo.icon = info.resolveIconResId();
6571
6572                // propagate priority/preferred order/default
6573                installerInfo.priority = info.priority;
6574                installerInfo.preferredOrder = info.preferredOrder;
6575                installerInfo.isDefault = info.isDefault;
6576                resolveInfos.set(i, installerInfo);
6577                continue;
6578            }
6579            // caller is a full app, don't need to apply any other filtering
6580            if (ephemeralPkgName == null) {
6581                continue;
6582            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6583                // caller is same app; don't need to apply any other filtering
6584                continue;
6585            }
6586            // allow activities that have been explicitly exposed to ephemeral apps
6587            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6588            if (!isEphemeralApp
6589                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6590                continue;
6591            }
6592            resolveInfos.remove(i);
6593        }
6594        return resolveInfos;
6595    }
6596
6597    /**
6598     * Returns the activity component that can handle install failures.
6599     * <p>By default, the instant application installer handles failures. However, an
6600     * application may want to handle failures on its own. Applications do this by
6601     * creating an activity with an intent filter that handles the action
6602     * {@link Intent#ACTION_INSTALL_FAILURE}.
6603     */
6604    private @Nullable ComponentName findInstallFailureActivity(
6605            String packageName, int filterCallingUid, int userId) {
6606        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6607        failureActivityIntent.setPackage(packageName);
6608        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6609        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6610                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6611                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6612        final int NR = result.size();
6613        if (NR > 0) {
6614            for (int i = 0; i < NR; i++) {
6615                final ResolveInfo info = result.get(i);
6616                if (info.activityInfo.splitName != null) {
6617                    continue;
6618                }
6619                return new ComponentName(packageName, info.activityInfo.name);
6620            }
6621        }
6622        return null;
6623    }
6624
6625    /**
6626     * @param resolveInfos list of resolve infos in descending priority order
6627     * @return if the list contains a resolve info with non-negative priority
6628     */
6629    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6630        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6631    }
6632
6633    private static boolean hasWebURI(Intent intent) {
6634        if (intent.getData() == null) {
6635            return false;
6636        }
6637        final String scheme = intent.getScheme();
6638        if (TextUtils.isEmpty(scheme)) {
6639            return false;
6640        }
6641        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6642    }
6643
6644    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6645            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6646            int userId) {
6647        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6648
6649        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6650            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6651                    candidates.size());
6652        }
6653
6654        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6655        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6656        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6657        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6658        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6659        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6660
6661        synchronized (mPackages) {
6662            final int count = candidates.size();
6663            // First, try to use linked apps. Partition the candidates into four lists:
6664            // one for the final results, one for the "do not use ever", one for "undefined status"
6665            // and finally one for "browser app type".
6666            for (int n=0; n<count; n++) {
6667                ResolveInfo info = candidates.get(n);
6668                String packageName = info.activityInfo.packageName;
6669                PackageSetting ps = mSettings.mPackages.get(packageName);
6670                if (ps != null) {
6671                    // Add to the special match all list (Browser use case)
6672                    if (info.handleAllWebDataURI) {
6673                        matchAllList.add(info);
6674                        continue;
6675                    }
6676                    // Try to get the status from User settings first
6677                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6678                    int status = (int)(packedStatus >> 32);
6679                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6680                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6681                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6682                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6683                                    + " : linkgen=" + linkGeneration);
6684                        }
6685                        // Use link-enabled generation as preferredOrder, i.e.
6686                        // prefer newly-enabled over earlier-enabled.
6687                        info.preferredOrder = linkGeneration;
6688                        alwaysList.add(info);
6689                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6690                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6691                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6692                        }
6693                        neverList.add(info);
6694                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6695                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6696                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6697                        }
6698                        alwaysAskList.add(info);
6699                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6700                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6701                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6702                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6703                        }
6704                        undefinedList.add(info);
6705                    }
6706                }
6707            }
6708
6709            // We'll want to include browser possibilities in a few cases
6710            boolean includeBrowser = false;
6711
6712            // First try to add the "always" resolution(s) for the current user, if any
6713            if (alwaysList.size() > 0) {
6714                result.addAll(alwaysList);
6715            } else {
6716                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6717                result.addAll(undefinedList);
6718                // Maybe add one for the other profile.
6719                if (xpDomainInfo != null && (
6720                        xpDomainInfo.bestDomainVerificationStatus
6721                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6722                    result.add(xpDomainInfo.resolveInfo);
6723                }
6724                includeBrowser = true;
6725            }
6726
6727            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6728            // If there were 'always' entries their preferred order has been set, so we also
6729            // back that off to make the alternatives equivalent
6730            if (alwaysAskList.size() > 0) {
6731                for (ResolveInfo i : result) {
6732                    i.preferredOrder = 0;
6733                }
6734                result.addAll(alwaysAskList);
6735                includeBrowser = true;
6736            }
6737
6738            if (includeBrowser) {
6739                // Also add browsers (all of them or only the default one)
6740                if (DEBUG_DOMAIN_VERIFICATION) {
6741                    Slog.v(TAG, "   ...including browsers in candidate set");
6742                }
6743                if ((matchFlags & MATCH_ALL) != 0) {
6744                    result.addAll(matchAllList);
6745                } else {
6746                    // Browser/generic handling case.  If there's a default browser, go straight
6747                    // to that (but only if there is no other higher-priority match).
6748                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6749                    int maxMatchPrio = 0;
6750                    ResolveInfo defaultBrowserMatch = null;
6751                    final int numCandidates = matchAllList.size();
6752                    for (int n = 0; n < numCandidates; n++) {
6753                        ResolveInfo info = matchAllList.get(n);
6754                        // track the highest overall match priority...
6755                        if (info.priority > maxMatchPrio) {
6756                            maxMatchPrio = info.priority;
6757                        }
6758                        // ...and the highest-priority default browser match
6759                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6760                            if (defaultBrowserMatch == null
6761                                    || (defaultBrowserMatch.priority < info.priority)) {
6762                                if (debug) {
6763                                    Slog.v(TAG, "Considering default browser match " + info);
6764                                }
6765                                defaultBrowserMatch = info;
6766                            }
6767                        }
6768                    }
6769                    if (defaultBrowserMatch != null
6770                            && defaultBrowserMatch.priority >= maxMatchPrio
6771                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6772                    {
6773                        if (debug) {
6774                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6775                        }
6776                        result.add(defaultBrowserMatch);
6777                    } else {
6778                        result.addAll(matchAllList);
6779                    }
6780                }
6781
6782                // If there is nothing selected, add all candidates and remove the ones that the user
6783                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6784                if (result.size() == 0) {
6785                    result.addAll(candidates);
6786                    result.removeAll(neverList);
6787                }
6788            }
6789        }
6790        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6791            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6792                    result.size());
6793            for (ResolveInfo info : result) {
6794                Slog.v(TAG, "  + " + info.activityInfo);
6795            }
6796        }
6797        return result;
6798    }
6799
6800    // Returns a packed value as a long:
6801    //
6802    // high 'int'-sized word: link status: undefined/ask/never/always.
6803    // low 'int'-sized word: relative priority among 'always' results.
6804    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6805        long result = ps.getDomainVerificationStatusForUser(userId);
6806        // if none available, get the master status
6807        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6808            if (ps.getIntentFilterVerificationInfo() != null) {
6809                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6810            }
6811        }
6812        return result;
6813    }
6814
6815    private ResolveInfo querySkipCurrentProfileIntents(
6816            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6817            int flags, int sourceUserId) {
6818        if (matchingFilters != null) {
6819            int size = matchingFilters.size();
6820            for (int i = 0; i < size; i ++) {
6821                CrossProfileIntentFilter filter = matchingFilters.get(i);
6822                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6823                    // Checking if there are activities in the target user that can handle the
6824                    // intent.
6825                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6826                            resolvedType, flags, sourceUserId);
6827                    if (resolveInfo != null) {
6828                        return resolveInfo;
6829                    }
6830                }
6831            }
6832        }
6833        return null;
6834    }
6835
6836    // Return matching ResolveInfo in target user if any.
6837    private ResolveInfo queryCrossProfileIntents(
6838            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6839            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6840        if (matchingFilters != null) {
6841            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6842            // match the same intent. For performance reasons, it is better not to
6843            // run queryIntent twice for the same userId
6844            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6845            int size = matchingFilters.size();
6846            for (int i = 0; i < size; i++) {
6847                CrossProfileIntentFilter filter = matchingFilters.get(i);
6848                int targetUserId = filter.getTargetUserId();
6849                boolean skipCurrentProfile =
6850                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6851                boolean skipCurrentProfileIfNoMatchFound =
6852                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6853                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6854                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6855                    // Checking if there are activities in the target user that can handle the
6856                    // intent.
6857                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6858                            resolvedType, flags, sourceUserId);
6859                    if (resolveInfo != null) return resolveInfo;
6860                    alreadyTriedUserIds.put(targetUserId, true);
6861                }
6862            }
6863        }
6864        return null;
6865    }
6866
6867    /**
6868     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6869     * will forward the intent to the filter's target user.
6870     * Otherwise, returns null.
6871     */
6872    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6873            String resolvedType, int flags, int sourceUserId) {
6874        int targetUserId = filter.getTargetUserId();
6875        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6876                resolvedType, flags, targetUserId);
6877        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6878            // If all the matches in the target profile are suspended, return null.
6879            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6880                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6881                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6882                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6883                            targetUserId);
6884                }
6885            }
6886        }
6887        return null;
6888    }
6889
6890    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6891            int sourceUserId, int targetUserId) {
6892        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6893        long ident = Binder.clearCallingIdentity();
6894        boolean targetIsProfile;
6895        try {
6896            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6897        } finally {
6898            Binder.restoreCallingIdentity(ident);
6899        }
6900        String className;
6901        if (targetIsProfile) {
6902            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6903        } else {
6904            className = FORWARD_INTENT_TO_PARENT;
6905        }
6906        ComponentName forwardingActivityComponentName = new ComponentName(
6907                mAndroidApplication.packageName, className);
6908        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6909                sourceUserId);
6910        if (!targetIsProfile) {
6911            forwardingActivityInfo.showUserIcon = targetUserId;
6912            forwardingResolveInfo.noResourceId = true;
6913        }
6914        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6915        forwardingResolveInfo.priority = 0;
6916        forwardingResolveInfo.preferredOrder = 0;
6917        forwardingResolveInfo.match = 0;
6918        forwardingResolveInfo.isDefault = true;
6919        forwardingResolveInfo.filter = filter;
6920        forwardingResolveInfo.targetUserId = targetUserId;
6921        return forwardingResolveInfo;
6922    }
6923
6924    @Override
6925    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6926            Intent[] specifics, String[] specificTypes, Intent intent,
6927            String resolvedType, int flags, int userId) {
6928        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6929                specificTypes, intent, resolvedType, flags, userId));
6930    }
6931
6932    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6933            Intent[] specifics, String[] specificTypes, Intent intent,
6934            String resolvedType, int flags, int userId) {
6935        if (!sUserManager.exists(userId)) return Collections.emptyList();
6936        final int callingUid = Binder.getCallingUid();
6937        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6938                false /*includeInstantApps*/);
6939        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
6940                false /*requireFullPermission*/, false /*checkShell*/,
6941                "query intent activity options");
6942        final String resultsAction = intent.getAction();
6943
6944        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6945                | PackageManager.GET_RESOLVED_FILTER, userId);
6946
6947        if (DEBUG_INTENT_MATCHING) {
6948            Log.v(TAG, "Query " + intent + ": " + results);
6949        }
6950
6951        int specificsPos = 0;
6952        int N;
6953
6954        // todo: note that the algorithm used here is O(N^2).  This
6955        // isn't a problem in our current environment, but if we start running
6956        // into situations where we have more than 5 or 10 matches then this
6957        // should probably be changed to something smarter...
6958
6959        // First we go through and resolve each of the specific items
6960        // that were supplied, taking care of removing any corresponding
6961        // duplicate items in the generic resolve list.
6962        if (specifics != null) {
6963            for (int i=0; i<specifics.length; i++) {
6964                final Intent sintent = specifics[i];
6965                if (sintent == null) {
6966                    continue;
6967                }
6968
6969                if (DEBUG_INTENT_MATCHING) {
6970                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6971                }
6972
6973                String action = sintent.getAction();
6974                if (resultsAction != null && resultsAction.equals(action)) {
6975                    // If this action was explicitly requested, then don't
6976                    // remove things that have it.
6977                    action = null;
6978                }
6979
6980                ResolveInfo ri = null;
6981                ActivityInfo ai = null;
6982
6983                ComponentName comp = sintent.getComponent();
6984                if (comp == null) {
6985                    ri = resolveIntent(
6986                        sintent,
6987                        specificTypes != null ? specificTypes[i] : null,
6988                            flags, userId);
6989                    if (ri == null) {
6990                        continue;
6991                    }
6992                    if (ri == mResolveInfo) {
6993                        // ACK!  Must do something better with this.
6994                    }
6995                    ai = ri.activityInfo;
6996                    comp = new ComponentName(ai.applicationInfo.packageName,
6997                            ai.name);
6998                } else {
6999                    ai = getActivityInfo(comp, flags, userId);
7000                    if (ai == null) {
7001                        continue;
7002                    }
7003                }
7004
7005                // Look for any generic query activities that are duplicates
7006                // of this specific one, and remove them from the results.
7007                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7008                N = results.size();
7009                int j;
7010                for (j=specificsPos; j<N; j++) {
7011                    ResolveInfo sri = results.get(j);
7012                    if ((sri.activityInfo.name.equals(comp.getClassName())
7013                            && sri.activityInfo.applicationInfo.packageName.equals(
7014                                    comp.getPackageName()))
7015                        || (action != null && sri.filter.matchAction(action))) {
7016                        results.remove(j);
7017                        if (DEBUG_INTENT_MATCHING) Log.v(
7018                            TAG, "Removing duplicate item from " + j
7019                            + " due to specific " + specificsPos);
7020                        if (ri == null) {
7021                            ri = sri;
7022                        }
7023                        j--;
7024                        N--;
7025                    }
7026                }
7027
7028                // Add this specific item to its proper place.
7029                if (ri == null) {
7030                    ri = new ResolveInfo();
7031                    ri.activityInfo = ai;
7032                }
7033                results.add(specificsPos, ri);
7034                ri.specificIndex = i;
7035                specificsPos++;
7036            }
7037        }
7038
7039        // Now we go through the remaining generic results and remove any
7040        // duplicate actions that are found here.
7041        N = results.size();
7042        for (int i=specificsPos; i<N-1; i++) {
7043            final ResolveInfo rii = results.get(i);
7044            if (rii.filter == null) {
7045                continue;
7046            }
7047
7048            // Iterate over all of the actions of this result's intent
7049            // filter...  typically this should be just one.
7050            final Iterator<String> it = rii.filter.actionsIterator();
7051            if (it == null) {
7052                continue;
7053            }
7054            while (it.hasNext()) {
7055                final String action = it.next();
7056                if (resultsAction != null && resultsAction.equals(action)) {
7057                    // If this action was explicitly requested, then don't
7058                    // remove things that have it.
7059                    continue;
7060                }
7061                for (int j=i+1; j<N; j++) {
7062                    final ResolveInfo rij = results.get(j);
7063                    if (rij.filter != null && rij.filter.hasAction(action)) {
7064                        results.remove(j);
7065                        if (DEBUG_INTENT_MATCHING) Log.v(
7066                            TAG, "Removing duplicate item from " + j
7067                            + " due to action " + action + " at " + i);
7068                        j--;
7069                        N--;
7070                    }
7071                }
7072            }
7073
7074            // If the caller didn't request filter information, drop it now
7075            // so we don't have to marshall/unmarshall it.
7076            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7077                rii.filter = null;
7078            }
7079        }
7080
7081        // Filter out the caller activity if so requested.
7082        if (caller != null) {
7083            N = results.size();
7084            for (int i=0; i<N; i++) {
7085                ActivityInfo ainfo = results.get(i).activityInfo;
7086                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7087                        && caller.getClassName().equals(ainfo.name)) {
7088                    results.remove(i);
7089                    break;
7090                }
7091            }
7092        }
7093
7094        // If the caller didn't request filter information,
7095        // drop them now so we don't have to
7096        // marshall/unmarshall it.
7097        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7098            N = results.size();
7099            for (int i=0; i<N; i++) {
7100                results.get(i).filter = null;
7101            }
7102        }
7103
7104        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7105        return results;
7106    }
7107
7108    @Override
7109    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7110            String resolvedType, int flags, int userId) {
7111        return new ParceledListSlice<>(
7112                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7113                        false /*allowDynamicSplits*/));
7114    }
7115
7116    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7117            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7118        if (!sUserManager.exists(userId)) return Collections.emptyList();
7119        final int callingUid = Binder.getCallingUid();
7120        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7121                false /*requireFullPermission*/, false /*checkShell*/,
7122                "query intent receivers");
7123        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7124        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7125                false /*includeInstantApps*/);
7126        ComponentName comp = intent.getComponent();
7127        if (comp == null) {
7128            if (intent.getSelector() != null) {
7129                intent = intent.getSelector();
7130                comp = intent.getComponent();
7131            }
7132        }
7133        if (comp != null) {
7134            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7135            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7136            if (ai != null) {
7137                // When specifying an explicit component, we prevent the activity from being
7138                // used when either 1) the calling package is normal and the activity is within
7139                // an instant application or 2) the calling package is ephemeral and the
7140                // activity is not visible to instant applications.
7141                final boolean matchInstantApp =
7142                        (flags & PackageManager.MATCH_INSTANT) != 0;
7143                final boolean matchVisibleToInstantAppOnly =
7144                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7145                final boolean matchExplicitlyVisibleOnly =
7146                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7147                final boolean isCallerInstantApp =
7148                        instantAppPkgName != null;
7149                final boolean isTargetSameInstantApp =
7150                        comp.getPackageName().equals(instantAppPkgName);
7151                final boolean isTargetInstantApp =
7152                        (ai.applicationInfo.privateFlags
7153                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7154                final boolean isTargetVisibleToInstantApp =
7155                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7156                final boolean isTargetExplicitlyVisibleToInstantApp =
7157                        isTargetVisibleToInstantApp
7158                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7159                final boolean isTargetHiddenFromInstantApp =
7160                        !isTargetVisibleToInstantApp
7161                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7162                final boolean blockResolution =
7163                        !isTargetSameInstantApp
7164                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7165                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7166                                        && isTargetHiddenFromInstantApp));
7167                if (!blockResolution) {
7168                    ResolveInfo ri = new ResolveInfo();
7169                    ri.activityInfo = ai;
7170                    list.add(ri);
7171                }
7172            }
7173            return applyPostResolutionFilter(
7174                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7175        }
7176
7177        // reader
7178        synchronized (mPackages) {
7179            String pkgName = intent.getPackage();
7180            if (pkgName == null) {
7181                final List<ResolveInfo> result =
7182                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7183                return applyPostResolutionFilter(
7184                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7185            }
7186            final PackageParser.Package pkg = mPackages.get(pkgName);
7187            if (pkg != null) {
7188                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7189                        intent, resolvedType, flags, pkg.receivers, userId);
7190                return applyPostResolutionFilter(
7191                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7192            }
7193            return Collections.emptyList();
7194        }
7195    }
7196
7197    @Override
7198    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7199        final int callingUid = Binder.getCallingUid();
7200        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7201    }
7202
7203    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7204            int userId, int callingUid) {
7205        if (!sUserManager.exists(userId)) return null;
7206        flags = updateFlagsForResolve(
7207                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7208        List<ResolveInfo> query = queryIntentServicesInternal(
7209                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7210        if (query != null) {
7211            if (query.size() >= 1) {
7212                // If there is more than one service with the same priority,
7213                // just arbitrarily pick the first one.
7214                return query.get(0);
7215            }
7216        }
7217        return null;
7218    }
7219
7220    @Override
7221    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7222            String resolvedType, int flags, int userId) {
7223        final int callingUid = Binder.getCallingUid();
7224        return new ParceledListSlice<>(queryIntentServicesInternal(
7225                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7226    }
7227
7228    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7229            String resolvedType, int flags, int userId, int callingUid,
7230            boolean includeInstantApps) {
7231        if (!sUserManager.exists(userId)) return Collections.emptyList();
7232        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7233                false /*requireFullPermission*/, false /*checkShell*/,
7234                "query intent receivers");
7235        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7236        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7237        ComponentName comp = intent.getComponent();
7238        if (comp == null) {
7239            if (intent.getSelector() != null) {
7240                intent = intent.getSelector();
7241                comp = intent.getComponent();
7242            }
7243        }
7244        if (comp != null) {
7245            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7246            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7247            if (si != null) {
7248                // When specifying an explicit component, we prevent the service from being
7249                // used when either 1) the service is in an instant application and the
7250                // caller is not the same instant application or 2) the calling package is
7251                // ephemeral and the activity is not visible to ephemeral applications.
7252                final boolean matchInstantApp =
7253                        (flags & PackageManager.MATCH_INSTANT) != 0;
7254                final boolean matchVisibleToInstantAppOnly =
7255                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7256                final boolean isCallerInstantApp =
7257                        instantAppPkgName != null;
7258                final boolean isTargetSameInstantApp =
7259                        comp.getPackageName().equals(instantAppPkgName);
7260                final boolean isTargetInstantApp =
7261                        (si.applicationInfo.privateFlags
7262                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7263                final boolean isTargetHiddenFromInstantApp =
7264                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7265                final boolean blockResolution =
7266                        !isTargetSameInstantApp
7267                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7268                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7269                                        && isTargetHiddenFromInstantApp));
7270                if (!blockResolution) {
7271                    final ResolveInfo ri = new ResolveInfo();
7272                    ri.serviceInfo = si;
7273                    list.add(ri);
7274                }
7275            }
7276            return list;
7277        }
7278
7279        // reader
7280        synchronized (mPackages) {
7281            String pkgName = intent.getPackage();
7282            if (pkgName == null) {
7283                return applyPostServiceResolutionFilter(
7284                        mServices.queryIntent(intent, resolvedType, flags, userId),
7285                        instantAppPkgName);
7286            }
7287            final PackageParser.Package pkg = mPackages.get(pkgName);
7288            if (pkg != null) {
7289                return applyPostServiceResolutionFilter(
7290                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7291                                userId),
7292                        instantAppPkgName);
7293            }
7294            return Collections.emptyList();
7295        }
7296    }
7297
7298    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7299            String instantAppPkgName) {
7300        if (instantAppPkgName == null) {
7301            return resolveInfos;
7302        }
7303        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7304            final ResolveInfo info = resolveInfos.get(i);
7305            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7306            // allow services that are defined in the provided package
7307            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7308                if (info.serviceInfo.splitName != null
7309                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7310                                info.serviceInfo.splitName)) {
7311                    // requested service is defined in a split that hasn't been installed yet.
7312                    // add the installer to the resolve list
7313                    if (DEBUG_EPHEMERAL) {
7314                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7315                    }
7316                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7317                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7318                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7319                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7320                            null /*failureIntent*/);
7321                    // make sure this resolver is the default
7322                    installerInfo.isDefault = true;
7323                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7324                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7325                    // add a non-generic filter
7326                    installerInfo.filter = new IntentFilter();
7327                    // load resources from the correct package
7328                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7329                    resolveInfos.set(i, installerInfo);
7330                }
7331                continue;
7332            }
7333            // allow services that have been explicitly exposed to ephemeral apps
7334            if (!isEphemeralApp
7335                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7336                continue;
7337            }
7338            resolveInfos.remove(i);
7339        }
7340        return resolveInfos;
7341    }
7342
7343    @Override
7344    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7345            String resolvedType, int flags, int userId) {
7346        return new ParceledListSlice<>(
7347                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7348    }
7349
7350    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7351            Intent intent, String resolvedType, int flags, int userId) {
7352        if (!sUserManager.exists(userId)) return Collections.emptyList();
7353        final int callingUid = Binder.getCallingUid();
7354        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7355        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7356                false /*includeInstantApps*/);
7357        ComponentName comp = intent.getComponent();
7358        if (comp == null) {
7359            if (intent.getSelector() != null) {
7360                intent = intent.getSelector();
7361                comp = intent.getComponent();
7362            }
7363        }
7364        if (comp != null) {
7365            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7366            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7367            if (pi != null) {
7368                // When specifying an explicit component, we prevent the provider from being
7369                // used when either 1) the provider is in an instant application and the
7370                // caller is not the same instant application or 2) the calling package is an
7371                // instant application and the provider is not visible to instant applications.
7372                final boolean matchInstantApp =
7373                        (flags & PackageManager.MATCH_INSTANT) != 0;
7374                final boolean matchVisibleToInstantAppOnly =
7375                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7376                final boolean isCallerInstantApp =
7377                        instantAppPkgName != null;
7378                final boolean isTargetSameInstantApp =
7379                        comp.getPackageName().equals(instantAppPkgName);
7380                final boolean isTargetInstantApp =
7381                        (pi.applicationInfo.privateFlags
7382                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7383                final boolean isTargetHiddenFromInstantApp =
7384                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7385                final boolean blockResolution =
7386                        !isTargetSameInstantApp
7387                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7388                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7389                                        && isTargetHiddenFromInstantApp));
7390                if (!blockResolution) {
7391                    final ResolveInfo ri = new ResolveInfo();
7392                    ri.providerInfo = pi;
7393                    list.add(ri);
7394                }
7395            }
7396            return list;
7397        }
7398
7399        // reader
7400        synchronized (mPackages) {
7401            String pkgName = intent.getPackage();
7402            if (pkgName == null) {
7403                return applyPostContentProviderResolutionFilter(
7404                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7405                        instantAppPkgName);
7406            }
7407            final PackageParser.Package pkg = mPackages.get(pkgName);
7408            if (pkg != null) {
7409                return applyPostContentProviderResolutionFilter(
7410                        mProviders.queryIntentForPackage(
7411                        intent, resolvedType, flags, pkg.providers, userId),
7412                        instantAppPkgName);
7413            }
7414            return Collections.emptyList();
7415        }
7416    }
7417
7418    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7419            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7420        if (instantAppPkgName == null) {
7421            return resolveInfos;
7422        }
7423        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7424            final ResolveInfo info = resolveInfos.get(i);
7425            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7426            // allow providers that are defined in the provided package
7427            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7428                if (info.providerInfo.splitName != null
7429                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7430                                info.providerInfo.splitName)) {
7431                    // requested provider is defined in a split that hasn't been installed yet.
7432                    // add the installer to the resolve list
7433                    if (DEBUG_EPHEMERAL) {
7434                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7435                    }
7436                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7437                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7438                            info.providerInfo.packageName, info.providerInfo.splitName,
7439                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7440                            null /*failureIntent*/);
7441                    // make sure this resolver is the default
7442                    installerInfo.isDefault = true;
7443                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7444                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7445                    // add a non-generic filter
7446                    installerInfo.filter = new IntentFilter();
7447                    // load resources from the correct package
7448                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7449                    resolveInfos.set(i, installerInfo);
7450                }
7451                continue;
7452            }
7453            // allow providers that have been explicitly exposed to instant applications
7454            if (!isEphemeralApp
7455                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7456                continue;
7457            }
7458            resolveInfos.remove(i);
7459        }
7460        return resolveInfos;
7461    }
7462
7463    @Override
7464    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7465        final int callingUid = Binder.getCallingUid();
7466        if (getInstantAppPackageName(callingUid) != null) {
7467            return ParceledListSlice.emptyList();
7468        }
7469        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7470        flags = updateFlagsForPackage(flags, userId, null);
7471        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7472        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7473                true /* requireFullPermission */, false /* checkShell */,
7474                "get installed packages");
7475
7476        // writer
7477        synchronized (mPackages) {
7478            ArrayList<PackageInfo> list;
7479            if (listUninstalled) {
7480                list = new ArrayList<>(mSettings.mPackages.size());
7481                for (PackageSetting ps : mSettings.mPackages.values()) {
7482                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7483                        continue;
7484                    }
7485                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7486                        continue;
7487                    }
7488                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7489                    if (pi != null) {
7490                        list.add(pi);
7491                    }
7492                }
7493            } else {
7494                list = new ArrayList<>(mPackages.size());
7495                for (PackageParser.Package p : mPackages.values()) {
7496                    final PackageSetting ps = (PackageSetting) p.mExtras;
7497                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7498                        continue;
7499                    }
7500                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7501                        continue;
7502                    }
7503                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7504                            p.mExtras, flags, userId);
7505                    if (pi != null) {
7506                        list.add(pi);
7507                    }
7508                }
7509            }
7510
7511            return new ParceledListSlice<>(list);
7512        }
7513    }
7514
7515    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7516            String[] permissions, boolean[] tmp, int flags, int userId) {
7517        int numMatch = 0;
7518        final PermissionsState permissionsState = ps.getPermissionsState();
7519        for (int i=0; i<permissions.length; i++) {
7520            final String permission = permissions[i];
7521            if (permissionsState.hasPermission(permission, userId)) {
7522                tmp[i] = true;
7523                numMatch++;
7524            } else {
7525                tmp[i] = false;
7526            }
7527        }
7528        if (numMatch == 0) {
7529            return;
7530        }
7531        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7532
7533        // The above might return null in cases of uninstalled apps or install-state
7534        // skew across users/profiles.
7535        if (pi != null) {
7536            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7537                if (numMatch == permissions.length) {
7538                    pi.requestedPermissions = permissions;
7539                } else {
7540                    pi.requestedPermissions = new String[numMatch];
7541                    numMatch = 0;
7542                    for (int i=0; i<permissions.length; i++) {
7543                        if (tmp[i]) {
7544                            pi.requestedPermissions[numMatch] = permissions[i];
7545                            numMatch++;
7546                        }
7547                    }
7548                }
7549            }
7550            list.add(pi);
7551        }
7552    }
7553
7554    @Override
7555    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7556            String[] permissions, int flags, int userId) {
7557        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7558        flags = updateFlagsForPackage(flags, userId, permissions);
7559        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7560                true /* requireFullPermission */, false /* checkShell */,
7561                "get packages holding permissions");
7562        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7563
7564        // writer
7565        synchronized (mPackages) {
7566            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7567            boolean[] tmpBools = new boolean[permissions.length];
7568            if (listUninstalled) {
7569                for (PackageSetting ps : mSettings.mPackages.values()) {
7570                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7571                            userId);
7572                }
7573            } else {
7574                for (PackageParser.Package pkg : mPackages.values()) {
7575                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7576                    if (ps != null) {
7577                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7578                                userId);
7579                    }
7580                }
7581            }
7582
7583            return new ParceledListSlice<PackageInfo>(list);
7584        }
7585    }
7586
7587    @Override
7588    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7589        final int callingUid = Binder.getCallingUid();
7590        if (getInstantAppPackageName(callingUid) != null) {
7591            return ParceledListSlice.emptyList();
7592        }
7593        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7594        flags = updateFlagsForApplication(flags, userId, null);
7595        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7596
7597        // writer
7598        synchronized (mPackages) {
7599            ArrayList<ApplicationInfo> list;
7600            if (listUninstalled) {
7601                list = new ArrayList<>(mSettings.mPackages.size());
7602                for (PackageSetting ps : mSettings.mPackages.values()) {
7603                    ApplicationInfo ai;
7604                    int effectiveFlags = flags;
7605                    if (ps.isSystem()) {
7606                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7607                    }
7608                    if (ps.pkg != null) {
7609                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7610                            continue;
7611                        }
7612                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7613                            continue;
7614                        }
7615                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7616                                ps.readUserState(userId), userId);
7617                        if (ai != null) {
7618                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7619                        }
7620                    } else {
7621                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7622                        // and already converts to externally visible package name
7623                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7624                                callingUid, effectiveFlags, userId);
7625                    }
7626                    if (ai != null) {
7627                        list.add(ai);
7628                    }
7629                }
7630            } else {
7631                list = new ArrayList<>(mPackages.size());
7632                for (PackageParser.Package p : mPackages.values()) {
7633                    if (p.mExtras != null) {
7634                        PackageSetting ps = (PackageSetting) p.mExtras;
7635                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7636                            continue;
7637                        }
7638                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7639                            continue;
7640                        }
7641                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7642                                ps.readUserState(userId), userId);
7643                        if (ai != null) {
7644                            ai.packageName = resolveExternalPackageNameLPr(p);
7645                            list.add(ai);
7646                        }
7647                    }
7648                }
7649            }
7650
7651            return new ParceledListSlice<>(list);
7652        }
7653    }
7654
7655    @Override
7656    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7657        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7658            return null;
7659        }
7660        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7661            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7662                    "getEphemeralApplications");
7663        }
7664        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7665                true /* requireFullPermission */, false /* checkShell */,
7666                "getEphemeralApplications");
7667        synchronized (mPackages) {
7668            List<InstantAppInfo> instantApps = mInstantAppRegistry
7669                    .getInstantAppsLPr(userId);
7670            if (instantApps != null) {
7671                return new ParceledListSlice<>(instantApps);
7672            }
7673        }
7674        return null;
7675    }
7676
7677    @Override
7678    public boolean isInstantApp(String packageName, int userId) {
7679        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7680                true /* requireFullPermission */, false /* checkShell */,
7681                "isInstantApp");
7682        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7683            return false;
7684        }
7685
7686        synchronized (mPackages) {
7687            int callingUid = Binder.getCallingUid();
7688            if (Process.isIsolated(callingUid)) {
7689                callingUid = mIsolatedOwners.get(callingUid);
7690            }
7691            final PackageSetting ps = mSettings.mPackages.get(packageName);
7692            PackageParser.Package pkg = mPackages.get(packageName);
7693            final boolean returnAllowed =
7694                    ps != null
7695                    && (isCallerSameApp(packageName, callingUid)
7696                            || canViewInstantApps(callingUid, userId)
7697                            || mInstantAppRegistry.isInstantAccessGranted(
7698                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7699            if (returnAllowed) {
7700                return ps.getInstantApp(userId);
7701            }
7702        }
7703        return false;
7704    }
7705
7706    @Override
7707    public byte[] getInstantAppCookie(String packageName, int userId) {
7708        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7709            return null;
7710        }
7711
7712        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7713                true /* requireFullPermission */, false /* checkShell */,
7714                "getInstantAppCookie");
7715        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7716            return null;
7717        }
7718        synchronized (mPackages) {
7719            return mInstantAppRegistry.getInstantAppCookieLPw(
7720                    packageName, userId);
7721        }
7722    }
7723
7724    @Override
7725    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7726        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7727            return true;
7728        }
7729
7730        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7731                true /* requireFullPermission */, true /* checkShell */,
7732                "setInstantAppCookie");
7733        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7734            return false;
7735        }
7736        synchronized (mPackages) {
7737            return mInstantAppRegistry.setInstantAppCookieLPw(
7738                    packageName, cookie, userId);
7739        }
7740    }
7741
7742    @Override
7743    public Bitmap getInstantAppIcon(String packageName, int userId) {
7744        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7745            return null;
7746        }
7747
7748        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7749            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7750                    "getInstantAppIcon");
7751        }
7752        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7753                true /* requireFullPermission */, false /* checkShell */,
7754                "getInstantAppIcon");
7755
7756        synchronized (mPackages) {
7757            return mInstantAppRegistry.getInstantAppIconLPw(
7758                    packageName, userId);
7759        }
7760    }
7761
7762    private boolean isCallerSameApp(String packageName, int uid) {
7763        PackageParser.Package pkg = mPackages.get(packageName);
7764        return pkg != null
7765                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7766    }
7767
7768    @Override
7769    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7770        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7771            return ParceledListSlice.emptyList();
7772        }
7773        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7774    }
7775
7776    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7777        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7778
7779        // reader
7780        synchronized (mPackages) {
7781            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7782            final int userId = UserHandle.getCallingUserId();
7783            while (i.hasNext()) {
7784                final PackageParser.Package p = i.next();
7785                if (p.applicationInfo == null) continue;
7786
7787                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7788                        && !p.applicationInfo.isDirectBootAware();
7789                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7790                        && p.applicationInfo.isDirectBootAware();
7791
7792                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7793                        && (!mSafeMode || isSystemApp(p))
7794                        && (matchesUnaware || matchesAware)) {
7795                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7796                    if (ps != null) {
7797                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7798                                ps.readUserState(userId), userId);
7799                        if (ai != null) {
7800                            finalList.add(ai);
7801                        }
7802                    }
7803                }
7804            }
7805        }
7806
7807        return finalList;
7808    }
7809
7810    @Override
7811    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7812        return resolveContentProviderInternal(name, flags, userId);
7813    }
7814
7815    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7816        if (!sUserManager.exists(userId)) return null;
7817        flags = updateFlagsForComponent(flags, userId, name);
7818        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7819        // reader
7820        synchronized (mPackages) {
7821            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7822            PackageSetting ps = provider != null
7823                    ? mSettings.mPackages.get(provider.owner.packageName)
7824                    : null;
7825            if (ps != null) {
7826                final boolean isInstantApp = ps.getInstantApp(userId);
7827                // normal application; filter out instant application provider
7828                if (instantAppPkgName == null && isInstantApp) {
7829                    return null;
7830                }
7831                // instant application; filter out other instant applications
7832                if (instantAppPkgName != null
7833                        && isInstantApp
7834                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7835                    return null;
7836                }
7837                // instant application; filter out non-exposed provider
7838                if (instantAppPkgName != null
7839                        && !isInstantApp
7840                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7841                    return null;
7842                }
7843                // provider not enabled
7844                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7845                    return null;
7846                }
7847                return PackageParser.generateProviderInfo(
7848                        provider, flags, ps.readUserState(userId), userId);
7849            }
7850            return null;
7851        }
7852    }
7853
7854    /**
7855     * @deprecated
7856     */
7857    @Deprecated
7858    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7859        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7860            return;
7861        }
7862        // reader
7863        synchronized (mPackages) {
7864            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7865                    .entrySet().iterator();
7866            final int userId = UserHandle.getCallingUserId();
7867            while (i.hasNext()) {
7868                Map.Entry<String, PackageParser.Provider> entry = i.next();
7869                PackageParser.Provider p = entry.getValue();
7870                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7871
7872                if (ps != null && p.syncable
7873                        && (!mSafeMode || (p.info.applicationInfo.flags
7874                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7875                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7876                            ps.readUserState(userId), userId);
7877                    if (info != null) {
7878                        outNames.add(entry.getKey());
7879                        outInfo.add(info);
7880                    }
7881                }
7882            }
7883        }
7884    }
7885
7886    @Override
7887    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7888            int uid, int flags, String metaDataKey) {
7889        final int callingUid = Binder.getCallingUid();
7890        final int userId = processName != null ? UserHandle.getUserId(uid)
7891                : UserHandle.getCallingUserId();
7892        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7893        flags = updateFlagsForComponent(flags, userId, processName);
7894        ArrayList<ProviderInfo> finalList = null;
7895        // reader
7896        synchronized (mPackages) {
7897            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7898            while (i.hasNext()) {
7899                final PackageParser.Provider p = i.next();
7900                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7901                if (ps != null && p.info.authority != null
7902                        && (processName == null
7903                                || (p.info.processName.equals(processName)
7904                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7905                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7906
7907                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7908                    // parameter.
7909                    if (metaDataKey != null
7910                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7911                        continue;
7912                    }
7913                    final ComponentName component =
7914                            new ComponentName(p.info.packageName, p.info.name);
7915                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
7916                        continue;
7917                    }
7918                    if (finalList == null) {
7919                        finalList = new ArrayList<ProviderInfo>(3);
7920                    }
7921                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7922                            ps.readUserState(userId), userId);
7923                    if (info != null) {
7924                        finalList.add(info);
7925                    }
7926                }
7927            }
7928        }
7929
7930        if (finalList != null) {
7931            Collections.sort(finalList, mProviderInitOrderSorter);
7932            return new ParceledListSlice<ProviderInfo>(finalList);
7933        }
7934
7935        return ParceledListSlice.emptyList();
7936    }
7937
7938    @Override
7939    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
7940        // reader
7941        synchronized (mPackages) {
7942            final int callingUid = Binder.getCallingUid();
7943            final int callingUserId = UserHandle.getUserId(callingUid);
7944            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
7945            if (ps == null) return null;
7946            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
7947                return null;
7948            }
7949            final PackageParser.Instrumentation i = mInstrumentation.get(component);
7950            return PackageParser.generateInstrumentationInfo(i, flags);
7951        }
7952    }
7953
7954    @Override
7955    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7956            String targetPackage, int flags) {
7957        final int callingUid = Binder.getCallingUid();
7958        final int callingUserId = UserHandle.getUserId(callingUid);
7959        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
7960        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
7961            return ParceledListSlice.emptyList();
7962        }
7963        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7964    }
7965
7966    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7967            int flags) {
7968        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7969
7970        // reader
7971        synchronized (mPackages) {
7972            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7973            while (i.hasNext()) {
7974                final PackageParser.Instrumentation p = i.next();
7975                if (targetPackage == null
7976                        || targetPackage.equals(p.info.targetPackage)) {
7977                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7978                            flags);
7979                    if (ii != null) {
7980                        finalList.add(ii);
7981                    }
7982                }
7983            }
7984        }
7985
7986        return finalList;
7987    }
7988
7989    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7990        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7991        try {
7992            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7993        } finally {
7994            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7995        }
7996    }
7997
7998    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7999        final File[] files = dir.listFiles();
8000        if (ArrayUtils.isEmpty(files)) {
8001            Log.d(TAG, "No files in app dir " + dir);
8002            return;
8003        }
8004
8005        if (DEBUG_PACKAGE_SCANNING) {
8006            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8007                    + " flags=0x" + Integer.toHexString(parseFlags));
8008        }
8009        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8010                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8011                mParallelPackageParserCallback);
8012
8013        // Submit files for parsing in parallel
8014        int fileCount = 0;
8015        for (File file : files) {
8016            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8017                    && !PackageInstallerService.isStageName(file.getName());
8018            if (!isPackage) {
8019                // Ignore entries which are not packages
8020                continue;
8021            }
8022            parallelPackageParser.submit(file, parseFlags);
8023            fileCount++;
8024        }
8025
8026        // Process results one by one
8027        for (; fileCount > 0; fileCount--) {
8028            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8029            Throwable throwable = parseResult.throwable;
8030            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8031
8032            if (throwable == null) {
8033                // Static shared libraries have synthetic package names
8034                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8035                    renameStaticSharedLibraryPackage(parseResult.pkg);
8036                }
8037                try {
8038                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8039                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8040                                currentTime, null);
8041                    }
8042                } catch (PackageManagerException e) {
8043                    errorCode = e.error;
8044                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8045                }
8046            } else if (throwable instanceof PackageParser.PackageParserException) {
8047                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8048                        throwable;
8049                errorCode = e.error;
8050                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8051            } else {
8052                throw new IllegalStateException("Unexpected exception occurred while parsing "
8053                        + parseResult.scanFile, throwable);
8054            }
8055
8056            // Delete invalid userdata apps
8057            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8058                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8059                logCriticalInfo(Log.WARN,
8060                        "Deleting invalid package at " + parseResult.scanFile);
8061                removeCodePathLI(parseResult.scanFile);
8062            }
8063        }
8064        parallelPackageParser.close();
8065    }
8066
8067    public static void reportSettingsProblem(int priority, String msg) {
8068        logCriticalInfo(priority, msg);
8069    }
8070
8071    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8072            final int policyFlags) throws PackageManagerException {
8073        // When upgrading from pre-N MR1, verify the package time stamp using the package
8074        // directory and not the APK file.
8075        final long lastModifiedTime = mIsPreNMR1Upgrade
8076                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8077        if (ps != null
8078                && ps.codePath.equals(srcFile)
8079                && ps.timeStamp == lastModifiedTime
8080                && !isCompatSignatureUpdateNeeded(pkg)
8081                && !isRecoverSignatureUpdateNeeded(pkg)) {
8082            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8083            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8084            ArraySet<PublicKey> signingKs;
8085            synchronized (mPackages) {
8086                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8087            }
8088            if (ps.signatures.mSignatures != null
8089                    && ps.signatures.mSignatures.length != 0
8090                    && signingKs != null) {
8091                // Optimization: reuse the existing cached certificates
8092                // if the package appears to be unchanged.
8093                pkg.mSignatures = ps.signatures.mSignatures;
8094                pkg.mSigningKeys = signingKs;
8095                return;
8096            }
8097
8098            Slog.w(TAG, "PackageSetting for " + ps.name
8099                    + " is missing signatures.  Collecting certs again to recover them.");
8100        } else {
8101            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8102        }
8103
8104        try {
8105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8106            PackageParser.collectCertificates(pkg, policyFlags);
8107        } catch (PackageParserException e) {
8108            throw PackageManagerException.from(e);
8109        } finally {
8110            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8111        }
8112    }
8113
8114    /**
8115     *  Traces a package scan.
8116     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8117     */
8118    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8119            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8120        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8121        try {
8122            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8123        } finally {
8124            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8125        }
8126    }
8127
8128    /**
8129     *  Scans a package and returns the newly parsed package.
8130     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8131     */
8132    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8133            long currentTime, UserHandle user) throws PackageManagerException {
8134        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8135        PackageParser pp = new PackageParser();
8136        pp.setSeparateProcesses(mSeparateProcesses);
8137        pp.setOnlyCoreApps(mOnlyCore);
8138        pp.setDisplayMetrics(mMetrics);
8139        pp.setCallback(mPackageParserCallback);
8140
8141        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8142            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8143        }
8144
8145        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8146        final PackageParser.Package pkg;
8147        try {
8148            pkg = pp.parsePackage(scanFile, parseFlags);
8149        } catch (PackageParserException e) {
8150            throw PackageManagerException.from(e);
8151        } finally {
8152            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8153        }
8154
8155        // Static shared libraries have synthetic package names
8156        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8157            renameStaticSharedLibraryPackage(pkg);
8158        }
8159
8160        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8161    }
8162
8163    /**
8164     *  Scans a package and returns the newly parsed package.
8165     *  @throws PackageManagerException on a parse error.
8166     */
8167    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8168            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8169            throws PackageManagerException {
8170        // If the package has children and this is the first dive in the function
8171        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8172        // packages (parent and children) would be successfully scanned before the
8173        // actual scan since scanning mutates internal state and we want to atomically
8174        // install the package and its children.
8175        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8176            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8177                scanFlags |= SCAN_CHECK_ONLY;
8178            }
8179        } else {
8180            scanFlags &= ~SCAN_CHECK_ONLY;
8181        }
8182
8183        // Scan the parent
8184        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8185                scanFlags, currentTime, user);
8186
8187        // Scan the children
8188        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8189        for (int i = 0; i < childCount; i++) {
8190            PackageParser.Package childPackage = pkg.childPackages.get(i);
8191            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8192                    currentTime, user);
8193        }
8194
8195
8196        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8197            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8198        }
8199
8200        return scannedPkg;
8201    }
8202
8203    /**
8204     *  Scans a package and returns the newly parsed package.
8205     *  @throws PackageManagerException on a parse error.
8206     */
8207    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8208            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8209            throws PackageManagerException {
8210        PackageSetting ps = null;
8211        PackageSetting updatedPkg;
8212        // reader
8213        synchronized (mPackages) {
8214            // Look to see if we already know about this package.
8215            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8216            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8217                // This package has been renamed to its original name.  Let's
8218                // use that.
8219                ps = mSettings.getPackageLPr(oldName);
8220            }
8221            // If there was no original package, see one for the real package name.
8222            if (ps == null) {
8223                ps = mSettings.getPackageLPr(pkg.packageName);
8224            }
8225            // Check to see if this package could be hiding/updating a system
8226            // package.  Must look for it either under the original or real
8227            // package name depending on our state.
8228            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8229            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8230
8231            // If this is a package we don't know about on the system partition, we
8232            // may need to remove disabled child packages on the system partition
8233            // or may need to not add child packages if the parent apk is updated
8234            // on the data partition and no longer defines this child package.
8235            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8236                // If this is a parent package for an updated system app and this system
8237                // app got an OTA update which no longer defines some of the child packages
8238                // we have to prune them from the disabled system packages.
8239                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8240                if (disabledPs != null) {
8241                    final int scannedChildCount = (pkg.childPackages != null)
8242                            ? pkg.childPackages.size() : 0;
8243                    final int disabledChildCount = disabledPs.childPackageNames != null
8244                            ? disabledPs.childPackageNames.size() : 0;
8245                    for (int i = 0; i < disabledChildCount; i++) {
8246                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8247                        boolean disabledPackageAvailable = false;
8248                        for (int j = 0; j < scannedChildCount; j++) {
8249                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8250                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8251                                disabledPackageAvailable = true;
8252                                break;
8253                            }
8254                         }
8255                         if (!disabledPackageAvailable) {
8256                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8257                         }
8258                    }
8259                }
8260            }
8261        }
8262
8263        final boolean isUpdatedPkg = updatedPkg != null;
8264        final boolean isUpdatedSystemPkg = isUpdatedPkg
8265                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8266        boolean isUpdatedPkgBetter = false;
8267        // First check if this is a system package that may involve an update
8268        if (isUpdatedSystemPkg) {
8269            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8270            // it needs to drop FLAG_PRIVILEGED.
8271            if (locationIsPrivileged(scanFile)) {
8272                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8273            } else {
8274                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8275            }
8276            // If new package is not located in "/oem" (e.g. due to an OTA),
8277            // it needs to drop FLAG_OEM.
8278            if (locationIsOem(scanFile)) {
8279                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8280            } else {
8281                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8282            }
8283
8284            if (ps != null && !ps.codePath.equals(scanFile)) {
8285                // The path has changed from what was last scanned...  check the
8286                // version of the new path against what we have stored to determine
8287                // what to do.
8288                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8289                if (pkg.mVersionCode <= ps.versionCode) {
8290                    // The system package has been updated and the code path does not match
8291                    // Ignore entry. Skip it.
8292                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8293                            + " ignored: updated version " + ps.versionCode
8294                            + " better than this " + pkg.mVersionCode);
8295                    if (!updatedPkg.codePath.equals(scanFile)) {
8296                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8297                                + ps.name + " changing from " + updatedPkg.codePathString
8298                                + " to " + scanFile);
8299                        updatedPkg.codePath = scanFile;
8300                        updatedPkg.codePathString = scanFile.toString();
8301                        updatedPkg.resourcePath = scanFile;
8302                        updatedPkg.resourcePathString = scanFile.toString();
8303                    }
8304                    updatedPkg.pkg = pkg;
8305                    updatedPkg.versionCode = pkg.mVersionCode;
8306
8307                    // Update the disabled system child packages to point to the package too.
8308                    final int childCount = updatedPkg.childPackageNames != null
8309                            ? updatedPkg.childPackageNames.size() : 0;
8310                    for (int i = 0; i < childCount; i++) {
8311                        String childPackageName = updatedPkg.childPackageNames.get(i);
8312                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8313                                childPackageName);
8314                        if (updatedChildPkg != null) {
8315                            updatedChildPkg.pkg = pkg;
8316                            updatedChildPkg.versionCode = pkg.mVersionCode;
8317                        }
8318                    }
8319                } else {
8320                    // The current app on the system partition is better than
8321                    // what we have updated to on the data partition; switch
8322                    // back to the system partition version.
8323                    // At this point, its safely assumed that package installation for
8324                    // apps in system partition will go through. If not there won't be a working
8325                    // version of the app
8326                    // writer
8327                    synchronized (mPackages) {
8328                        // Just remove the loaded entries from package lists.
8329                        mPackages.remove(ps.name);
8330                    }
8331
8332                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8333                            + " reverting from " + ps.codePathString
8334                            + ": new version " + pkg.mVersionCode
8335                            + " better than installed " + ps.versionCode);
8336
8337                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8338                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8339                    synchronized (mInstallLock) {
8340                        args.cleanUpResourcesLI();
8341                    }
8342                    synchronized (mPackages) {
8343                        mSettings.enableSystemPackageLPw(ps.name);
8344                    }
8345                    isUpdatedPkgBetter = true;
8346                }
8347            }
8348        }
8349
8350        String resourcePath = null;
8351        String baseResourcePath = null;
8352        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8353            if (ps != null && ps.resourcePathString != null) {
8354                resourcePath = ps.resourcePathString;
8355                baseResourcePath = ps.resourcePathString;
8356            } else {
8357                // Should not happen at all. Just log an error.
8358                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8359            }
8360        } else {
8361            resourcePath = pkg.codePath;
8362            baseResourcePath = pkg.baseCodePath;
8363        }
8364
8365        // Set application objects path explicitly.
8366        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8367        pkg.setApplicationInfoCodePath(pkg.codePath);
8368        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8369        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8370        pkg.setApplicationInfoResourcePath(resourcePath);
8371        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8372        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8373
8374        // throw an exception if we have an update to a system application, but, it's not more
8375        // recent than the package we've already scanned
8376        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8377            // Set CPU Abis to application info.
8378            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8379                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8380                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8381            } else {
8382                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8383                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8384            }
8385            pkg.mExtras = updatedPkg;
8386
8387            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8388                    + scanFile + " ignored: updated version " + ps.versionCode
8389                    + " better than this " + pkg.mVersionCode);
8390        }
8391
8392        if (isUpdatedPkg) {
8393            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8394            // initially
8395            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8396
8397            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8398            // flag set initially
8399            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8400                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8401            }
8402
8403            // An updated OEM app will not have the PARSE_IS_OEM
8404            // flag set initially
8405            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8406                policyFlags |= PackageParser.PARSE_IS_OEM;
8407            }
8408        }
8409
8410        // Verify certificates against what was last scanned
8411        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8412
8413        /*
8414         * A new system app appeared, but we already had a non-system one of the
8415         * same name installed earlier.
8416         */
8417        boolean shouldHideSystemApp = false;
8418        if (!isUpdatedPkg && ps != null
8419                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8420            /*
8421             * Check to make sure the signatures match first. If they don't,
8422             * wipe the installed application and its data.
8423             */
8424            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8425                    != PackageManager.SIGNATURE_MATCH) {
8426                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8427                        + " signatures don't match existing userdata copy; removing");
8428                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8429                        "scanPackageInternalLI")) {
8430                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8431                }
8432                ps = null;
8433            } else {
8434                /*
8435                 * If the newly-added system app is an older version than the
8436                 * already installed version, hide it. It will be scanned later
8437                 * and re-added like an update.
8438                 */
8439                if (pkg.mVersionCode <= ps.versionCode) {
8440                    shouldHideSystemApp = true;
8441                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8442                            + " but new version " + pkg.mVersionCode + " better than installed "
8443                            + ps.versionCode + "; hiding system");
8444                } else {
8445                    /*
8446                     * The newly found system app is a newer version that the
8447                     * one previously installed. Simply remove the
8448                     * already-installed application and replace it with our own
8449                     * while keeping the application data.
8450                     */
8451                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8452                            + " reverting from " + ps.codePathString + ": new version "
8453                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8454                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8455                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8456                    synchronized (mInstallLock) {
8457                        args.cleanUpResourcesLI();
8458                    }
8459                }
8460            }
8461        }
8462
8463        // The apk is forward locked (not public) if its code and resources
8464        // are kept in different files. (except for app in either system or
8465        // vendor path).
8466        // TODO grab this value from PackageSettings
8467        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8468            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8469                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8470            }
8471        }
8472
8473        final int userId = ((user == null) ? 0 : user.getIdentifier());
8474        if (ps != null && ps.getInstantApp(userId)) {
8475            scanFlags |= SCAN_AS_INSTANT_APP;
8476        }
8477        if (ps != null && ps.getVirtulalPreload(userId)) {
8478            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8479        }
8480
8481        // Note that we invoke the following method only if we are about to unpack an application
8482        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8483                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8484
8485        /*
8486         * If the system app should be overridden by a previously installed
8487         * data, hide the system app now and let the /data/app scan pick it up
8488         * again.
8489         */
8490        if (shouldHideSystemApp) {
8491            synchronized (mPackages) {
8492                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8493            }
8494        }
8495
8496        return scannedPkg;
8497    }
8498
8499    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8500        // Derive the new package synthetic package name
8501        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8502                + pkg.staticSharedLibVersion);
8503    }
8504
8505    private static String fixProcessName(String defProcessName,
8506            String processName) {
8507        if (processName == null) {
8508            return defProcessName;
8509        }
8510        return processName;
8511    }
8512
8513    /**
8514     * Enforces that only the system UID or root's UID can call a method exposed
8515     * via Binder.
8516     *
8517     * @param message used as message if SecurityException is thrown
8518     * @throws SecurityException if the caller is not system or root
8519     */
8520    private static final void enforceSystemOrRoot(String message) {
8521        final int uid = Binder.getCallingUid();
8522        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8523            throw new SecurityException(message);
8524        }
8525    }
8526
8527    @Override
8528    public void performFstrimIfNeeded() {
8529        enforceSystemOrRoot("Only the system can request fstrim");
8530
8531        // Before everything else, see whether we need to fstrim.
8532        try {
8533            IStorageManager sm = PackageHelper.getStorageManager();
8534            if (sm != null) {
8535                boolean doTrim = false;
8536                final long interval = android.provider.Settings.Global.getLong(
8537                        mContext.getContentResolver(),
8538                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8539                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8540                if (interval > 0) {
8541                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8542                    if (timeSinceLast > interval) {
8543                        doTrim = true;
8544                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8545                                + "; running immediately");
8546                    }
8547                }
8548                if (doTrim) {
8549                    final boolean dexOptDialogShown;
8550                    synchronized (mPackages) {
8551                        dexOptDialogShown = mDexOptDialogShown;
8552                    }
8553                    if (!isFirstBoot() && dexOptDialogShown) {
8554                        try {
8555                            ActivityManager.getService().showBootMessage(
8556                                    mContext.getResources().getString(
8557                                            R.string.android_upgrading_fstrim), true);
8558                        } catch (RemoteException e) {
8559                        }
8560                    }
8561                    sm.runMaintenance();
8562                }
8563            } else {
8564                Slog.e(TAG, "storageManager service unavailable!");
8565            }
8566        } catch (RemoteException e) {
8567            // Can't happen; StorageManagerService is local
8568        }
8569    }
8570
8571    @Override
8572    public void updatePackagesIfNeeded() {
8573        enforceSystemOrRoot("Only the system can request package update");
8574
8575        // We need to re-extract after an OTA.
8576        boolean causeUpgrade = isUpgrade();
8577
8578        // First boot or factory reset.
8579        // Note: we also handle devices that are upgrading to N right now as if it is their
8580        //       first boot, as they do not have profile data.
8581        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8582
8583        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8584        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8585
8586        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8587            return;
8588        }
8589
8590        List<PackageParser.Package> pkgs;
8591        synchronized (mPackages) {
8592            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8593        }
8594
8595        final long startTime = System.nanoTime();
8596        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8597                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8598                    false /* bootComplete */);
8599
8600        final int elapsedTimeSeconds =
8601                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8602
8603        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8604        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8605        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8606        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8607        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8608    }
8609
8610    /*
8611     * Return the prebuilt profile path given a package base code path.
8612     */
8613    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8614        return pkg.baseCodePath + ".prof";
8615    }
8616
8617    /**
8618     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8619     * containing statistics about the invocation. The array consists of three elements,
8620     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8621     * and {@code numberOfPackagesFailed}.
8622     */
8623    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8624            final String compilerFilter, boolean bootComplete) {
8625
8626        int numberOfPackagesVisited = 0;
8627        int numberOfPackagesOptimized = 0;
8628        int numberOfPackagesSkipped = 0;
8629        int numberOfPackagesFailed = 0;
8630        final int numberOfPackagesToDexopt = pkgs.size();
8631
8632        for (PackageParser.Package pkg : pkgs) {
8633            numberOfPackagesVisited++;
8634
8635            boolean useProfileForDexopt = false;
8636
8637            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8638                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8639                // that are already compiled.
8640                File profileFile = new File(getPrebuildProfilePath(pkg));
8641                // Copy profile if it exists.
8642                if (profileFile.exists()) {
8643                    try {
8644                        // We could also do this lazily before calling dexopt in
8645                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8646                        // is that we don't have a good way to say "do this only once".
8647                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8648                                pkg.applicationInfo.uid, pkg.packageName)) {
8649                            Log.e(TAG, "Installer failed to copy system profile!");
8650                        } else {
8651                            // Disabled as this causes speed-profile compilation during first boot
8652                            // even if things are already compiled.
8653                            // useProfileForDexopt = true;
8654                        }
8655                    } catch (Exception e) {
8656                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8657                                e);
8658                    }
8659                } else {
8660                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8661                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8662                    // minimize the number off apps being speed-profile compiled during first boot.
8663                    // The other paths will not change the filter.
8664                    if (disabledPs != null && disabledPs.pkg.isStub) {
8665                        // The package is the stub one, remove the stub suffix to get the normal
8666                        // package and APK names.
8667                        String systemProfilePath =
8668                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8669                        profileFile = new File(systemProfilePath);
8670                        // If we have a profile for a compressed APK, copy it to the reference
8671                        // location.
8672                        // Note that copying the profile here will cause it to override the
8673                        // reference profile every OTA even though the existing reference profile
8674                        // may have more data. We can't copy during decompression since the
8675                        // directories are not set up at that point.
8676                        if (profileFile.exists()) {
8677                            try {
8678                                // We could also do this lazily before calling dexopt in
8679                                // PackageDexOptimizer to prevent this happening on first boot. The
8680                                // issue is that we don't have a good way to say "do this only
8681                                // once".
8682                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8683                                        pkg.applicationInfo.uid, pkg.packageName)) {
8684                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8685                                } else {
8686                                    useProfileForDexopt = true;
8687                                }
8688                            } catch (Exception e) {
8689                                Log.e(TAG, "Failed to copy profile " +
8690                                        profileFile.getAbsolutePath() + " ", e);
8691                            }
8692                        }
8693                    }
8694                }
8695            }
8696
8697            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8698                if (DEBUG_DEXOPT) {
8699                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8700                }
8701                numberOfPackagesSkipped++;
8702                continue;
8703            }
8704
8705            if (DEBUG_DEXOPT) {
8706                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8707                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8708            }
8709
8710            if (showDialog) {
8711                try {
8712                    ActivityManager.getService().showBootMessage(
8713                            mContext.getResources().getString(R.string.android_upgrading_apk,
8714                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8715                } catch (RemoteException e) {
8716                }
8717                synchronized (mPackages) {
8718                    mDexOptDialogShown = true;
8719                }
8720            }
8721
8722            String pkgCompilerFilter = compilerFilter;
8723            if (useProfileForDexopt) {
8724                // Use background dexopt mode to try and use the profile. Note that this does not
8725                // guarantee usage of the profile.
8726                pkgCompilerFilter =
8727                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8728                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8729            }
8730
8731            // checkProfiles is false to avoid merging profiles during boot which
8732            // might interfere with background compilation (b/28612421).
8733            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8734            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8735            // trade-off worth doing to save boot time work.
8736            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8737            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8738                    pkg.packageName,
8739                    pkgCompilerFilter,
8740                    dexoptFlags));
8741
8742            switch (primaryDexOptStaus) {
8743                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8744                    numberOfPackagesOptimized++;
8745                    break;
8746                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8747                    numberOfPackagesSkipped++;
8748                    break;
8749                case PackageDexOptimizer.DEX_OPT_FAILED:
8750                    numberOfPackagesFailed++;
8751                    break;
8752                default:
8753                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8754                    break;
8755            }
8756        }
8757
8758        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8759                numberOfPackagesFailed };
8760    }
8761
8762    @Override
8763    public void notifyPackageUse(String packageName, int reason) {
8764        synchronized (mPackages) {
8765            final int callingUid = Binder.getCallingUid();
8766            final int callingUserId = UserHandle.getUserId(callingUid);
8767            if (getInstantAppPackageName(callingUid) != null) {
8768                if (!isCallerSameApp(packageName, callingUid)) {
8769                    return;
8770                }
8771            } else {
8772                if (isInstantApp(packageName, callingUserId)) {
8773                    return;
8774                }
8775            }
8776            notifyPackageUseLocked(packageName, reason);
8777        }
8778    }
8779
8780    private void notifyPackageUseLocked(String packageName, int reason) {
8781        final PackageParser.Package p = mPackages.get(packageName);
8782        if (p == null) {
8783            return;
8784        }
8785        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8786    }
8787
8788    @Override
8789    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8790            List<String> classPaths, String loaderIsa) {
8791        int userId = UserHandle.getCallingUserId();
8792        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8793        if (ai == null) {
8794            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8795                + loadingPackageName + ", user=" + userId);
8796            return;
8797        }
8798        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8799    }
8800
8801    @Override
8802    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8803            IDexModuleRegisterCallback callback) {
8804        int userId = UserHandle.getCallingUserId();
8805        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8806        DexManager.RegisterDexModuleResult result;
8807        if (ai == null) {
8808            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8809                     " calling user. package=" + packageName + ", user=" + userId);
8810            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8811        } else {
8812            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8813        }
8814
8815        if (callback != null) {
8816            mHandler.post(() -> {
8817                try {
8818                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8819                } catch (RemoteException e) {
8820                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8821                }
8822            });
8823        }
8824    }
8825
8826    /**
8827     * Ask the package manager to perform a dex-opt with the given compiler filter.
8828     *
8829     * Note: exposed only for the shell command to allow moving packages explicitly to a
8830     *       definite state.
8831     */
8832    @Override
8833    public boolean performDexOptMode(String packageName,
8834            boolean checkProfiles, String targetCompilerFilter, boolean force,
8835            boolean bootComplete, String splitName) {
8836        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8837                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8838                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8839        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8840                splitName, flags));
8841    }
8842
8843    /**
8844     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8845     * secondary dex files belonging to the given package.
8846     *
8847     * Note: exposed only for the shell command to allow moving packages explicitly to a
8848     *       definite state.
8849     */
8850    @Override
8851    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8852            boolean force) {
8853        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8854                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8855                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8856                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8857        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8858    }
8859
8860    /*package*/ boolean performDexOpt(DexoptOptions options) {
8861        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8862            return false;
8863        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8864            return false;
8865        }
8866
8867        if (options.isDexoptOnlySecondaryDex()) {
8868            return mDexManager.dexoptSecondaryDex(options);
8869        } else {
8870            int dexoptStatus = performDexOptWithStatus(options);
8871            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8872        }
8873    }
8874
8875    /**
8876     * Perform dexopt on the given package and return one of following result:
8877     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8878     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8879     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8880     */
8881    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8882        return performDexOptTraced(options);
8883    }
8884
8885    private int performDexOptTraced(DexoptOptions options) {
8886        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8887        try {
8888            return performDexOptInternal(options);
8889        } finally {
8890            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8891        }
8892    }
8893
8894    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8895    // if the package can now be considered up to date for the given filter.
8896    private int performDexOptInternal(DexoptOptions options) {
8897        PackageParser.Package p;
8898        synchronized (mPackages) {
8899            p = mPackages.get(options.getPackageName());
8900            if (p == null) {
8901                // Package could not be found. Report failure.
8902                return PackageDexOptimizer.DEX_OPT_FAILED;
8903            }
8904            mPackageUsage.maybeWriteAsync(mPackages);
8905            mCompilerStats.maybeWriteAsync();
8906        }
8907        long callingId = Binder.clearCallingIdentity();
8908        try {
8909            synchronized (mInstallLock) {
8910                return performDexOptInternalWithDependenciesLI(p, options);
8911            }
8912        } finally {
8913            Binder.restoreCallingIdentity(callingId);
8914        }
8915    }
8916
8917    public ArraySet<String> getOptimizablePackages() {
8918        ArraySet<String> pkgs = new ArraySet<String>();
8919        synchronized (mPackages) {
8920            for (PackageParser.Package p : mPackages.values()) {
8921                if (PackageDexOptimizer.canOptimizePackage(p)) {
8922                    pkgs.add(p.packageName);
8923                }
8924            }
8925        }
8926        return pkgs;
8927    }
8928
8929    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8930            DexoptOptions options) {
8931        // Select the dex optimizer based on the force parameter.
8932        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8933        //       allocate an object here.
8934        PackageDexOptimizer pdo = options.isForce()
8935                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8936                : mPackageDexOptimizer;
8937
8938        // Dexopt all dependencies first. Note: we ignore the return value and march on
8939        // on errors.
8940        // Note that we are going to call performDexOpt on those libraries as many times as
8941        // they are referenced in packages. When we do a batch of performDexOpt (for example
8942        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8943        // and the first package that uses the library will dexopt it. The
8944        // others will see that the compiled code for the library is up to date.
8945        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8946        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8947        if (!deps.isEmpty()) {
8948            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
8949                    options.getCompilerFilter(), options.getSplitName(),
8950                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
8951            for (PackageParser.Package depPackage : deps) {
8952                // TODO: Analyze and investigate if we (should) profile libraries.
8953                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8954                        getOrCreateCompilerPackageStats(depPackage),
8955                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
8956            }
8957        }
8958        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
8959                getOrCreateCompilerPackageStats(p),
8960                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
8961    }
8962
8963    /**
8964     * Reconcile the information we have about the secondary dex files belonging to
8965     * {@code packagName} and the actual dex files. For all dex files that were
8966     * deleted, update the internal records and delete the generated oat files.
8967     */
8968    @Override
8969    public void reconcileSecondaryDexFiles(String packageName) {
8970        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8971            return;
8972        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
8973            return;
8974        }
8975        mDexManager.reconcileSecondaryDexFiles(packageName);
8976    }
8977
8978    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8979    // a reference there.
8980    /*package*/ DexManager getDexManager() {
8981        return mDexManager;
8982    }
8983
8984    /**
8985     * Execute the background dexopt job immediately.
8986     */
8987    @Override
8988    public boolean runBackgroundDexoptJob() {
8989        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8990            return false;
8991        }
8992        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8993    }
8994
8995    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8996        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8997                || p.usesStaticLibraries != null) {
8998            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8999            Set<String> collectedNames = new HashSet<>();
9000            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9001
9002            retValue.remove(p);
9003
9004            return retValue;
9005        } else {
9006            return Collections.emptyList();
9007        }
9008    }
9009
9010    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9011            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9012        if (!collectedNames.contains(p.packageName)) {
9013            collectedNames.add(p.packageName);
9014            collected.add(p);
9015
9016            if (p.usesLibraries != null) {
9017                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9018                        null, collected, collectedNames);
9019            }
9020            if (p.usesOptionalLibraries != null) {
9021                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9022                        null, collected, collectedNames);
9023            }
9024            if (p.usesStaticLibraries != null) {
9025                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9026                        p.usesStaticLibrariesVersions, collected, collectedNames);
9027            }
9028        }
9029    }
9030
9031    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9032            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9033        final int libNameCount = libs.size();
9034        for (int i = 0; i < libNameCount; i++) {
9035            String libName = libs.get(i);
9036            int version = (versions != null && versions.length == libNameCount)
9037                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9038            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9039            if (libPkg != null) {
9040                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9041            }
9042        }
9043    }
9044
9045    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9046        synchronized (mPackages) {
9047            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9048            if (libEntry != null) {
9049                return mPackages.get(libEntry.apk);
9050            }
9051            return null;
9052        }
9053    }
9054
9055    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9056        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9057        if (versionedLib == null) {
9058            return null;
9059        }
9060        return versionedLib.get(version);
9061    }
9062
9063    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9064        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9065                pkg.staticSharedLibName);
9066        if (versionedLib == null) {
9067            return null;
9068        }
9069        int previousLibVersion = -1;
9070        final int versionCount = versionedLib.size();
9071        for (int i = 0; i < versionCount; i++) {
9072            final int libVersion = versionedLib.keyAt(i);
9073            if (libVersion < pkg.staticSharedLibVersion) {
9074                previousLibVersion = Math.max(previousLibVersion, libVersion);
9075            }
9076        }
9077        if (previousLibVersion >= 0) {
9078            return versionedLib.get(previousLibVersion);
9079        }
9080        return null;
9081    }
9082
9083    public void shutdown() {
9084        mPackageUsage.writeNow(mPackages);
9085        mCompilerStats.writeNow();
9086        mDexManager.writePackageDexUsageNow();
9087    }
9088
9089    @Override
9090    public void dumpProfiles(String packageName) {
9091        PackageParser.Package pkg;
9092        synchronized (mPackages) {
9093            pkg = mPackages.get(packageName);
9094            if (pkg == null) {
9095                throw new IllegalArgumentException("Unknown package: " + packageName);
9096            }
9097        }
9098        /* Only the shell, root, or the app user should be able to dump profiles. */
9099        int callingUid = Binder.getCallingUid();
9100        if (callingUid != Process.SHELL_UID &&
9101            callingUid != Process.ROOT_UID &&
9102            callingUid != pkg.applicationInfo.uid) {
9103            throw new SecurityException("dumpProfiles");
9104        }
9105
9106        synchronized (mInstallLock) {
9107            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9108            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9109            try {
9110                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9111                String codePaths = TextUtils.join(";", allCodePaths);
9112                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9113            } catch (InstallerException e) {
9114                Slog.w(TAG, "Failed to dump profiles", e);
9115            }
9116            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9117        }
9118    }
9119
9120    @Override
9121    public void forceDexOpt(String packageName) {
9122        enforceSystemOrRoot("forceDexOpt");
9123
9124        PackageParser.Package pkg;
9125        synchronized (mPackages) {
9126            pkg = mPackages.get(packageName);
9127            if (pkg == null) {
9128                throw new IllegalArgumentException("Unknown package: " + packageName);
9129            }
9130        }
9131
9132        synchronized (mInstallLock) {
9133            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9134
9135            // Whoever is calling forceDexOpt wants a compiled package.
9136            // Don't use profiles since that may cause compilation to be skipped.
9137            final int res = performDexOptInternalWithDependenciesLI(
9138                    pkg,
9139                    new DexoptOptions(packageName,
9140                            getDefaultCompilerFilter(),
9141                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9142
9143            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9144            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9145                throw new IllegalStateException("Failed to dexopt: " + res);
9146            }
9147        }
9148    }
9149
9150    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9151        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9152            Slog.w(TAG, "Unable to update from " + oldPkg.name
9153                    + " to " + newPkg.packageName
9154                    + ": old package not in system partition");
9155            return false;
9156        } else if (mPackages.get(oldPkg.name) != null) {
9157            Slog.w(TAG, "Unable to update from " + oldPkg.name
9158                    + " to " + newPkg.packageName
9159                    + ": old package still exists");
9160            return false;
9161        }
9162        return true;
9163    }
9164
9165    void removeCodePathLI(File codePath) {
9166        if (codePath.isDirectory()) {
9167            try {
9168                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9169            } catch (InstallerException e) {
9170                Slog.w(TAG, "Failed to remove code path", e);
9171            }
9172        } else {
9173            codePath.delete();
9174        }
9175    }
9176
9177    private int[] resolveUserIds(int userId) {
9178        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9179    }
9180
9181    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9182        if (pkg == null) {
9183            Slog.wtf(TAG, "Package was null!", new Throwable());
9184            return;
9185        }
9186        clearAppDataLeafLIF(pkg, userId, flags);
9187        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9188        for (int i = 0; i < childCount; i++) {
9189            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9190        }
9191    }
9192
9193    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9194        final PackageSetting ps;
9195        synchronized (mPackages) {
9196            ps = mSettings.mPackages.get(pkg.packageName);
9197        }
9198        for (int realUserId : resolveUserIds(userId)) {
9199            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9200            try {
9201                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9202                        ceDataInode);
9203            } catch (InstallerException e) {
9204                Slog.w(TAG, String.valueOf(e));
9205            }
9206        }
9207    }
9208
9209    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9210        if (pkg == null) {
9211            Slog.wtf(TAG, "Package was null!", new Throwable());
9212            return;
9213        }
9214        destroyAppDataLeafLIF(pkg, userId, flags);
9215        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9216        for (int i = 0; i < childCount; i++) {
9217            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9218        }
9219    }
9220
9221    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9222        final PackageSetting ps;
9223        synchronized (mPackages) {
9224            ps = mSettings.mPackages.get(pkg.packageName);
9225        }
9226        for (int realUserId : resolveUserIds(userId)) {
9227            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9228            try {
9229                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9230                        ceDataInode);
9231            } catch (InstallerException e) {
9232                Slog.w(TAG, String.valueOf(e));
9233            }
9234            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9235        }
9236    }
9237
9238    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9239        if (pkg == null) {
9240            Slog.wtf(TAG, "Package was null!", new Throwable());
9241            return;
9242        }
9243        destroyAppProfilesLeafLIF(pkg);
9244        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9245        for (int i = 0; i < childCount; i++) {
9246            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9247        }
9248    }
9249
9250    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9251        try {
9252            mInstaller.destroyAppProfiles(pkg.packageName);
9253        } catch (InstallerException e) {
9254            Slog.w(TAG, String.valueOf(e));
9255        }
9256    }
9257
9258    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9259        if (pkg == null) {
9260            Slog.wtf(TAG, "Package was null!", new Throwable());
9261            return;
9262        }
9263        clearAppProfilesLeafLIF(pkg);
9264        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9265        for (int i = 0; i < childCount; i++) {
9266            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9267        }
9268    }
9269
9270    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9271        try {
9272            mInstaller.clearAppProfiles(pkg.packageName);
9273        } catch (InstallerException e) {
9274            Slog.w(TAG, String.valueOf(e));
9275        }
9276    }
9277
9278    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9279            long lastUpdateTime) {
9280        // Set parent install/update time
9281        PackageSetting ps = (PackageSetting) pkg.mExtras;
9282        if (ps != null) {
9283            ps.firstInstallTime = firstInstallTime;
9284            ps.lastUpdateTime = lastUpdateTime;
9285        }
9286        // Set children install/update time
9287        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9288        for (int i = 0; i < childCount; i++) {
9289            PackageParser.Package childPkg = pkg.childPackages.get(i);
9290            ps = (PackageSetting) childPkg.mExtras;
9291            if (ps != null) {
9292                ps.firstInstallTime = firstInstallTime;
9293                ps.lastUpdateTime = lastUpdateTime;
9294            }
9295        }
9296    }
9297
9298    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9299            SharedLibraryEntry file,
9300            PackageParser.Package changingLib) {
9301        if (file.path != null) {
9302            usesLibraryFiles.add(file.path);
9303            return;
9304        }
9305        PackageParser.Package p = mPackages.get(file.apk);
9306        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9307            // If we are doing this while in the middle of updating a library apk,
9308            // then we need to make sure to use that new apk for determining the
9309            // dependencies here.  (We haven't yet finished committing the new apk
9310            // to the package manager state.)
9311            if (p == null || p.packageName.equals(changingLib.packageName)) {
9312                p = changingLib;
9313            }
9314        }
9315        if (p != null) {
9316            usesLibraryFiles.addAll(p.getAllCodePaths());
9317            if (p.usesLibraryFiles != null) {
9318                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9319            }
9320        }
9321    }
9322
9323    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9324            PackageParser.Package changingLib) throws PackageManagerException {
9325        if (pkg == null) {
9326            return;
9327        }
9328        // The collection used here must maintain the order of addition (so
9329        // that libraries are searched in the correct order) and must have no
9330        // duplicates.
9331        Set<String> usesLibraryFiles = null;
9332        if (pkg.usesLibraries != null) {
9333            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9334                    null, null, pkg.packageName, changingLib, true,
9335                    pkg.applicationInfo.targetSdkVersion, null);
9336        }
9337        if (pkg.usesStaticLibraries != null) {
9338            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9339                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9340                    pkg.packageName, changingLib, true,
9341                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9342        }
9343        if (pkg.usesOptionalLibraries != null) {
9344            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9345                    null, null, pkg.packageName, changingLib, false,
9346                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9347        }
9348        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9349            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9350        } else {
9351            pkg.usesLibraryFiles = null;
9352        }
9353    }
9354
9355    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9356            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9357            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9358            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9359            throws PackageManagerException {
9360        final int libCount = requestedLibraries.size();
9361        for (int i = 0; i < libCount; i++) {
9362            final String libName = requestedLibraries.get(i);
9363            final int libVersion = requiredVersions != null ? requiredVersions[i]
9364                    : SharedLibraryInfo.VERSION_UNDEFINED;
9365            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9366            if (libEntry == null) {
9367                if (required) {
9368                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9369                            "Package " + packageName + " requires unavailable shared library "
9370                                    + libName + "; failing!");
9371                } else if (DEBUG_SHARED_LIBRARIES) {
9372                    Slog.i(TAG, "Package " + packageName
9373                            + " desires unavailable shared library "
9374                            + libName + "; ignoring!");
9375                }
9376            } else {
9377                if (requiredVersions != null && requiredCertDigests != null) {
9378                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9379                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9380                            "Package " + packageName + " requires unavailable static shared"
9381                                    + " library " + libName + " version "
9382                                    + libEntry.info.getVersion() + "; failing!");
9383                    }
9384
9385                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9386                    if (libPkg == null) {
9387                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9388                                "Package " + packageName + " requires unavailable static shared"
9389                                        + " library; failing!");
9390                    }
9391
9392                    final String[] expectedCertDigests = requiredCertDigests[i];
9393                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9394                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9395                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9396                            : PackageUtils.computeSignaturesSha256Digests(
9397                                    new Signature[]{libPkg.mSignatures[0]});
9398
9399                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9400                    // target O we don't parse the "additional-certificate" tags similarly
9401                    // how we only consider all certs only for apps targeting O (see above).
9402                    // Therefore, the size check is safe to make.
9403                    if (expectedCertDigests.length != libCertDigests.length) {
9404                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9405                                "Package " + packageName + " requires differently signed" +
9406                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9407                    }
9408
9409                    // Use a predictable order as signature order may vary
9410                    Arrays.sort(libCertDigests);
9411                    Arrays.sort(expectedCertDigests);
9412
9413                    final int certCount = libCertDigests.length;
9414                    for (int j = 0; j < certCount; j++) {
9415                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9416                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9417                                    "Package " + packageName + " requires differently signed" +
9418                                            " static shared library; failing!");
9419                        }
9420                    }
9421                }
9422
9423                if (outUsedLibraries == null) {
9424                    // Use LinkedHashSet to preserve the order of files added to
9425                    // usesLibraryFiles while eliminating duplicates.
9426                    outUsedLibraries = new LinkedHashSet<>();
9427                }
9428                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9429            }
9430        }
9431        return outUsedLibraries;
9432    }
9433
9434    private static boolean hasString(List<String> list, List<String> which) {
9435        if (list == null) {
9436            return false;
9437        }
9438        for (int i=list.size()-1; i>=0; i--) {
9439            for (int j=which.size()-1; j>=0; j--) {
9440                if (which.get(j).equals(list.get(i))) {
9441                    return true;
9442                }
9443            }
9444        }
9445        return false;
9446    }
9447
9448    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9449            PackageParser.Package changingPkg) {
9450        ArrayList<PackageParser.Package> res = null;
9451        for (PackageParser.Package pkg : mPackages.values()) {
9452            if (changingPkg != null
9453                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9454                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9455                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9456                            changingPkg.staticSharedLibName)) {
9457                return null;
9458            }
9459            if (res == null) {
9460                res = new ArrayList<>();
9461            }
9462            res.add(pkg);
9463            try {
9464                updateSharedLibrariesLPr(pkg, changingPkg);
9465            } catch (PackageManagerException e) {
9466                // If a system app update or an app and a required lib missing we
9467                // delete the package and for updated system apps keep the data as
9468                // it is better for the user to reinstall than to be in an limbo
9469                // state. Also libs disappearing under an app should never happen
9470                // - just in case.
9471                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9472                    final int flags = pkg.isUpdatedSystemApp()
9473                            ? PackageManager.DELETE_KEEP_DATA : 0;
9474                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9475                            flags , null, true, null);
9476                }
9477                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9478            }
9479        }
9480        return res;
9481    }
9482
9483    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9484            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9485                    throws PackageManagerException {
9486        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9487        // If the package has children and this is the first dive in the function
9488        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9489        // whether all packages (parent and children) would be successfully scanned
9490        // before the actual scan since scanning mutates internal state and we want
9491        // to atomically install the package and its children.
9492        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9493            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9494                scanFlags |= SCAN_CHECK_ONLY;
9495            }
9496        } else {
9497            scanFlags &= ~SCAN_CHECK_ONLY;
9498        }
9499
9500        final PackageParser.Package scannedPkg;
9501        try {
9502            // Scan the parent
9503            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9504            // Scan the children
9505            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9506            for (int i = 0; i < childCount; i++) {
9507                PackageParser.Package childPkg = pkg.childPackages.get(i);
9508                scanPackageLI(childPkg, policyFlags,
9509                        scanFlags, currentTime, user);
9510            }
9511        } finally {
9512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9513        }
9514
9515        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9516            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9517        }
9518
9519        return scannedPkg;
9520    }
9521
9522    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9523            int scanFlags, long currentTime, @Nullable UserHandle user)
9524                    throws PackageManagerException {
9525        boolean success = false;
9526        try {
9527            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9528                    currentTime, user);
9529            success = true;
9530            return res;
9531        } finally {
9532            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9533                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9534                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9535                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9536                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9537            }
9538        }
9539    }
9540
9541    /**
9542     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9543     */
9544    private static boolean apkHasCode(String fileName) {
9545        StrictJarFile jarFile = null;
9546        try {
9547            jarFile = new StrictJarFile(fileName,
9548                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9549            return jarFile.findEntry("classes.dex") != null;
9550        } catch (IOException ignore) {
9551        } finally {
9552            try {
9553                if (jarFile != null) {
9554                    jarFile.close();
9555                }
9556            } catch (IOException ignore) {}
9557        }
9558        return false;
9559    }
9560
9561    /**
9562     * Enforces code policy for the package. This ensures that if an APK has
9563     * declared hasCode="true" in its manifest that the APK actually contains
9564     * code.
9565     *
9566     * @throws PackageManagerException If bytecode could not be found when it should exist
9567     */
9568    private static void assertCodePolicy(PackageParser.Package pkg)
9569            throws PackageManagerException {
9570        final boolean shouldHaveCode =
9571                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9572        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9573            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9574                    "Package " + pkg.baseCodePath + " code is missing");
9575        }
9576
9577        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9578            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9579                final boolean splitShouldHaveCode =
9580                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9581                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9582                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9583                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9584                }
9585            }
9586        }
9587    }
9588
9589    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9590            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9591                    throws PackageManagerException {
9592        if (DEBUG_PACKAGE_SCANNING) {
9593            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9594                Log.d(TAG, "Scanning package " + pkg.packageName);
9595        }
9596
9597        applyPolicy(pkg, policyFlags);
9598
9599        assertPackageIsValid(pkg, policyFlags, scanFlags);
9600
9601        if (Build.IS_DEBUGGABLE &&
9602                pkg.isPrivileged() &&
9603                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
9604            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9605        }
9606
9607        // Initialize package source and resource directories
9608        final File scanFile = new File(pkg.codePath);
9609        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9610        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9611
9612        SharedUserSetting suid = null;
9613        PackageSetting pkgSetting = null;
9614
9615        // Getting the package setting may have a side-effect, so if we
9616        // are only checking if scan would succeed, stash a copy of the
9617        // old setting to restore at the end.
9618        PackageSetting nonMutatedPs = null;
9619
9620        // We keep references to the derived CPU Abis from settings in oder to reuse
9621        // them in the case where we're not upgrading or booting for the first time.
9622        String primaryCpuAbiFromSettings = null;
9623        String secondaryCpuAbiFromSettings = null;
9624
9625        // writer
9626        synchronized (mPackages) {
9627            if (pkg.mSharedUserId != null) {
9628                // SIDE EFFECTS; may potentially allocate a new shared user
9629                suid = mSettings.getSharedUserLPw(
9630                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9631                if (DEBUG_PACKAGE_SCANNING) {
9632                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9633                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9634                                + "): packages=" + suid.packages);
9635                }
9636            }
9637
9638            // Check if we are renaming from an original package name.
9639            PackageSetting origPackage = null;
9640            String realName = null;
9641            if (pkg.mOriginalPackages != null) {
9642                // This package may need to be renamed to a previously
9643                // installed name.  Let's check on that...
9644                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9645                if (pkg.mOriginalPackages.contains(renamed)) {
9646                    // This package had originally been installed as the
9647                    // original name, and we have already taken care of
9648                    // transitioning to the new one.  Just update the new
9649                    // one to continue using the old name.
9650                    realName = pkg.mRealPackage;
9651                    if (!pkg.packageName.equals(renamed)) {
9652                        // Callers into this function may have already taken
9653                        // care of renaming the package; only do it here if
9654                        // it is not already done.
9655                        pkg.setPackageName(renamed);
9656                    }
9657                } else {
9658                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9659                        if ((origPackage = mSettings.getPackageLPr(
9660                                pkg.mOriginalPackages.get(i))) != null) {
9661                            // We do have the package already installed under its
9662                            // original name...  should we use it?
9663                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9664                                // New package is not compatible with original.
9665                                origPackage = null;
9666                                continue;
9667                            } else if (origPackage.sharedUser != null) {
9668                                // Make sure uid is compatible between packages.
9669                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9670                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9671                                            + " to " + pkg.packageName + ": old uid "
9672                                            + origPackage.sharedUser.name
9673                                            + " differs from " + pkg.mSharedUserId);
9674                                    origPackage = null;
9675                                    continue;
9676                                }
9677                                // TODO: Add case when shared user id is added [b/28144775]
9678                            } else {
9679                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9680                                        + pkg.packageName + " to old name " + origPackage.name);
9681                            }
9682                            break;
9683                        }
9684                    }
9685                }
9686            }
9687
9688            if (mTransferedPackages.contains(pkg.packageName)) {
9689                Slog.w(TAG, "Package " + pkg.packageName
9690                        + " was transferred to another, but its .apk remains");
9691            }
9692
9693            // See comments in nonMutatedPs declaration
9694            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9695                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9696                if (foundPs != null) {
9697                    nonMutatedPs = new PackageSetting(foundPs);
9698                }
9699            }
9700
9701            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9702                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9703                if (foundPs != null) {
9704                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9705                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9706                }
9707            }
9708
9709            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9710            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9711                PackageManagerService.reportSettingsProblem(Log.WARN,
9712                        "Package " + pkg.packageName + " shared user changed from "
9713                                + (pkgSetting.sharedUser != null
9714                                        ? pkgSetting.sharedUser.name : "<nothing>")
9715                                + " to "
9716                                + (suid != null ? suid.name : "<nothing>")
9717                                + "; replacing with new");
9718                pkgSetting = null;
9719            }
9720            final PackageSetting oldPkgSetting =
9721                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9722            final PackageSetting disabledPkgSetting =
9723                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9724
9725            String[] usesStaticLibraries = null;
9726            if (pkg.usesStaticLibraries != null) {
9727                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9728                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9729            }
9730
9731            if (pkgSetting == null) {
9732                final String parentPackageName = (pkg.parentPackage != null)
9733                        ? pkg.parentPackage.packageName : null;
9734                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9735                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
9736                // REMOVE SharedUserSetting from method; update in a separate call
9737                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9738                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9739                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9740                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9741                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9742                        true /*allowInstall*/, instantApp, virtualPreload,
9743                        parentPackageName, pkg.getChildPackageNames(),
9744                        UserManagerService.getInstance(), usesStaticLibraries,
9745                        pkg.usesStaticLibrariesVersions);
9746                // SIDE EFFECTS; updates system state; move elsewhere
9747                if (origPackage != null) {
9748                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9749                }
9750                mSettings.addUserToSettingLPw(pkgSetting);
9751            } else {
9752                // REMOVE SharedUserSetting from method; update in a separate call.
9753                //
9754                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9755                // secondaryCpuAbi are not known at this point so we always update them
9756                // to null here, only to reset them at a later point.
9757                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9758                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9759                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9760                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9761                        UserManagerService.getInstance(), usesStaticLibraries,
9762                        pkg.usesStaticLibrariesVersions);
9763            }
9764            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9765            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9766
9767            // SIDE EFFECTS; modifies system state; move elsewhere
9768            if (pkgSetting.origPackage != null) {
9769                // If we are first transitioning from an original package,
9770                // fix up the new package's name now.  We need to do this after
9771                // looking up the package under its new name, so getPackageLP
9772                // can take care of fiddling things correctly.
9773                pkg.setPackageName(origPackage.name);
9774
9775                // File a report about this.
9776                String msg = "New package " + pkgSetting.realName
9777                        + " renamed to replace old package " + pkgSetting.name;
9778                reportSettingsProblem(Log.WARN, msg);
9779
9780                // Make a note of it.
9781                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9782                    mTransferedPackages.add(origPackage.name);
9783                }
9784
9785                // No longer need to retain this.
9786                pkgSetting.origPackage = null;
9787            }
9788
9789            // SIDE EFFECTS; modifies system state; move elsewhere
9790            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9791                // Make a note of it.
9792                mTransferedPackages.add(pkg.packageName);
9793            }
9794
9795            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9796                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9797            }
9798
9799            if ((scanFlags & SCAN_BOOTING) == 0
9800                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9801                // Check all shared libraries and map to their actual file path.
9802                // We only do this here for apps not on a system dir, because those
9803                // are the only ones that can fail an install due to this.  We
9804                // will take care of the system apps by updating all of their
9805                // library paths after the scan is done. Also during the initial
9806                // scan don't update any libs as we do this wholesale after all
9807                // apps are scanned to avoid dependency based scanning.
9808                updateSharedLibrariesLPr(pkg, null);
9809            }
9810
9811            if (mFoundPolicyFile) {
9812                SELinuxMMAC.assignSeInfoValue(pkg);
9813            }
9814            pkg.applicationInfo.uid = pkgSetting.appId;
9815            pkg.mExtras = pkgSetting;
9816
9817
9818            // Static shared libs have same package with different versions where
9819            // we internally use a synthetic package name to allow multiple versions
9820            // of the same package, therefore we need to compare signatures against
9821            // the package setting for the latest library version.
9822            PackageSetting signatureCheckPs = pkgSetting;
9823            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9824                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9825                if (libraryEntry != null) {
9826                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9827                }
9828            }
9829
9830            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9831            if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9832                if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9833                    // We just determined the app is signed correctly, so bring
9834                    // over the latest parsed certs.
9835                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9836                } else {
9837                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9838                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9839                                "Package " + pkg.packageName + " upgrade keys do not match the "
9840                                + "previously installed version");
9841                    } else {
9842                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9843                        String msg = "System package " + pkg.packageName
9844                                + " signature changed; retaining data.";
9845                        reportSettingsProblem(Log.WARN, msg);
9846                    }
9847                }
9848            } else {
9849                try {
9850                    final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9851                    final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9852                    final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9853                            compareCompat, compareRecover);
9854                    // The new KeySets will be re-added later in the scanning process.
9855                    if (compatMatch) {
9856                        synchronized (mPackages) {
9857                            ksms.removeAppKeySetDataLPw(pkg.packageName);
9858                        }
9859                    }
9860                    // We just determined the app is signed correctly, so bring
9861                    // over the latest parsed certs.
9862                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9863                } catch (PackageManagerException e) {
9864                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9865                        throw e;
9866                    }
9867                    // The signature has changed, but this package is in the system
9868                    // image...  let's recover!
9869                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9870                    // However...  if this package is part of a shared user, but it
9871                    // doesn't match the signature of the shared user, let's fail.
9872                    // What this means is that you can't change the signatures
9873                    // associated with an overall shared user, which doesn't seem all
9874                    // that unreasonable.
9875                    if (signatureCheckPs.sharedUser != null) {
9876                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9877                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9878                            throw new PackageManagerException(
9879                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9880                                    "Signature mismatch for shared user: "
9881                                            + pkgSetting.sharedUser);
9882                        }
9883                    }
9884                    // File a report about this.
9885                    String msg = "System package " + pkg.packageName
9886                            + " signature changed; retaining data.";
9887                    reportSettingsProblem(Log.WARN, msg);
9888                }
9889            }
9890
9891            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9892                // This package wants to adopt ownership of permissions from
9893                // another package.
9894                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9895                    final String origName = pkg.mAdoptPermissions.get(i);
9896                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9897                    if (orig != null) {
9898                        if (verifyPackageUpdateLPr(orig, pkg)) {
9899                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9900                                    + pkg.packageName);
9901                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9902                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9903                        }
9904                    }
9905                }
9906            }
9907        }
9908
9909        pkg.applicationInfo.processName = fixProcessName(
9910                pkg.applicationInfo.packageName,
9911                pkg.applicationInfo.processName);
9912
9913        if (pkg != mPlatformPackage) {
9914            // Get all of our default paths setup
9915            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9916        }
9917
9918        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9919
9920        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9921            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9922                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9923                final boolean extractNativeLibs = !pkg.isLibrary();
9924                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
9925                        mAppLib32InstallDir);
9926                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9927
9928                // Some system apps still use directory structure for native libraries
9929                // in which case we might end up not detecting abi solely based on apk
9930                // structure. Try to detect abi based on directory structure.
9931                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9932                        pkg.applicationInfo.primaryCpuAbi == null) {
9933                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9934                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9935                }
9936            } else {
9937                // This is not a first boot or an upgrade, don't bother deriving the
9938                // ABI during the scan. Instead, trust the value that was stored in the
9939                // package setting.
9940                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9941                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9942
9943                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9944
9945                if (DEBUG_ABI_SELECTION) {
9946                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9947                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9948                        pkg.applicationInfo.secondaryCpuAbi);
9949                }
9950            }
9951        } else {
9952            if ((scanFlags & SCAN_MOVE) != 0) {
9953                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9954                // but we already have this packages package info in the PackageSetting. We just
9955                // use that and derive the native library path based on the new codepath.
9956                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9957                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9958            }
9959
9960            // Set native library paths again. For moves, the path will be updated based on the
9961            // ABIs we've determined above. For non-moves, the path will be updated based on the
9962            // ABIs we determined during compilation, but the path will depend on the final
9963            // package path (after the rename away from the stage path).
9964            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9965        }
9966
9967        // This is a special case for the "system" package, where the ABI is
9968        // dictated by the zygote configuration (and init.rc). We should keep track
9969        // of this ABI so that we can deal with "normal" applications that run under
9970        // the same UID correctly.
9971        if (mPlatformPackage == pkg) {
9972            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9973                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9974        }
9975
9976        // If there's a mismatch between the abi-override in the package setting
9977        // and the abiOverride specified for the install. Warn about this because we
9978        // would've already compiled the app without taking the package setting into
9979        // account.
9980        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9981            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9982                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9983                        " for package " + pkg.packageName);
9984            }
9985        }
9986
9987        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9988        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9989        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9990
9991        // Copy the derived override back to the parsed package, so that we can
9992        // update the package settings accordingly.
9993        pkg.cpuAbiOverride = cpuAbiOverride;
9994
9995        if (DEBUG_ABI_SELECTION) {
9996            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9997                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9998                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9999        }
10000
10001        // Push the derived path down into PackageSettings so we know what to
10002        // clean up at uninstall time.
10003        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10004
10005        if (DEBUG_ABI_SELECTION) {
10006            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10007                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10008                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10009        }
10010
10011        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10012        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10013            // We don't do this here during boot because we can do it all
10014            // at once after scanning all existing packages.
10015            //
10016            // We also do this *before* we perform dexopt on this package, so that
10017            // we can avoid redundant dexopts, and also to make sure we've got the
10018            // code and package path correct.
10019            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10020        }
10021
10022        if (mFactoryTest && pkg.requestedPermissions.contains(
10023                android.Manifest.permission.FACTORY_TEST)) {
10024            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10025        }
10026
10027        if (isSystemApp(pkg)) {
10028            pkgSetting.isOrphaned = true;
10029        }
10030
10031        // Take care of first install / last update times.
10032        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10033        if (currentTime != 0) {
10034            if (pkgSetting.firstInstallTime == 0) {
10035                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10036            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10037                pkgSetting.lastUpdateTime = currentTime;
10038            }
10039        } else if (pkgSetting.firstInstallTime == 0) {
10040            // We need *something*.  Take time time stamp of the file.
10041            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10042        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10043            if (scanFileTime != pkgSetting.timeStamp) {
10044                // A package on the system image has changed; consider this
10045                // to be an update.
10046                pkgSetting.lastUpdateTime = scanFileTime;
10047            }
10048        }
10049        pkgSetting.setTimeStamp(scanFileTime);
10050
10051        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10052            if (nonMutatedPs != null) {
10053                synchronized (mPackages) {
10054                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10055                }
10056            }
10057        } else {
10058            final int userId = user == null ? 0 : user.getIdentifier();
10059            // Modify state for the given package setting
10060            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10061                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10062            if (pkgSetting.getInstantApp(userId)) {
10063                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10064            }
10065        }
10066        return pkg;
10067    }
10068
10069    /**
10070     * Applies policy to the parsed package based upon the given policy flags.
10071     * Ensures the package is in a good state.
10072     * <p>
10073     * Implementation detail: This method must NOT have any side effect. It would
10074     * ideally be static, but, it requires locks to read system state.
10075     */
10076    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10077        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10078            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10079            if (pkg.applicationInfo.isDirectBootAware()) {
10080                // we're direct boot aware; set for all components
10081                for (PackageParser.Service s : pkg.services) {
10082                    s.info.encryptionAware = s.info.directBootAware = true;
10083                }
10084                for (PackageParser.Provider p : pkg.providers) {
10085                    p.info.encryptionAware = p.info.directBootAware = true;
10086                }
10087                for (PackageParser.Activity a : pkg.activities) {
10088                    a.info.encryptionAware = a.info.directBootAware = true;
10089                }
10090                for (PackageParser.Activity r : pkg.receivers) {
10091                    r.info.encryptionAware = r.info.directBootAware = true;
10092                }
10093            }
10094            if (compressedFileExists(pkg.codePath)) {
10095                pkg.isStub = true;
10096            }
10097        } else {
10098            // Only allow system apps to be flagged as core apps.
10099            pkg.coreApp = false;
10100            // clear flags not applicable to regular apps
10101            pkg.applicationInfo.privateFlags &=
10102                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10103            pkg.applicationInfo.privateFlags &=
10104                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10105        }
10106        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10107
10108        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10109            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10110        }
10111
10112        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10113            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10114        }
10115
10116        if (!isSystemApp(pkg)) {
10117            // Only system apps can use these features.
10118            pkg.mOriginalPackages = null;
10119            pkg.mRealPackage = null;
10120            pkg.mAdoptPermissions = null;
10121        }
10122    }
10123
10124    /**
10125     * Asserts the parsed package is valid according to the given policy. If the
10126     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10127     * <p>
10128     * Implementation detail: This method must NOT have any side effects. It would
10129     * ideally be static, but, it requires locks to read system state.
10130     *
10131     * @throws PackageManagerException If the package fails any of the validation checks
10132     */
10133    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10134            throws PackageManagerException {
10135        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10136            assertCodePolicy(pkg);
10137        }
10138
10139        if (pkg.applicationInfo.getCodePath() == null ||
10140                pkg.applicationInfo.getResourcePath() == null) {
10141            // Bail out. The resource and code paths haven't been set.
10142            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10143                    "Code and resource paths haven't been set correctly");
10144        }
10145
10146        // Make sure we're not adding any bogus keyset info
10147        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10148        ksms.assertScannedPackageValid(pkg);
10149
10150        synchronized (mPackages) {
10151            // The special "android" package can only be defined once
10152            if (pkg.packageName.equals("android")) {
10153                if (mAndroidApplication != null) {
10154                    Slog.w(TAG, "*************************************************");
10155                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10156                    Slog.w(TAG, " codePath=" + pkg.codePath);
10157                    Slog.w(TAG, "*************************************************");
10158                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10159                            "Core android package being redefined.  Skipping.");
10160                }
10161            }
10162
10163            // A package name must be unique; don't allow duplicates
10164            if (mPackages.containsKey(pkg.packageName)) {
10165                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10166                        "Application package " + pkg.packageName
10167                        + " already installed.  Skipping duplicate.");
10168            }
10169
10170            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10171                // Static libs have a synthetic package name containing the version
10172                // but we still want the base name to be unique.
10173                if (mPackages.containsKey(pkg.manifestPackageName)) {
10174                    throw new PackageManagerException(
10175                            "Duplicate static shared lib provider package");
10176                }
10177
10178                // Static shared libraries should have at least O target SDK
10179                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10180                    throw new PackageManagerException(
10181                            "Packages declaring static-shared libs must target O SDK or higher");
10182                }
10183
10184                // Package declaring static a shared lib cannot be instant apps
10185                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10186                    throw new PackageManagerException(
10187                            "Packages declaring static-shared libs cannot be instant apps");
10188                }
10189
10190                // Package declaring static a shared lib cannot be renamed since the package
10191                // name is synthetic and apps can't code around package manager internals.
10192                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10193                    throw new PackageManagerException(
10194                            "Packages declaring static-shared libs cannot be renamed");
10195                }
10196
10197                // Package declaring static a shared lib cannot declare child packages
10198                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10199                    throw new PackageManagerException(
10200                            "Packages declaring static-shared libs cannot have child packages");
10201                }
10202
10203                // Package declaring static a shared lib cannot declare dynamic libs
10204                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10205                    throw new PackageManagerException(
10206                            "Packages declaring static-shared libs cannot declare dynamic libs");
10207                }
10208
10209                // Package declaring static a shared lib cannot declare shared users
10210                if (pkg.mSharedUserId != null) {
10211                    throw new PackageManagerException(
10212                            "Packages declaring static-shared libs cannot declare shared users");
10213                }
10214
10215                // Static shared libs cannot declare activities
10216                if (!pkg.activities.isEmpty()) {
10217                    throw new PackageManagerException(
10218                            "Static shared libs cannot declare activities");
10219                }
10220
10221                // Static shared libs cannot declare services
10222                if (!pkg.services.isEmpty()) {
10223                    throw new PackageManagerException(
10224                            "Static shared libs cannot declare services");
10225                }
10226
10227                // Static shared libs cannot declare providers
10228                if (!pkg.providers.isEmpty()) {
10229                    throw new PackageManagerException(
10230                            "Static shared libs cannot declare content providers");
10231                }
10232
10233                // Static shared libs cannot declare receivers
10234                if (!pkg.receivers.isEmpty()) {
10235                    throw new PackageManagerException(
10236                            "Static shared libs cannot declare broadcast receivers");
10237                }
10238
10239                // Static shared libs cannot declare permission groups
10240                if (!pkg.permissionGroups.isEmpty()) {
10241                    throw new PackageManagerException(
10242                            "Static shared libs cannot declare permission groups");
10243                }
10244
10245                // Static shared libs cannot declare permissions
10246                if (!pkg.permissions.isEmpty()) {
10247                    throw new PackageManagerException(
10248                            "Static shared libs cannot declare permissions");
10249                }
10250
10251                // Static shared libs cannot declare protected broadcasts
10252                if (pkg.protectedBroadcasts != null) {
10253                    throw new PackageManagerException(
10254                            "Static shared libs cannot declare protected broadcasts");
10255                }
10256
10257                // Static shared libs cannot be overlay targets
10258                if (pkg.mOverlayTarget != null) {
10259                    throw new PackageManagerException(
10260                            "Static shared libs cannot be overlay targets");
10261                }
10262
10263                // The version codes must be ordered as lib versions
10264                int minVersionCode = Integer.MIN_VALUE;
10265                int maxVersionCode = Integer.MAX_VALUE;
10266
10267                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10268                        pkg.staticSharedLibName);
10269                if (versionedLib != null) {
10270                    final int versionCount = versionedLib.size();
10271                    for (int i = 0; i < versionCount; i++) {
10272                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10273                        final int libVersionCode = libInfo.getDeclaringPackage()
10274                                .getVersionCode();
10275                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10276                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10277                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10278                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10279                        } else {
10280                            minVersionCode = maxVersionCode = libVersionCode;
10281                            break;
10282                        }
10283                    }
10284                }
10285                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10286                    throw new PackageManagerException("Static shared"
10287                            + " lib version codes must be ordered as lib versions");
10288                }
10289            }
10290
10291            // Only privileged apps and updated privileged apps can add child packages.
10292            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10293                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10294                    throw new PackageManagerException("Only privileged apps can add child "
10295                            + "packages. Ignoring package " + pkg.packageName);
10296                }
10297                final int childCount = pkg.childPackages.size();
10298                for (int i = 0; i < childCount; i++) {
10299                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10300                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10301                            childPkg.packageName)) {
10302                        throw new PackageManagerException("Can't override child of "
10303                                + "another disabled app. Ignoring package " + pkg.packageName);
10304                    }
10305                }
10306            }
10307
10308            // If we're only installing presumed-existing packages, require that the
10309            // scanned APK is both already known and at the path previously established
10310            // for it.  Previously unknown packages we pick up normally, but if we have an
10311            // a priori expectation about this package's install presence, enforce it.
10312            // With a singular exception for new system packages. When an OTA contains
10313            // a new system package, we allow the codepath to change from a system location
10314            // to the user-installed location. If we don't allow this change, any newer,
10315            // user-installed version of the application will be ignored.
10316            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10317                if (mExpectingBetter.containsKey(pkg.packageName)) {
10318                    logCriticalInfo(Log.WARN,
10319                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10320                } else {
10321                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10322                    if (known != null) {
10323                        if (DEBUG_PACKAGE_SCANNING) {
10324                            Log.d(TAG, "Examining " + pkg.codePath
10325                                    + " and requiring known paths " + known.codePathString
10326                                    + " & " + known.resourcePathString);
10327                        }
10328                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10329                                || !pkg.applicationInfo.getResourcePath().equals(
10330                                        known.resourcePathString)) {
10331                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10332                                    "Application package " + pkg.packageName
10333                                    + " found at " + pkg.applicationInfo.getCodePath()
10334                                    + " but expected at " + known.codePathString
10335                                    + "; ignoring.");
10336                        }
10337                    } else {
10338                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10339                                "Application package " + pkg.packageName
10340                                + " not found; ignoring.");
10341                    }
10342                }
10343            }
10344
10345            // Verify that this new package doesn't have any content providers
10346            // that conflict with existing packages.  Only do this if the
10347            // package isn't already installed, since we don't want to break
10348            // things that are installed.
10349            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10350                final int N = pkg.providers.size();
10351                int i;
10352                for (i=0; i<N; i++) {
10353                    PackageParser.Provider p = pkg.providers.get(i);
10354                    if (p.info.authority != null) {
10355                        String names[] = p.info.authority.split(";");
10356                        for (int j = 0; j < names.length; j++) {
10357                            if (mProvidersByAuthority.containsKey(names[j])) {
10358                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10359                                final String otherPackageName =
10360                                        ((other != null && other.getComponentName() != null) ?
10361                                                other.getComponentName().getPackageName() : "?");
10362                                throw new PackageManagerException(
10363                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10364                                        "Can't install because provider name " + names[j]
10365                                                + " (in package " + pkg.applicationInfo.packageName
10366                                                + ") is already used by " + otherPackageName);
10367                            }
10368                        }
10369                    }
10370                }
10371            }
10372        }
10373    }
10374
10375    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10376            int type, String declaringPackageName, int declaringVersionCode) {
10377        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10378        if (versionedLib == null) {
10379            versionedLib = new SparseArray<>();
10380            mSharedLibraries.put(name, versionedLib);
10381            if (type == SharedLibraryInfo.TYPE_STATIC) {
10382                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10383            }
10384        } else if (versionedLib.indexOfKey(version) >= 0) {
10385            return false;
10386        }
10387        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10388                version, type, declaringPackageName, declaringVersionCode);
10389        versionedLib.put(version, libEntry);
10390        return true;
10391    }
10392
10393    private boolean removeSharedLibraryLPw(String name, int version) {
10394        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10395        if (versionedLib == null) {
10396            return false;
10397        }
10398        final int libIdx = versionedLib.indexOfKey(version);
10399        if (libIdx < 0) {
10400            return false;
10401        }
10402        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10403        versionedLib.remove(version);
10404        if (versionedLib.size() <= 0) {
10405            mSharedLibraries.remove(name);
10406            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10407                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10408                        .getPackageName());
10409            }
10410        }
10411        return true;
10412    }
10413
10414    /**
10415     * Adds a scanned package to the system. When this method is finished, the package will
10416     * be available for query, resolution, etc...
10417     */
10418    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10419            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10420        final String pkgName = pkg.packageName;
10421        if (mCustomResolverComponentName != null &&
10422                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10423            setUpCustomResolverActivity(pkg);
10424        }
10425
10426        if (pkg.packageName.equals("android")) {
10427            synchronized (mPackages) {
10428                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10429                    // Set up information for our fall-back user intent resolution activity.
10430                    mPlatformPackage = pkg;
10431                    pkg.mVersionCode = mSdkVersion;
10432                    mAndroidApplication = pkg.applicationInfo;
10433                    if (!mResolverReplaced) {
10434                        mResolveActivity.applicationInfo = mAndroidApplication;
10435                        mResolveActivity.name = ResolverActivity.class.getName();
10436                        mResolveActivity.packageName = mAndroidApplication.packageName;
10437                        mResolveActivity.processName = "system:ui";
10438                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10439                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10440                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10441                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10442                        mResolveActivity.exported = true;
10443                        mResolveActivity.enabled = true;
10444                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10445                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10446                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10447                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10448                                | ActivityInfo.CONFIG_ORIENTATION
10449                                | ActivityInfo.CONFIG_KEYBOARD
10450                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10451                        mResolveInfo.activityInfo = mResolveActivity;
10452                        mResolveInfo.priority = 0;
10453                        mResolveInfo.preferredOrder = 0;
10454                        mResolveInfo.match = 0;
10455                        mResolveComponentName = new ComponentName(
10456                                mAndroidApplication.packageName, mResolveActivity.name);
10457                    }
10458                }
10459            }
10460        }
10461
10462        ArrayList<PackageParser.Package> clientLibPkgs = null;
10463        // writer
10464        synchronized (mPackages) {
10465            boolean hasStaticSharedLibs = false;
10466
10467            // Any app can add new static shared libraries
10468            if (pkg.staticSharedLibName != null) {
10469                // Static shared libs don't allow renaming as they have synthetic package
10470                // names to allow install of multiple versions, so use name from manifest.
10471                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10472                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10473                        pkg.manifestPackageName, pkg.mVersionCode)) {
10474                    hasStaticSharedLibs = true;
10475                } else {
10476                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10477                                + pkg.staticSharedLibName + " already exists; skipping");
10478                }
10479                // Static shared libs cannot be updated once installed since they
10480                // use synthetic package name which includes the version code, so
10481                // not need to update other packages's shared lib dependencies.
10482            }
10483
10484            if (!hasStaticSharedLibs
10485                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10486                // Only system apps can add new dynamic shared libraries.
10487                if (pkg.libraryNames != null) {
10488                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10489                        String name = pkg.libraryNames.get(i);
10490                        boolean allowed = false;
10491                        if (pkg.isUpdatedSystemApp()) {
10492                            // New library entries can only be added through the
10493                            // system image.  This is important to get rid of a lot
10494                            // of nasty edge cases: for example if we allowed a non-
10495                            // system update of the app to add a library, then uninstalling
10496                            // the update would make the library go away, and assumptions
10497                            // we made such as through app install filtering would now
10498                            // have allowed apps on the device which aren't compatible
10499                            // with it.  Better to just have the restriction here, be
10500                            // conservative, and create many fewer cases that can negatively
10501                            // impact the user experience.
10502                            final PackageSetting sysPs = mSettings
10503                                    .getDisabledSystemPkgLPr(pkg.packageName);
10504                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10505                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10506                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10507                                        allowed = true;
10508                                        break;
10509                                    }
10510                                }
10511                            }
10512                        } else {
10513                            allowed = true;
10514                        }
10515                        if (allowed) {
10516                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10517                                    SharedLibraryInfo.VERSION_UNDEFINED,
10518                                    SharedLibraryInfo.TYPE_DYNAMIC,
10519                                    pkg.packageName, pkg.mVersionCode)) {
10520                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10521                                        + name + " already exists; skipping");
10522                            }
10523                        } else {
10524                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10525                                    + name + " that is not declared on system image; skipping");
10526                        }
10527                    }
10528
10529                    if ((scanFlags & SCAN_BOOTING) == 0) {
10530                        // If we are not booting, we need to update any applications
10531                        // that are clients of our shared library.  If we are booting,
10532                        // this will all be done once the scan is complete.
10533                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10534                    }
10535                }
10536            }
10537        }
10538
10539        if ((scanFlags & SCAN_BOOTING) != 0) {
10540            // No apps can run during boot scan, so they don't need to be frozen
10541        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10542            // Caller asked to not kill app, so it's probably not frozen
10543        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10544            // Caller asked us to ignore frozen check for some reason; they
10545            // probably didn't know the package name
10546        } else {
10547            // We're doing major surgery on this package, so it better be frozen
10548            // right now to keep it from launching
10549            checkPackageFrozen(pkgName);
10550        }
10551
10552        // Also need to kill any apps that are dependent on the library.
10553        if (clientLibPkgs != null) {
10554            for (int i=0; i<clientLibPkgs.size(); i++) {
10555                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10556                killApplication(clientPkg.applicationInfo.packageName,
10557                        clientPkg.applicationInfo.uid, "update lib");
10558            }
10559        }
10560
10561        // writer
10562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10563
10564        synchronized (mPackages) {
10565            // We don't expect installation to fail beyond this point
10566
10567            // Add the new setting to mSettings
10568            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10569            // Add the new setting to mPackages
10570            mPackages.put(pkg.applicationInfo.packageName, pkg);
10571            // Make sure we don't accidentally delete its data.
10572            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10573            while (iter.hasNext()) {
10574                PackageCleanItem item = iter.next();
10575                if (pkgName.equals(item.packageName)) {
10576                    iter.remove();
10577                }
10578            }
10579
10580            // Add the package's KeySets to the global KeySetManagerService
10581            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10582            ksms.addScannedPackageLPw(pkg);
10583
10584            int N = pkg.providers.size();
10585            StringBuilder r = null;
10586            int i;
10587            for (i=0; i<N; i++) {
10588                PackageParser.Provider p = pkg.providers.get(i);
10589                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10590                        p.info.processName);
10591                mProviders.addProvider(p);
10592                p.syncable = p.info.isSyncable;
10593                if (p.info.authority != null) {
10594                    String names[] = p.info.authority.split(";");
10595                    p.info.authority = null;
10596                    for (int j = 0; j < names.length; j++) {
10597                        if (j == 1 && p.syncable) {
10598                            // We only want the first authority for a provider to possibly be
10599                            // syncable, so if we already added this provider using a different
10600                            // authority clear the syncable flag. We copy the provider before
10601                            // changing it because the mProviders object contains a reference
10602                            // to a provider that we don't want to change.
10603                            // Only do this for the second authority since the resulting provider
10604                            // object can be the same for all future authorities for this provider.
10605                            p = new PackageParser.Provider(p);
10606                            p.syncable = false;
10607                        }
10608                        if (!mProvidersByAuthority.containsKey(names[j])) {
10609                            mProvidersByAuthority.put(names[j], p);
10610                            if (p.info.authority == null) {
10611                                p.info.authority = names[j];
10612                            } else {
10613                                p.info.authority = p.info.authority + ";" + names[j];
10614                            }
10615                            if (DEBUG_PACKAGE_SCANNING) {
10616                                if (chatty)
10617                                    Log.d(TAG, "Registered content provider: " + names[j]
10618                                            + ", className = " + p.info.name + ", isSyncable = "
10619                                            + p.info.isSyncable);
10620                            }
10621                        } else {
10622                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10623                            Slog.w(TAG, "Skipping provider name " + names[j] +
10624                                    " (in package " + pkg.applicationInfo.packageName +
10625                                    "): name already used by "
10626                                    + ((other != null && other.getComponentName() != null)
10627                                            ? other.getComponentName().getPackageName() : "?"));
10628                        }
10629                    }
10630                }
10631                if (chatty) {
10632                    if (r == null) {
10633                        r = new StringBuilder(256);
10634                    } else {
10635                        r.append(' ');
10636                    }
10637                    r.append(p.info.name);
10638                }
10639            }
10640            if (r != null) {
10641                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10642            }
10643
10644            N = pkg.services.size();
10645            r = null;
10646            for (i=0; i<N; i++) {
10647                PackageParser.Service s = pkg.services.get(i);
10648                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10649                        s.info.processName);
10650                mServices.addService(s);
10651                if (chatty) {
10652                    if (r == null) {
10653                        r = new StringBuilder(256);
10654                    } else {
10655                        r.append(' ');
10656                    }
10657                    r.append(s.info.name);
10658                }
10659            }
10660            if (r != null) {
10661                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10662            }
10663
10664            N = pkg.receivers.size();
10665            r = null;
10666            for (i=0; i<N; i++) {
10667                PackageParser.Activity a = pkg.receivers.get(i);
10668                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10669                        a.info.processName);
10670                mReceivers.addActivity(a, "receiver");
10671                if (chatty) {
10672                    if (r == null) {
10673                        r = new StringBuilder(256);
10674                    } else {
10675                        r.append(' ');
10676                    }
10677                    r.append(a.info.name);
10678                }
10679            }
10680            if (r != null) {
10681                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10682            }
10683
10684            N = pkg.activities.size();
10685            r = null;
10686            for (i=0; i<N; i++) {
10687                PackageParser.Activity a = pkg.activities.get(i);
10688                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10689                        a.info.processName);
10690                mActivities.addActivity(a, "activity");
10691                if (chatty) {
10692                    if (r == null) {
10693                        r = new StringBuilder(256);
10694                    } else {
10695                        r.append(' ');
10696                    }
10697                    r.append(a.info.name);
10698                }
10699            }
10700            if (r != null) {
10701                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10702            }
10703
10704            // Don't allow ephemeral applications to define new permissions groups.
10705            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10706                Slog.w(TAG, "Permission groups from package " + pkg.packageName
10707                        + " ignored: instant apps cannot define new permission groups.");
10708            } else {
10709                mPermissionManager.addAllPermissionGroups(pkg, chatty);
10710            }
10711
10712            // Don't allow ephemeral applications to define new permissions.
10713            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10714                Slog.w(TAG, "Permissions from package " + pkg.packageName
10715                        + " ignored: instant apps cannot define new permissions.");
10716            } else {
10717                mPermissionManager.addAllPermissions(pkg, chatty);
10718            }
10719
10720            N = pkg.instrumentation.size();
10721            r = null;
10722            for (i=0; i<N; i++) {
10723                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10724                a.info.packageName = pkg.applicationInfo.packageName;
10725                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10726                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10727                a.info.splitNames = pkg.splitNames;
10728                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10729                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10730                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10731                a.info.dataDir = pkg.applicationInfo.dataDir;
10732                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10733                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10734                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10735                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10736                mInstrumentation.put(a.getComponentName(), a);
10737                if (chatty) {
10738                    if (r == null) {
10739                        r = new StringBuilder(256);
10740                    } else {
10741                        r.append(' ');
10742                    }
10743                    r.append(a.info.name);
10744                }
10745            }
10746            if (r != null) {
10747                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10748            }
10749
10750            if (pkg.protectedBroadcasts != null) {
10751                N = pkg.protectedBroadcasts.size();
10752                synchronized (mProtectedBroadcasts) {
10753                    for (i = 0; i < N; i++) {
10754                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10755                    }
10756                }
10757            }
10758        }
10759
10760        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10761    }
10762
10763    /**
10764     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10765     * is derived purely on the basis of the contents of {@code scanFile} and
10766     * {@code cpuAbiOverride}.
10767     *
10768     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10769     */
10770    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10771                                 String cpuAbiOverride, boolean extractLibs,
10772                                 File appLib32InstallDir)
10773            throws PackageManagerException {
10774        // Give ourselves some initial paths; we'll come back for another
10775        // pass once we've determined ABI below.
10776        setNativeLibraryPaths(pkg, appLib32InstallDir);
10777
10778        // We would never need to extract libs for forward-locked and external packages,
10779        // since the container service will do it for us. We shouldn't attempt to
10780        // extract libs from system app when it was not updated.
10781        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10782                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10783            extractLibs = false;
10784        }
10785
10786        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10787        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10788
10789        NativeLibraryHelper.Handle handle = null;
10790        try {
10791            handle = NativeLibraryHelper.Handle.create(pkg);
10792            // TODO(multiArch): This can be null for apps that didn't go through the
10793            // usual installation process. We can calculate it again, like we
10794            // do during install time.
10795            //
10796            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10797            // unnecessary.
10798            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10799
10800            // Null out the abis so that they can be recalculated.
10801            pkg.applicationInfo.primaryCpuAbi = null;
10802            pkg.applicationInfo.secondaryCpuAbi = null;
10803            if (isMultiArch(pkg.applicationInfo)) {
10804                // Warn if we've set an abiOverride for multi-lib packages..
10805                // By definition, we need to copy both 32 and 64 bit libraries for
10806                // such packages.
10807                if (pkg.cpuAbiOverride != null
10808                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10809                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10810                }
10811
10812                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10813                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10814                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10815                    if (extractLibs) {
10816                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10817                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10818                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10819                                useIsaSpecificSubdirs);
10820                    } else {
10821                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10822                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10823                    }
10824                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10825                }
10826
10827                // Shared library native code should be in the APK zip aligned
10828                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
10829                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10830                            "Shared library native lib extraction not supported");
10831                }
10832
10833                maybeThrowExceptionForMultiArchCopy(
10834                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10835
10836                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10837                    if (extractLibs) {
10838                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10839                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10840                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10841                                useIsaSpecificSubdirs);
10842                    } else {
10843                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10844                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10845                    }
10846                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10847                }
10848
10849                maybeThrowExceptionForMultiArchCopy(
10850                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10851
10852                if (abi64 >= 0) {
10853                    // Shared library native libs should be in the APK zip aligned
10854                    if (extractLibs && pkg.isLibrary()) {
10855                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10856                                "Shared library native lib extraction not supported");
10857                    }
10858                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10859                }
10860
10861                if (abi32 >= 0) {
10862                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10863                    if (abi64 >= 0) {
10864                        if (pkg.use32bitAbi) {
10865                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10866                            pkg.applicationInfo.primaryCpuAbi = abi;
10867                        } else {
10868                            pkg.applicationInfo.secondaryCpuAbi = abi;
10869                        }
10870                    } else {
10871                        pkg.applicationInfo.primaryCpuAbi = abi;
10872                    }
10873                }
10874            } else {
10875                String[] abiList = (cpuAbiOverride != null) ?
10876                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10877
10878                // Enable gross and lame hacks for apps that are built with old
10879                // SDK tools. We must scan their APKs for renderscript bitcode and
10880                // not launch them if it's present. Don't bother checking on devices
10881                // that don't have 64 bit support.
10882                boolean needsRenderScriptOverride = false;
10883                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10884                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10885                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10886                    needsRenderScriptOverride = true;
10887                }
10888
10889                final int copyRet;
10890                if (extractLibs) {
10891                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10892                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10893                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10894                } else {
10895                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10896                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10897                }
10898                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10899
10900                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10901                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10902                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10903                }
10904
10905                if (copyRet >= 0) {
10906                    // Shared libraries that have native libs must be multi-architecture
10907                    if (pkg.isLibrary()) {
10908                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10909                                "Shared library with native libs must be multiarch");
10910                    }
10911                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10912                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10913                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10914                } else if (needsRenderScriptOverride) {
10915                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10916                }
10917            }
10918        } catch (IOException ioe) {
10919            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10920        } finally {
10921            IoUtils.closeQuietly(handle);
10922        }
10923
10924        // Now that we've calculated the ABIs and determined if it's an internal app,
10925        // we will go ahead and populate the nativeLibraryPath.
10926        setNativeLibraryPaths(pkg, appLib32InstallDir);
10927    }
10928
10929    /**
10930     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10931     * i.e, so that all packages can be run inside a single process if required.
10932     *
10933     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10934     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10935     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10936     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10937     * updating a package that belongs to a shared user.
10938     *
10939     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10940     * adds unnecessary complexity.
10941     */
10942    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10943            PackageParser.Package scannedPackage) {
10944        String requiredInstructionSet = null;
10945        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10946            requiredInstructionSet = VMRuntime.getInstructionSet(
10947                     scannedPackage.applicationInfo.primaryCpuAbi);
10948        }
10949
10950        PackageSetting requirer = null;
10951        for (PackageSetting ps : packagesForUser) {
10952            // If packagesForUser contains scannedPackage, we skip it. This will happen
10953            // when scannedPackage is an update of an existing package. Without this check,
10954            // we will never be able to change the ABI of any package belonging to a shared
10955            // user, even if it's compatible with other packages.
10956            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10957                if (ps.primaryCpuAbiString == null) {
10958                    continue;
10959                }
10960
10961                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10962                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10963                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10964                    // this but there's not much we can do.
10965                    String errorMessage = "Instruction set mismatch, "
10966                            + ((requirer == null) ? "[caller]" : requirer)
10967                            + " requires " + requiredInstructionSet + " whereas " + ps
10968                            + " requires " + instructionSet;
10969                    Slog.w(TAG, errorMessage);
10970                }
10971
10972                if (requiredInstructionSet == null) {
10973                    requiredInstructionSet = instructionSet;
10974                    requirer = ps;
10975                }
10976            }
10977        }
10978
10979        if (requiredInstructionSet != null) {
10980            String adjustedAbi;
10981            if (requirer != null) {
10982                // requirer != null implies that either scannedPackage was null or that scannedPackage
10983                // did not require an ABI, in which case we have to adjust scannedPackage to match
10984                // the ABI of the set (which is the same as requirer's ABI)
10985                adjustedAbi = requirer.primaryCpuAbiString;
10986                if (scannedPackage != null) {
10987                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10988                }
10989            } else {
10990                // requirer == null implies that we're updating all ABIs in the set to
10991                // match scannedPackage.
10992                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10993            }
10994
10995            for (PackageSetting ps : packagesForUser) {
10996                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10997                    if (ps.primaryCpuAbiString != null) {
10998                        continue;
10999                    }
11000
11001                    ps.primaryCpuAbiString = adjustedAbi;
11002                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11003                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11004                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11005                        if (DEBUG_ABI_SELECTION) {
11006                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11007                                    + " (requirer="
11008                                    + (requirer != null ? requirer.pkg : "null")
11009                                    + ", scannedPackage="
11010                                    + (scannedPackage != null ? scannedPackage : "null")
11011                                    + ")");
11012                        }
11013                        try {
11014                            mInstaller.rmdex(ps.codePathString,
11015                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11016                        } catch (InstallerException ignored) {
11017                        }
11018                    }
11019                }
11020            }
11021        }
11022    }
11023
11024    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11025        synchronized (mPackages) {
11026            mResolverReplaced = true;
11027            // Set up information for custom user intent resolution activity.
11028            mResolveActivity.applicationInfo = pkg.applicationInfo;
11029            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11030            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11031            mResolveActivity.processName = pkg.applicationInfo.packageName;
11032            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11033            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11034                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11035            mResolveActivity.theme = 0;
11036            mResolveActivity.exported = true;
11037            mResolveActivity.enabled = true;
11038            mResolveInfo.activityInfo = mResolveActivity;
11039            mResolveInfo.priority = 0;
11040            mResolveInfo.preferredOrder = 0;
11041            mResolveInfo.match = 0;
11042            mResolveComponentName = mCustomResolverComponentName;
11043            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11044                    mResolveComponentName);
11045        }
11046    }
11047
11048    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11049        if (installerActivity == null) {
11050            if (DEBUG_EPHEMERAL) {
11051                Slog.d(TAG, "Clear ephemeral installer activity");
11052            }
11053            mInstantAppInstallerActivity = null;
11054            return;
11055        }
11056
11057        if (DEBUG_EPHEMERAL) {
11058            Slog.d(TAG, "Set ephemeral installer activity: "
11059                    + installerActivity.getComponentName());
11060        }
11061        // Set up information for ephemeral installer activity
11062        mInstantAppInstallerActivity = installerActivity;
11063        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11064                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11065        mInstantAppInstallerActivity.exported = true;
11066        mInstantAppInstallerActivity.enabled = true;
11067        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11068        mInstantAppInstallerInfo.priority = 0;
11069        mInstantAppInstallerInfo.preferredOrder = 1;
11070        mInstantAppInstallerInfo.isDefault = true;
11071        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11072                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11073    }
11074
11075    private static String calculateBundledApkRoot(final String codePathString) {
11076        final File codePath = new File(codePathString);
11077        final File codeRoot;
11078        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11079            codeRoot = Environment.getRootDirectory();
11080        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11081            codeRoot = Environment.getOemDirectory();
11082        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11083            codeRoot = Environment.getVendorDirectory();
11084        } else {
11085            // Unrecognized code path; take its top real segment as the apk root:
11086            // e.g. /something/app/blah.apk => /something
11087            try {
11088                File f = codePath.getCanonicalFile();
11089                File parent = f.getParentFile();    // non-null because codePath is a file
11090                File tmp;
11091                while ((tmp = parent.getParentFile()) != null) {
11092                    f = parent;
11093                    parent = tmp;
11094                }
11095                codeRoot = f;
11096                Slog.w(TAG, "Unrecognized code path "
11097                        + codePath + " - using " + codeRoot);
11098            } catch (IOException e) {
11099                // Can't canonicalize the code path -- shenanigans?
11100                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11101                return Environment.getRootDirectory().getPath();
11102            }
11103        }
11104        return codeRoot.getPath();
11105    }
11106
11107    /**
11108     * Derive and set the location of native libraries for the given package,
11109     * which varies depending on where and how the package was installed.
11110     */
11111    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11112        final ApplicationInfo info = pkg.applicationInfo;
11113        final String codePath = pkg.codePath;
11114        final File codeFile = new File(codePath);
11115        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11116        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11117
11118        info.nativeLibraryRootDir = null;
11119        info.nativeLibraryRootRequiresIsa = false;
11120        info.nativeLibraryDir = null;
11121        info.secondaryNativeLibraryDir = null;
11122
11123        if (isApkFile(codeFile)) {
11124            // Monolithic install
11125            if (bundledApp) {
11126                // If "/system/lib64/apkname" exists, assume that is the per-package
11127                // native library directory to use; otherwise use "/system/lib/apkname".
11128                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11129                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11130                        getPrimaryInstructionSet(info));
11131
11132                // This is a bundled system app so choose the path based on the ABI.
11133                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11134                // is just the default path.
11135                final String apkName = deriveCodePathName(codePath);
11136                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11137                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11138                        apkName).getAbsolutePath();
11139
11140                if (info.secondaryCpuAbi != null) {
11141                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11142                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11143                            secondaryLibDir, apkName).getAbsolutePath();
11144                }
11145            } else if (asecApp) {
11146                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11147                        .getAbsolutePath();
11148            } else {
11149                final String apkName = deriveCodePathName(codePath);
11150                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11151                        .getAbsolutePath();
11152            }
11153
11154            info.nativeLibraryRootRequiresIsa = false;
11155            info.nativeLibraryDir = info.nativeLibraryRootDir;
11156        } else {
11157            // Cluster install
11158            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11159            info.nativeLibraryRootRequiresIsa = true;
11160
11161            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11162                    getPrimaryInstructionSet(info)).getAbsolutePath();
11163
11164            if (info.secondaryCpuAbi != null) {
11165                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11166                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11167            }
11168        }
11169    }
11170
11171    /**
11172     * Calculate the abis and roots for a bundled app. These can uniquely
11173     * be determined from the contents of the system partition, i.e whether
11174     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11175     * of this information, and instead assume that the system was built
11176     * sensibly.
11177     */
11178    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11179                                           PackageSetting pkgSetting) {
11180        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11181
11182        // If "/system/lib64/apkname" exists, assume that is the per-package
11183        // native library directory to use; otherwise use "/system/lib/apkname".
11184        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11185        setBundledAppAbi(pkg, apkRoot, apkName);
11186        // pkgSetting might be null during rescan following uninstall of updates
11187        // to a bundled app, so accommodate that possibility.  The settings in
11188        // that case will be established later from the parsed package.
11189        //
11190        // If the settings aren't null, sync them up with what we've just derived.
11191        // note that apkRoot isn't stored in the package settings.
11192        if (pkgSetting != null) {
11193            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11194            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11195        }
11196    }
11197
11198    /**
11199     * Deduces the ABI of a bundled app and sets the relevant fields on the
11200     * parsed pkg object.
11201     *
11202     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11203     *        under which system libraries are installed.
11204     * @param apkName the name of the installed package.
11205     */
11206    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11207        final File codeFile = new File(pkg.codePath);
11208
11209        final boolean has64BitLibs;
11210        final boolean has32BitLibs;
11211        if (isApkFile(codeFile)) {
11212            // Monolithic install
11213            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11214            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11215        } else {
11216            // Cluster install
11217            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11218            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11219                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11220                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11221                has64BitLibs = (new File(rootDir, isa)).exists();
11222            } else {
11223                has64BitLibs = false;
11224            }
11225            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11226                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11227                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11228                has32BitLibs = (new File(rootDir, isa)).exists();
11229            } else {
11230                has32BitLibs = false;
11231            }
11232        }
11233
11234        if (has64BitLibs && !has32BitLibs) {
11235            // The package has 64 bit libs, but not 32 bit libs. Its primary
11236            // ABI should be 64 bit. We can safely assume here that the bundled
11237            // native libraries correspond to the most preferred ABI in the list.
11238
11239            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11240            pkg.applicationInfo.secondaryCpuAbi = null;
11241        } else if (has32BitLibs && !has64BitLibs) {
11242            // The package has 32 bit libs but not 64 bit libs. Its primary
11243            // ABI should be 32 bit.
11244
11245            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11246            pkg.applicationInfo.secondaryCpuAbi = null;
11247        } else if (has32BitLibs && has64BitLibs) {
11248            // The application has both 64 and 32 bit bundled libraries. We check
11249            // here that the app declares multiArch support, and warn if it doesn't.
11250            //
11251            // We will be lenient here and record both ABIs. The primary will be the
11252            // ABI that's higher on the list, i.e, a device that's configured to prefer
11253            // 64 bit apps will see a 64 bit primary ABI,
11254
11255            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11256                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11257            }
11258
11259            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11260                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11261                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11262            } else {
11263                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11264                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11265            }
11266        } else {
11267            pkg.applicationInfo.primaryCpuAbi = null;
11268            pkg.applicationInfo.secondaryCpuAbi = null;
11269        }
11270    }
11271
11272    private void killApplication(String pkgName, int appId, String reason) {
11273        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11274    }
11275
11276    private void killApplication(String pkgName, int appId, int userId, String reason) {
11277        // Request the ActivityManager to kill the process(only for existing packages)
11278        // so that we do not end up in a confused state while the user is still using the older
11279        // version of the application while the new one gets installed.
11280        final long token = Binder.clearCallingIdentity();
11281        try {
11282            IActivityManager am = ActivityManager.getService();
11283            if (am != null) {
11284                try {
11285                    am.killApplication(pkgName, appId, userId, reason);
11286                } catch (RemoteException e) {
11287                }
11288            }
11289        } finally {
11290            Binder.restoreCallingIdentity(token);
11291        }
11292    }
11293
11294    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11295        // Remove the parent package setting
11296        PackageSetting ps = (PackageSetting) pkg.mExtras;
11297        if (ps != null) {
11298            removePackageLI(ps, chatty);
11299        }
11300        // Remove the child package setting
11301        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11302        for (int i = 0; i < childCount; i++) {
11303            PackageParser.Package childPkg = pkg.childPackages.get(i);
11304            ps = (PackageSetting) childPkg.mExtras;
11305            if (ps != null) {
11306                removePackageLI(ps, chatty);
11307            }
11308        }
11309    }
11310
11311    void removePackageLI(PackageSetting ps, boolean chatty) {
11312        if (DEBUG_INSTALL) {
11313            if (chatty)
11314                Log.d(TAG, "Removing package " + ps.name);
11315        }
11316
11317        // writer
11318        synchronized (mPackages) {
11319            mPackages.remove(ps.name);
11320            final PackageParser.Package pkg = ps.pkg;
11321            if (pkg != null) {
11322                cleanPackageDataStructuresLILPw(pkg, chatty);
11323            }
11324        }
11325    }
11326
11327    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11328        if (DEBUG_INSTALL) {
11329            if (chatty)
11330                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11331        }
11332
11333        // writer
11334        synchronized (mPackages) {
11335            // Remove the parent package
11336            mPackages.remove(pkg.applicationInfo.packageName);
11337            cleanPackageDataStructuresLILPw(pkg, chatty);
11338
11339            // Remove the child packages
11340            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11341            for (int i = 0; i < childCount; i++) {
11342                PackageParser.Package childPkg = pkg.childPackages.get(i);
11343                mPackages.remove(childPkg.applicationInfo.packageName);
11344                cleanPackageDataStructuresLILPw(childPkg, chatty);
11345            }
11346        }
11347    }
11348
11349    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11350        int N = pkg.providers.size();
11351        StringBuilder r = null;
11352        int i;
11353        for (i=0; i<N; i++) {
11354            PackageParser.Provider p = pkg.providers.get(i);
11355            mProviders.removeProvider(p);
11356            if (p.info.authority == null) {
11357
11358                /* There was another ContentProvider with this authority when
11359                 * this app was installed so this authority is null,
11360                 * Ignore it as we don't have to unregister the provider.
11361                 */
11362                continue;
11363            }
11364            String names[] = p.info.authority.split(";");
11365            for (int j = 0; j < names.length; j++) {
11366                if (mProvidersByAuthority.get(names[j]) == p) {
11367                    mProvidersByAuthority.remove(names[j]);
11368                    if (DEBUG_REMOVE) {
11369                        if (chatty)
11370                            Log.d(TAG, "Unregistered content provider: " + names[j]
11371                                    + ", className = " + p.info.name + ", isSyncable = "
11372                                    + p.info.isSyncable);
11373                    }
11374                }
11375            }
11376            if (DEBUG_REMOVE && chatty) {
11377                if (r == null) {
11378                    r = new StringBuilder(256);
11379                } else {
11380                    r.append(' ');
11381                }
11382                r.append(p.info.name);
11383            }
11384        }
11385        if (r != null) {
11386            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11387        }
11388
11389        N = pkg.services.size();
11390        r = null;
11391        for (i=0; i<N; i++) {
11392            PackageParser.Service s = pkg.services.get(i);
11393            mServices.removeService(s);
11394            if (chatty) {
11395                if (r == null) {
11396                    r = new StringBuilder(256);
11397                } else {
11398                    r.append(' ');
11399                }
11400                r.append(s.info.name);
11401            }
11402        }
11403        if (r != null) {
11404            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11405        }
11406
11407        N = pkg.receivers.size();
11408        r = null;
11409        for (i=0; i<N; i++) {
11410            PackageParser.Activity a = pkg.receivers.get(i);
11411            mReceivers.removeActivity(a, "receiver");
11412            if (DEBUG_REMOVE && chatty) {
11413                if (r == null) {
11414                    r = new StringBuilder(256);
11415                } else {
11416                    r.append(' ');
11417                }
11418                r.append(a.info.name);
11419            }
11420        }
11421        if (r != null) {
11422            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11423        }
11424
11425        N = pkg.activities.size();
11426        r = null;
11427        for (i=0; i<N; i++) {
11428            PackageParser.Activity a = pkg.activities.get(i);
11429            mActivities.removeActivity(a, "activity");
11430            if (DEBUG_REMOVE && chatty) {
11431                if (r == null) {
11432                    r = new StringBuilder(256);
11433                } else {
11434                    r.append(' ');
11435                }
11436                r.append(a.info.name);
11437            }
11438        }
11439        if (r != null) {
11440            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11441        }
11442
11443        mPermissionManager.removeAllPermissions(pkg, chatty);
11444
11445        N = pkg.instrumentation.size();
11446        r = null;
11447        for (i=0; i<N; i++) {
11448            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11449            mInstrumentation.remove(a.getComponentName());
11450            if (DEBUG_REMOVE && chatty) {
11451                if (r == null) {
11452                    r = new StringBuilder(256);
11453                } else {
11454                    r.append(' ');
11455                }
11456                r.append(a.info.name);
11457            }
11458        }
11459        if (r != null) {
11460            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11461        }
11462
11463        r = null;
11464        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11465            // Only system apps can hold shared libraries.
11466            if (pkg.libraryNames != null) {
11467                for (i = 0; i < pkg.libraryNames.size(); i++) {
11468                    String name = pkg.libraryNames.get(i);
11469                    if (removeSharedLibraryLPw(name, 0)) {
11470                        if (DEBUG_REMOVE && chatty) {
11471                            if (r == null) {
11472                                r = new StringBuilder(256);
11473                            } else {
11474                                r.append(' ');
11475                            }
11476                            r.append(name);
11477                        }
11478                    }
11479                }
11480            }
11481        }
11482
11483        r = null;
11484
11485        // Any package can hold static shared libraries.
11486        if (pkg.staticSharedLibName != null) {
11487            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11488                if (DEBUG_REMOVE && chatty) {
11489                    if (r == null) {
11490                        r = new StringBuilder(256);
11491                    } else {
11492                        r.append(' ');
11493                    }
11494                    r.append(pkg.staticSharedLibName);
11495                }
11496            }
11497        }
11498
11499        if (r != null) {
11500            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11501        }
11502    }
11503
11504
11505    final class ActivityIntentResolver
11506            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11507        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11508                boolean defaultOnly, int userId) {
11509            if (!sUserManager.exists(userId)) return null;
11510            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11511            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11512        }
11513
11514        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11515                int userId) {
11516            if (!sUserManager.exists(userId)) return null;
11517            mFlags = flags;
11518            return super.queryIntent(intent, resolvedType,
11519                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11520                    userId);
11521        }
11522
11523        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11524                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11525            if (!sUserManager.exists(userId)) return null;
11526            if (packageActivities == null) {
11527                return null;
11528            }
11529            mFlags = flags;
11530            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11531            final int N = packageActivities.size();
11532            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11533                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11534
11535            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11536            for (int i = 0; i < N; ++i) {
11537                intentFilters = packageActivities.get(i).intents;
11538                if (intentFilters != null && intentFilters.size() > 0) {
11539                    PackageParser.ActivityIntentInfo[] array =
11540                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11541                    intentFilters.toArray(array);
11542                    listCut.add(array);
11543                }
11544            }
11545            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11546        }
11547
11548        /**
11549         * Finds a privileged activity that matches the specified activity names.
11550         */
11551        private PackageParser.Activity findMatchingActivity(
11552                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11553            for (PackageParser.Activity sysActivity : activityList) {
11554                if (sysActivity.info.name.equals(activityInfo.name)) {
11555                    return sysActivity;
11556                }
11557                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11558                    return sysActivity;
11559                }
11560                if (sysActivity.info.targetActivity != null) {
11561                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11562                        return sysActivity;
11563                    }
11564                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11565                        return sysActivity;
11566                    }
11567                }
11568            }
11569            return null;
11570        }
11571
11572        public class IterGenerator<E> {
11573            public Iterator<E> generate(ActivityIntentInfo info) {
11574                return null;
11575            }
11576        }
11577
11578        public class ActionIterGenerator extends IterGenerator<String> {
11579            @Override
11580            public Iterator<String> generate(ActivityIntentInfo info) {
11581                return info.actionsIterator();
11582            }
11583        }
11584
11585        public class CategoriesIterGenerator extends IterGenerator<String> {
11586            @Override
11587            public Iterator<String> generate(ActivityIntentInfo info) {
11588                return info.categoriesIterator();
11589            }
11590        }
11591
11592        public class SchemesIterGenerator extends IterGenerator<String> {
11593            @Override
11594            public Iterator<String> generate(ActivityIntentInfo info) {
11595                return info.schemesIterator();
11596            }
11597        }
11598
11599        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11600            @Override
11601            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11602                return info.authoritiesIterator();
11603            }
11604        }
11605
11606        /**
11607         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11608         * MODIFIED. Do not pass in a list that should not be changed.
11609         */
11610        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11611                IterGenerator<T> generator, Iterator<T> searchIterator) {
11612            // loop through the set of actions; every one must be found in the intent filter
11613            while (searchIterator.hasNext()) {
11614                // we must have at least one filter in the list to consider a match
11615                if (intentList.size() == 0) {
11616                    break;
11617                }
11618
11619                final T searchAction = searchIterator.next();
11620
11621                // loop through the set of intent filters
11622                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11623                while (intentIter.hasNext()) {
11624                    final ActivityIntentInfo intentInfo = intentIter.next();
11625                    boolean selectionFound = false;
11626
11627                    // loop through the intent filter's selection criteria; at least one
11628                    // of them must match the searched criteria
11629                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11630                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11631                        final T intentSelection = intentSelectionIter.next();
11632                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11633                            selectionFound = true;
11634                            break;
11635                        }
11636                    }
11637
11638                    // the selection criteria wasn't found in this filter's set; this filter
11639                    // is not a potential match
11640                    if (!selectionFound) {
11641                        intentIter.remove();
11642                    }
11643                }
11644            }
11645        }
11646
11647        private boolean isProtectedAction(ActivityIntentInfo filter) {
11648            final Iterator<String> actionsIter = filter.actionsIterator();
11649            while (actionsIter != null && actionsIter.hasNext()) {
11650                final String filterAction = actionsIter.next();
11651                if (PROTECTED_ACTIONS.contains(filterAction)) {
11652                    return true;
11653                }
11654            }
11655            return false;
11656        }
11657
11658        /**
11659         * Adjusts the priority of the given intent filter according to policy.
11660         * <p>
11661         * <ul>
11662         * <li>The priority for non privileged applications is capped to '0'</li>
11663         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11664         * <li>The priority for unbundled updates to privileged applications is capped to the
11665         *      priority defined on the system partition</li>
11666         * </ul>
11667         * <p>
11668         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11669         * allowed to obtain any priority on any action.
11670         */
11671        private void adjustPriority(
11672                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11673            // nothing to do; priority is fine as-is
11674            if (intent.getPriority() <= 0) {
11675                return;
11676            }
11677
11678            final ActivityInfo activityInfo = intent.activity.info;
11679            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11680
11681            final boolean privilegedApp =
11682                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11683            if (!privilegedApp) {
11684                // non-privileged applications can never define a priority >0
11685                if (DEBUG_FILTERS) {
11686                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
11687                            + " package: " + applicationInfo.packageName
11688                            + " activity: " + intent.activity.className
11689                            + " origPrio: " + intent.getPriority());
11690                }
11691                intent.setPriority(0);
11692                return;
11693            }
11694
11695            if (systemActivities == null) {
11696                // the system package is not disabled; we're parsing the system partition
11697                if (isProtectedAction(intent)) {
11698                    if (mDeferProtectedFilters) {
11699                        // We can't deal with these just yet. No component should ever obtain a
11700                        // >0 priority for a protected actions, with ONE exception -- the setup
11701                        // wizard. The setup wizard, however, cannot be known until we're able to
11702                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11703                        // until all intent filters have been processed. Chicken, meet egg.
11704                        // Let the filter temporarily have a high priority and rectify the
11705                        // priorities after all system packages have been scanned.
11706                        mProtectedFilters.add(intent);
11707                        if (DEBUG_FILTERS) {
11708                            Slog.i(TAG, "Protected action; save for later;"
11709                                    + " package: " + applicationInfo.packageName
11710                                    + " activity: " + intent.activity.className
11711                                    + " origPrio: " + intent.getPriority());
11712                        }
11713                        return;
11714                    } else {
11715                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11716                            Slog.i(TAG, "No setup wizard;"
11717                                + " All protected intents capped to priority 0");
11718                        }
11719                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11720                            if (DEBUG_FILTERS) {
11721                                Slog.i(TAG, "Found setup wizard;"
11722                                    + " allow priority " + intent.getPriority() + ";"
11723                                    + " package: " + intent.activity.info.packageName
11724                                    + " activity: " + intent.activity.className
11725                                    + " priority: " + intent.getPriority());
11726                            }
11727                            // setup wizard gets whatever it wants
11728                            return;
11729                        }
11730                        if (DEBUG_FILTERS) {
11731                            Slog.i(TAG, "Protected action; cap priority to 0;"
11732                                    + " package: " + intent.activity.info.packageName
11733                                    + " activity: " + intent.activity.className
11734                                    + " origPrio: " + intent.getPriority());
11735                        }
11736                        intent.setPriority(0);
11737                        return;
11738                    }
11739                }
11740                // privileged apps on the system image get whatever priority they request
11741                return;
11742            }
11743
11744            // privileged app unbundled update ... try to find the same activity
11745            final PackageParser.Activity foundActivity =
11746                    findMatchingActivity(systemActivities, activityInfo);
11747            if (foundActivity == null) {
11748                // this is a new activity; it cannot obtain >0 priority
11749                if (DEBUG_FILTERS) {
11750                    Slog.i(TAG, "New activity; cap priority to 0;"
11751                            + " package: " + applicationInfo.packageName
11752                            + " activity: " + intent.activity.className
11753                            + " origPrio: " + intent.getPriority());
11754                }
11755                intent.setPriority(0);
11756                return;
11757            }
11758
11759            // found activity, now check for filter equivalence
11760
11761            // a shallow copy is enough; we modify the list, not its contents
11762            final List<ActivityIntentInfo> intentListCopy =
11763                    new ArrayList<>(foundActivity.intents);
11764            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11765
11766            // find matching action subsets
11767            final Iterator<String> actionsIterator = intent.actionsIterator();
11768            if (actionsIterator != null) {
11769                getIntentListSubset(
11770                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11771                if (intentListCopy.size() == 0) {
11772                    // no more intents to match; we're not equivalent
11773                    if (DEBUG_FILTERS) {
11774                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11775                                + " package: " + applicationInfo.packageName
11776                                + " activity: " + intent.activity.className
11777                                + " origPrio: " + intent.getPriority());
11778                    }
11779                    intent.setPriority(0);
11780                    return;
11781                }
11782            }
11783
11784            // find matching category subsets
11785            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11786            if (categoriesIterator != null) {
11787                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11788                        categoriesIterator);
11789                if (intentListCopy.size() == 0) {
11790                    // no more intents to match; we're not equivalent
11791                    if (DEBUG_FILTERS) {
11792                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11793                                + " package: " + applicationInfo.packageName
11794                                + " activity: " + intent.activity.className
11795                                + " origPrio: " + intent.getPriority());
11796                    }
11797                    intent.setPriority(0);
11798                    return;
11799                }
11800            }
11801
11802            // find matching schemes subsets
11803            final Iterator<String> schemesIterator = intent.schemesIterator();
11804            if (schemesIterator != null) {
11805                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11806                        schemesIterator);
11807                if (intentListCopy.size() == 0) {
11808                    // no more intents to match; we're not equivalent
11809                    if (DEBUG_FILTERS) {
11810                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11811                                + " package: " + applicationInfo.packageName
11812                                + " activity: " + intent.activity.className
11813                                + " origPrio: " + intent.getPriority());
11814                    }
11815                    intent.setPriority(0);
11816                    return;
11817                }
11818            }
11819
11820            // find matching authorities subsets
11821            final Iterator<IntentFilter.AuthorityEntry>
11822                    authoritiesIterator = intent.authoritiesIterator();
11823            if (authoritiesIterator != null) {
11824                getIntentListSubset(intentListCopy,
11825                        new AuthoritiesIterGenerator(),
11826                        authoritiesIterator);
11827                if (intentListCopy.size() == 0) {
11828                    // no more intents to match; we're not equivalent
11829                    if (DEBUG_FILTERS) {
11830                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11831                                + " package: " + applicationInfo.packageName
11832                                + " activity: " + intent.activity.className
11833                                + " origPrio: " + intent.getPriority());
11834                    }
11835                    intent.setPriority(0);
11836                    return;
11837                }
11838            }
11839
11840            // we found matching filter(s); app gets the max priority of all intents
11841            int cappedPriority = 0;
11842            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11843                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11844            }
11845            if (intent.getPriority() > cappedPriority) {
11846                if (DEBUG_FILTERS) {
11847                    Slog.i(TAG, "Found matching filter(s);"
11848                            + " cap priority to " + cappedPriority + ";"
11849                            + " package: " + applicationInfo.packageName
11850                            + " activity: " + intent.activity.className
11851                            + " origPrio: " + intent.getPriority());
11852                }
11853                intent.setPriority(cappedPriority);
11854                return;
11855            }
11856            // all this for nothing; the requested priority was <= what was on the system
11857        }
11858
11859        public final void addActivity(PackageParser.Activity a, String type) {
11860            mActivities.put(a.getComponentName(), a);
11861            if (DEBUG_SHOW_INFO)
11862                Log.v(
11863                TAG, "  " + type + " " +
11864                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11865            if (DEBUG_SHOW_INFO)
11866                Log.v(TAG, "    Class=" + a.info.name);
11867            final int NI = a.intents.size();
11868            for (int j=0; j<NI; j++) {
11869                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11870                if ("activity".equals(type)) {
11871                    final PackageSetting ps =
11872                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11873                    final List<PackageParser.Activity> systemActivities =
11874                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11875                    adjustPriority(systemActivities, intent);
11876                }
11877                if (DEBUG_SHOW_INFO) {
11878                    Log.v(TAG, "    IntentFilter:");
11879                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11880                }
11881                if (!intent.debugCheck()) {
11882                    Log.w(TAG, "==> For Activity " + a.info.name);
11883                }
11884                addFilter(intent);
11885            }
11886        }
11887
11888        public final void removeActivity(PackageParser.Activity a, String type) {
11889            mActivities.remove(a.getComponentName());
11890            if (DEBUG_SHOW_INFO) {
11891                Log.v(TAG, "  " + type + " "
11892                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11893                                : a.info.name) + ":");
11894                Log.v(TAG, "    Class=" + a.info.name);
11895            }
11896            final int NI = a.intents.size();
11897            for (int j=0; j<NI; j++) {
11898                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11899                if (DEBUG_SHOW_INFO) {
11900                    Log.v(TAG, "    IntentFilter:");
11901                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11902                }
11903                removeFilter(intent);
11904            }
11905        }
11906
11907        @Override
11908        protected boolean allowFilterResult(
11909                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11910            ActivityInfo filterAi = filter.activity.info;
11911            for (int i=dest.size()-1; i>=0; i--) {
11912                ActivityInfo destAi = dest.get(i).activityInfo;
11913                if (destAi.name == filterAi.name
11914                        && destAi.packageName == filterAi.packageName) {
11915                    return false;
11916                }
11917            }
11918            return true;
11919        }
11920
11921        @Override
11922        protected ActivityIntentInfo[] newArray(int size) {
11923            return new ActivityIntentInfo[size];
11924        }
11925
11926        @Override
11927        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11928            if (!sUserManager.exists(userId)) return true;
11929            PackageParser.Package p = filter.activity.owner;
11930            if (p != null) {
11931                PackageSetting ps = (PackageSetting)p.mExtras;
11932                if (ps != null) {
11933                    // System apps are never considered stopped for purposes of
11934                    // filtering, because there may be no way for the user to
11935                    // actually re-launch them.
11936                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11937                            && ps.getStopped(userId);
11938                }
11939            }
11940            return false;
11941        }
11942
11943        @Override
11944        protected boolean isPackageForFilter(String packageName,
11945                PackageParser.ActivityIntentInfo info) {
11946            return packageName.equals(info.activity.owner.packageName);
11947        }
11948
11949        @Override
11950        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11951                int match, int userId) {
11952            if (!sUserManager.exists(userId)) return null;
11953            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11954                return null;
11955            }
11956            final PackageParser.Activity activity = info.activity;
11957            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11958            if (ps == null) {
11959                return null;
11960            }
11961            final PackageUserState userState = ps.readUserState(userId);
11962            ActivityInfo ai =
11963                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
11964            if (ai == null) {
11965                return null;
11966            }
11967            final boolean matchExplicitlyVisibleOnly =
11968                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
11969            final boolean matchVisibleToInstantApp =
11970                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
11971            final boolean componentVisible =
11972                    matchVisibleToInstantApp
11973                    && info.isVisibleToInstantApp()
11974                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
11975            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
11976            // throw out filters that aren't visible to ephemeral apps
11977            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
11978                return null;
11979            }
11980            // throw out instant app filters if we're not explicitly requesting them
11981            if (!matchInstantApp && userState.instantApp) {
11982                return null;
11983            }
11984            // throw out instant app filters if updates are available; will trigger
11985            // instant app resolution
11986            if (userState.instantApp && ps.isUpdateAvailable()) {
11987                return null;
11988            }
11989            final ResolveInfo res = new ResolveInfo();
11990            res.activityInfo = ai;
11991            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11992                res.filter = info;
11993            }
11994            if (info != null) {
11995                res.handleAllWebDataURI = info.handleAllWebDataURI();
11996            }
11997            res.priority = info.getPriority();
11998            res.preferredOrder = activity.owner.mPreferredOrder;
11999            //System.out.println("Result: " + res.activityInfo.className +
12000            //                   " = " + res.priority);
12001            res.match = match;
12002            res.isDefault = info.hasDefault;
12003            res.labelRes = info.labelRes;
12004            res.nonLocalizedLabel = info.nonLocalizedLabel;
12005            if (userNeedsBadging(userId)) {
12006                res.noResourceId = true;
12007            } else {
12008                res.icon = info.icon;
12009            }
12010            res.iconResourceId = info.icon;
12011            res.system = res.activityInfo.applicationInfo.isSystemApp();
12012            res.isInstantAppAvailable = userState.instantApp;
12013            return res;
12014        }
12015
12016        @Override
12017        protected void sortResults(List<ResolveInfo> results) {
12018            Collections.sort(results, mResolvePrioritySorter);
12019        }
12020
12021        @Override
12022        protected void dumpFilter(PrintWriter out, String prefix,
12023                PackageParser.ActivityIntentInfo filter) {
12024            out.print(prefix); out.print(
12025                    Integer.toHexString(System.identityHashCode(filter.activity)));
12026                    out.print(' ');
12027                    filter.activity.printComponentShortName(out);
12028                    out.print(" filter ");
12029                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12030        }
12031
12032        @Override
12033        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12034            return filter.activity;
12035        }
12036
12037        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12038            PackageParser.Activity activity = (PackageParser.Activity)label;
12039            out.print(prefix); out.print(
12040                    Integer.toHexString(System.identityHashCode(activity)));
12041                    out.print(' ');
12042                    activity.printComponentShortName(out);
12043            if (count > 1) {
12044                out.print(" ("); out.print(count); out.print(" filters)");
12045            }
12046            out.println();
12047        }
12048
12049        // Keys are String (activity class name), values are Activity.
12050        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12051                = new ArrayMap<ComponentName, PackageParser.Activity>();
12052        private int mFlags;
12053    }
12054
12055    private final class ServiceIntentResolver
12056            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12057        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12058                boolean defaultOnly, int userId) {
12059            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12060            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12061        }
12062
12063        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12064                int userId) {
12065            if (!sUserManager.exists(userId)) return null;
12066            mFlags = flags;
12067            return super.queryIntent(intent, resolvedType,
12068                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12069                    userId);
12070        }
12071
12072        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12073                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12074            if (!sUserManager.exists(userId)) return null;
12075            if (packageServices == null) {
12076                return null;
12077            }
12078            mFlags = flags;
12079            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12080            final int N = packageServices.size();
12081            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12082                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12083
12084            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12085            for (int i = 0; i < N; ++i) {
12086                intentFilters = packageServices.get(i).intents;
12087                if (intentFilters != null && intentFilters.size() > 0) {
12088                    PackageParser.ServiceIntentInfo[] array =
12089                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12090                    intentFilters.toArray(array);
12091                    listCut.add(array);
12092                }
12093            }
12094            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12095        }
12096
12097        public final void addService(PackageParser.Service s) {
12098            mServices.put(s.getComponentName(), s);
12099            if (DEBUG_SHOW_INFO) {
12100                Log.v(TAG, "  "
12101                        + (s.info.nonLocalizedLabel != null
12102                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12103                Log.v(TAG, "    Class=" + s.info.name);
12104            }
12105            final int NI = s.intents.size();
12106            int j;
12107            for (j=0; j<NI; j++) {
12108                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12109                if (DEBUG_SHOW_INFO) {
12110                    Log.v(TAG, "    IntentFilter:");
12111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12112                }
12113                if (!intent.debugCheck()) {
12114                    Log.w(TAG, "==> For Service " + s.info.name);
12115                }
12116                addFilter(intent);
12117            }
12118        }
12119
12120        public final void removeService(PackageParser.Service s) {
12121            mServices.remove(s.getComponentName());
12122            if (DEBUG_SHOW_INFO) {
12123                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12124                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12125                Log.v(TAG, "    Class=" + s.info.name);
12126            }
12127            final int NI = s.intents.size();
12128            int j;
12129            for (j=0; j<NI; j++) {
12130                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12131                if (DEBUG_SHOW_INFO) {
12132                    Log.v(TAG, "    IntentFilter:");
12133                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12134                }
12135                removeFilter(intent);
12136            }
12137        }
12138
12139        @Override
12140        protected boolean allowFilterResult(
12141                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12142            ServiceInfo filterSi = filter.service.info;
12143            for (int i=dest.size()-1; i>=0; i--) {
12144                ServiceInfo destAi = dest.get(i).serviceInfo;
12145                if (destAi.name == filterSi.name
12146                        && destAi.packageName == filterSi.packageName) {
12147                    return false;
12148                }
12149            }
12150            return true;
12151        }
12152
12153        @Override
12154        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12155            return new PackageParser.ServiceIntentInfo[size];
12156        }
12157
12158        @Override
12159        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12160            if (!sUserManager.exists(userId)) return true;
12161            PackageParser.Package p = filter.service.owner;
12162            if (p != null) {
12163                PackageSetting ps = (PackageSetting)p.mExtras;
12164                if (ps != null) {
12165                    // System apps are never considered stopped for purposes of
12166                    // filtering, because there may be no way for the user to
12167                    // actually re-launch them.
12168                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12169                            && ps.getStopped(userId);
12170                }
12171            }
12172            return false;
12173        }
12174
12175        @Override
12176        protected boolean isPackageForFilter(String packageName,
12177                PackageParser.ServiceIntentInfo info) {
12178            return packageName.equals(info.service.owner.packageName);
12179        }
12180
12181        @Override
12182        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12183                int match, int userId) {
12184            if (!sUserManager.exists(userId)) return null;
12185            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12186            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12187                return null;
12188            }
12189            final PackageParser.Service service = info.service;
12190            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12191            if (ps == null) {
12192                return null;
12193            }
12194            final PackageUserState userState = ps.readUserState(userId);
12195            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12196                    userState, userId);
12197            if (si == null) {
12198                return null;
12199            }
12200            final boolean matchVisibleToInstantApp =
12201                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12202            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12203            // throw out filters that aren't visible to ephemeral apps
12204            if (matchVisibleToInstantApp
12205                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12206                return null;
12207            }
12208            // throw out ephemeral filters if we're not explicitly requesting them
12209            if (!isInstantApp && userState.instantApp) {
12210                return null;
12211            }
12212            // throw out instant app filters if updates are available; will trigger
12213            // instant app resolution
12214            if (userState.instantApp && ps.isUpdateAvailable()) {
12215                return null;
12216            }
12217            final ResolveInfo res = new ResolveInfo();
12218            res.serviceInfo = si;
12219            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12220                res.filter = filter;
12221            }
12222            res.priority = info.getPriority();
12223            res.preferredOrder = service.owner.mPreferredOrder;
12224            res.match = match;
12225            res.isDefault = info.hasDefault;
12226            res.labelRes = info.labelRes;
12227            res.nonLocalizedLabel = info.nonLocalizedLabel;
12228            res.icon = info.icon;
12229            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12230            return res;
12231        }
12232
12233        @Override
12234        protected void sortResults(List<ResolveInfo> results) {
12235            Collections.sort(results, mResolvePrioritySorter);
12236        }
12237
12238        @Override
12239        protected void dumpFilter(PrintWriter out, String prefix,
12240                PackageParser.ServiceIntentInfo filter) {
12241            out.print(prefix); out.print(
12242                    Integer.toHexString(System.identityHashCode(filter.service)));
12243                    out.print(' ');
12244                    filter.service.printComponentShortName(out);
12245                    out.print(" filter ");
12246                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12247        }
12248
12249        @Override
12250        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12251            return filter.service;
12252        }
12253
12254        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12255            PackageParser.Service service = (PackageParser.Service)label;
12256            out.print(prefix); out.print(
12257                    Integer.toHexString(System.identityHashCode(service)));
12258                    out.print(' ');
12259                    service.printComponentShortName(out);
12260            if (count > 1) {
12261                out.print(" ("); out.print(count); out.print(" filters)");
12262            }
12263            out.println();
12264        }
12265
12266//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12267//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12268//            final List<ResolveInfo> retList = Lists.newArrayList();
12269//            while (i.hasNext()) {
12270//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12271//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12272//                    retList.add(resolveInfo);
12273//                }
12274//            }
12275//            return retList;
12276//        }
12277
12278        // Keys are String (activity class name), values are Activity.
12279        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12280                = new ArrayMap<ComponentName, PackageParser.Service>();
12281        private int mFlags;
12282    }
12283
12284    private final class ProviderIntentResolver
12285            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12286        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12287                boolean defaultOnly, int userId) {
12288            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12289            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12290        }
12291
12292        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12293                int userId) {
12294            if (!sUserManager.exists(userId))
12295                return null;
12296            mFlags = flags;
12297            return super.queryIntent(intent, resolvedType,
12298                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12299                    userId);
12300        }
12301
12302        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12303                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12304            if (!sUserManager.exists(userId))
12305                return null;
12306            if (packageProviders == null) {
12307                return null;
12308            }
12309            mFlags = flags;
12310            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12311            final int N = packageProviders.size();
12312            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12313                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12314
12315            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12316            for (int i = 0; i < N; ++i) {
12317                intentFilters = packageProviders.get(i).intents;
12318                if (intentFilters != null && intentFilters.size() > 0) {
12319                    PackageParser.ProviderIntentInfo[] array =
12320                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12321                    intentFilters.toArray(array);
12322                    listCut.add(array);
12323                }
12324            }
12325            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12326        }
12327
12328        public final void addProvider(PackageParser.Provider p) {
12329            if (mProviders.containsKey(p.getComponentName())) {
12330                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12331                return;
12332            }
12333
12334            mProviders.put(p.getComponentName(), p);
12335            if (DEBUG_SHOW_INFO) {
12336                Log.v(TAG, "  "
12337                        + (p.info.nonLocalizedLabel != null
12338                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12339                Log.v(TAG, "    Class=" + p.info.name);
12340            }
12341            final int NI = p.intents.size();
12342            int j;
12343            for (j = 0; j < NI; j++) {
12344                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12345                if (DEBUG_SHOW_INFO) {
12346                    Log.v(TAG, "    IntentFilter:");
12347                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12348                }
12349                if (!intent.debugCheck()) {
12350                    Log.w(TAG, "==> For Provider " + p.info.name);
12351                }
12352                addFilter(intent);
12353            }
12354        }
12355
12356        public final void removeProvider(PackageParser.Provider p) {
12357            mProviders.remove(p.getComponentName());
12358            if (DEBUG_SHOW_INFO) {
12359                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12360                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12361                Log.v(TAG, "    Class=" + p.info.name);
12362            }
12363            final int NI = p.intents.size();
12364            int j;
12365            for (j = 0; j < NI; j++) {
12366                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12367                if (DEBUG_SHOW_INFO) {
12368                    Log.v(TAG, "    IntentFilter:");
12369                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12370                }
12371                removeFilter(intent);
12372            }
12373        }
12374
12375        @Override
12376        protected boolean allowFilterResult(
12377                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12378            ProviderInfo filterPi = filter.provider.info;
12379            for (int i = dest.size() - 1; i >= 0; i--) {
12380                ProviderInfo destPi = dest.get(i).providerInfo;
12381                if (destPi.name == filterPi.name
12382                        && destPi.packageName == filterPi.packageName) {
12383                    return false;
12384                }
12385            }
12386            return true;
12387        }
12388
12389        @Override
12390        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12391            return new PackageParser.ProviderIntentInfo[size];
12392        }
12393
12394        @Override
12395        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12396            if (!sUserManager.exists(userId))
12397                return true;
12398            PackageParser.Package p = filter.provider.owner;
12399            if (p != null) {
12400                PackageSetting ps = (PackageSetting) p.mExtras;
12401                if (ps != null) {
12402                    // System apps are never considered stopped for purposes of
12403                    // filtering, because there may be no way for the user to
12404                    // actually re-launch them.
12405                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12406                            && ps.getStopped(userId);
12407                }
12408            }
12409            return false;
12410        }
12411
12412        @Override
12413        protected boolean isPackageForFilter(String packageName,
12414                PackageParser.ProviderIntentInfo info) {
12415            return packageName.equals(info.provider.owner.packageName);
12416        }
12417
12418        @Override
12419        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12420                int match, int userId) {
12421            if (!sUserManager.exists(userId))
12422                return null;
12423            final PackageParser.ProviderIntentInfo info = filter;
12424            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12425                return null;
12426            }
12427            final PackageParser.Provider provider = info.provider;
12428            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12429            if (ps == null) {
12430                return null;
12431            }
12432            final PackageUserState userState = ps.readUserState(userId);
12433            final boolean matchVisibleToInstantApp =
12434                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12435            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12436            // throw out filters that aren't visible to instant applications
12437            if (matchVisibleToInstantApp
12438                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12439                return null;
12440            }
12441            // throw out instant application filters if we're not explicitly requesting them
12442            if (!isInstantApp && userState.instantApp) {
12443                return null;
12444            }
12445            // throw out instant application filters if updates are available; will trigger
12446            // instant application resolution
12447            if (userState.instantApp && ps.isUpdateAvailable()) {
12448                return null;
12449            }
12450            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12451                    userState, userId);
12452            if (pi == null) {
12453                return null;
12454            }
12455            final ResolveInfo res = new ResolveInfo();
12456            res.providerInfo = pi;
12457            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12458                res.filter = filter;
12459            }
12460            res.priority = info.getPriority();
12461            res.preferredOrder = provider.owner.mPreferredOrder;
12462            res.match = match;
12463            res.isDefault = info.hasDefault;
12464            res.labelRes = info.labelRes;
12465            res.nonLocalizedLabel = info.nonLocalizedLabel;
12466            res.icon = info.icon;
12467            res.system = res.providerInfo.applicationInfo.isSystemApp();
12468            return res;
12469        }
12470
12471        @Override
12472        protected void sortResults(List<ResolveInfo> results) {
12473            Collections.sort(results, mResolvePrioritySorter);
12474        }
12475
12476        @Override
12477        protected void dumpFilter(PrintWriter out, String prefix,
12478                PackageParser.ProviderIntentInfo filter) {
12479            out.print(prefix);
12480            out.print(
12481                    Integer.toHexString(System.identityHashCode(filter.provider)));
12482            out.print(' ');
12483            filter.provider.printComponentShortName(out);
12484            out.print(" filter ");
12485            out.println(Integer.toHexString(System.identityHashCode(filter)));
12486        }
12487
12488        @Override
12489        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12490            return filter.provider;
12491        }
12492
12493        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12494            PackageParser.Provider provider = (PackageParser.Provider)label;
12495            out.print(prefix); out.print(
12496                    Integer.toHexString(System.identityHashCode(provider)));
12497                    out.print(' ');
12498                    provider.printComponentShortName(out);
12499            if (count > 1) {
12500                out.print(" ("); out.print(count); out.print(" filters)");
12501            }
12502            out.println();
12503        }
12504
12505        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12506                = new ArrayMap<ComponentName, PackageParser.Provider>();
12507        private int mFlags;
12508    }
12509
12510    static final class EphemeralIntentResolver
12511            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12512        /**
12513         * The result that has the highest defined order. Ordering applies on a
12514         * per-package basis. Mapping is from package name to Pair of order and
12515         * EphemeralResolveInfo.
12516         * <p>
12517         * NOTE: This is implemented as a field variable for convenience and efficiency.
12518         * By having a field variable, we're able to track filter ordering as soon as
12519         * a non-zero order is defined. Otherwise, multiple loops across the result set
12520         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12521         * this needs to be contained entirely within {@link #filterResults}.
12522         */
12523        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12524
12525        @Override
12526        protected AuxiliaryResolveInfo[] newArray(int size) {
12527            return new AuxiliaryResolveInfo[size];
12528        }
12529
12530        @Override
12531        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12532            return true;
12533        }
12534
12535        @Override
12536        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12537                int userId) {
12538            if (!sUserManager.exists(userId)) {
12539                return null;
12540            }
12541            final String packageName = responseObj.resolveInfo.getPackageName();
12542            final Integer order = responseObj.getOrder();
12543            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12544                    mOrderResult.get(packageName);
12545            // ordering is enabled and this item's order isn't high enough
12546            if (lastOrderResult != null && lastOrderResult.first >= order) {
12547                return null;
12548            }
12549            final InstantAppResolveInfo res = responseObj.resolveInfo;
12550            if (order > 0) {
12551                // non-zero order, enable ordering
12552                mOrderResult.put(packageName, new Pair<>(order, res));
12553            }
12554            return responseObj;
12555        }
12556
12557        @Override
12558        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12559            // only do work if ordering is enabled [most of the time it won't be]
12560            if (mOrderResult.size() == 0) {
12561                return;
12562            }
12563            int resultSize = results.size();
12564            for (int i = 0; i < resultSize; i++) {
12565                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12566                final String packageName = info.getPackageName();
12567                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12568                if (savedInfo == null) {
12569                    // package doesn't having ordering
12570                    continue;
12571                }
12572                if (savedInfo.second == info) {
12573                    // circled back to the highest ordered item; remove from order list
12574                    mOrderResult.remove(packageName);
12575                    if (mOrderResult.size() == 0) {
12576                        // no more ordered items
12577                        break;
12578                    }
12579                    continue;
12580                }
12581                // item has a worse order, remove it from the result list
12582                results.remove(i);
12583                resultSize--;
12584                i--;
12585            }
12586        }
12587    }
12588
12589    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12590            new Comparator<ResolveInfo>() {
12591        public int compare(ResolveInfo r1, ResolveInfo r2) {
12592            int v1 = r1.priority;
12593            int v2 = r2.priority;
12594            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12595            if (v1 != v2) {
12596                return (v1 > v2) ? -1 : 1;
12597            }
12598            v1 = r1.preferredOrder;
12599            v2 = r2.preferredOrder;
12600            if (v1 != v2) {
12601                return (v1 > v2) ? -1 : 1;
12602            }
12603            if (r1.isDefault != r2.isDefault) {
12604                return r1.isDefault ? -1 : 1;
12605            }
12606            v1 = r1.match;
12607            v2 = r2.match;
12608            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12609            if (v1 != v2) {
12610                return (v1 > v2) ? -1 : 1;
12611            }
12612            if (r1.system != r2.system) {
12613                return r1.system ? -1 : 1;
12614            }
12615            if (r1.activityInfo != null) {
12616                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12617            }
12618            if (r1.serviceInfo != null) {
12619                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12620            }
12621            if (r1.providerInfo != null) {
12622                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12623            }
12624            return 0;
12625        }
12626    };
12627
12628    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12629            new Comparator<ProviderInfo>() {
12630        public int compare(ProviderInfo p1, ProviderInfo p2) {
12631            final int v1 = p1.initOrder;
12632            final int v2 = p2.initOrder;
12633            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12634        }
12635    };
12636
12637    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12638            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12639            final int[] userIds) {
12640        mHandler.post(new Runnable() {
12641            @Override
12642            public void run() {
12643                try {
12644                    final IActivityManager am = ActivityManager.getService();
12645                    if (am == null) return;
12646                    final int[] resolvedUserIds;
12647                    if (userIds == null) {
12648                        resolvedUserIds = am.getRunningUserIds();
12649                    } else {
12650                        resolvedUserIds = userIds;
12651                    }
12652                    for (int id : resolvedUserIds) {
12653                        final Intent intent = new Intent(action,
12654                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12655                        if (extras != null) {
12656                            intent.putExtras(extras);
12657                        }
12658                        if (targetPkg != null) {
12659                            intent.setPackage(targetPkg);
12660                        }
12661                        // Modify the UID when posting to other users
12662                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12663                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12664                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12665                            intent.putExtra(Intent.EXTRA_UID, uid);
12666                        }
12667                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12668                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12669                        if (DEBUG_BROADCASTS) {
12670                            RuntimeException here = new RuntimeException("here");
12671                            here.fillInStackTrace();
12672                            Slog.d(TAG, "Sending to user " + id + ": "
12673                                    + intent.toShortString(false, true, false, false)
12674                                    + " " + intent.getExtras(), here);
12675                        }
12676                        am.broadcastIntent(null, intent, null, finishedReceiver,
12677                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12678                                null, finishedReceiver != null, false, id);
12679                    }
12680                } catch (RemoteException ex) {
12681                }
12682            }
12683        });
12684    }
12685
12686    /**
12687     * Check if the external storage media is available. This is true if there
12688     * is a mounted external storage medium or if the external storage is
12689     * emulated.
12690     */
12691    private boolean isExternalMediaAvailable() {
12692        return mMediaMounted || Environment.isExternalStorageEmulated();
12693    }
12694
12695    @Override
12696    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12697        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
12698            return null;
12699        }
12700        // writer
12701        synchronized (mPackages) {
12702            if (!isExternalMediaAvailable()) {
12703                // If the external storage is no longer mounted at this point,
12704                // the caller may not have been able to delete all of this
12705                // packages files and can not delete any more.  Bail.
12706                return null;
12707            }
12708            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12709            if (lastPackage != null) {
12710                pkgs.remove(lastPackage);
12711            }
12712            if (pkgs.size() > 0) {
12713                return pkgs.get(0);
12714            }
12715        }
12716        return null;
12717    }
12718
12719    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12720        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12721                userId, andCode ? 1 : 0, packageName);
12722        if (mSystemReady) {
12723            msg.sendToTarget();
12724        } else {
12725            if (mPostSystemReadyMessages == null) {
12726                mPostSystemReadyMessages = new ArrayList<>();
12727            }
12728            mPostSystemReadyMessages.add(msg);
12729        }
12730    }
12731
12732    void startCleaningPackages() {
12733        // reader
12734        if (!isExternalMediaAvailable()) {
12735            return;
12736        }
12737        synchronized (mPackages) {
12738            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12739                return;
12740            }
12741        }
12742        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12743        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12744        IActivityManager am = ActivityManager.getService();
12745        if (am != null) {
12746            int dcsUid = -1;
12747            synchronized (mPackages) {
12748                if (!mDefaultContainerWhitelisted) {
12749                    mDefaultContainerWhitelisted = true;
12750                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
12751                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
12752                }
12753            }
12754            try {
12755                if (dcsUid > 0) {
12756                    am.backgroundWhitelistUid(dcsUid);
12757                }
12758                am.startService(null, intent, null, false, mContext.getOpPackageName(),
12759                        UserHandle.USER_SYSTEM);
12760            } catch (RemoteException e) {
12761            }
12762        }
12763    }
12764
12765    @Override
12766    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12767            int installFlags, String installerPackageName, int userId) {
12768        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12769
12770        final int callingUid = Binder.getCallingUid();
12771        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
12772                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12773
12774        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12775            try {
12776                if (observer != null) {
12777                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12778                }
12779            } catch (RemoteException re) {
12780            }
12781            return;
12782        }
12783
12784        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12785            installFlags |= PackageManager.INSTALL_FROM_ADB;
12786
12787        } else {
12788            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12789            // about installerPackageName.
12790
12791            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12792            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12793        }
12794
12795        UserHandle user;
12796        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12797            user = UserHandle.ALL;
12798        } else {
12799            user = new UserHandle(userId);
12800        }
12801
12802        // Only system components can circumvent runtime permissions when installing.
12803        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12804                && mContext.checkCallingOrSelfPermission(Manifest.permission
12805                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12806            throw new SecurityException("You need the "
12807                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12808                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12809        }
12810
12811        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12812                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12813            throw new IllegalArgumentException(
12814                    "New installs into ASEC containers no longer supported");
12815        }
12816
12817        final File originFile = new File(originPath);
12818        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12819
12820        final Message msg = mHandler.obtainMessage(INIT_COPY);
12821        final VerificationInfo verificationInfo = new VerificationInfo(
12822                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12823        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12824                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12825                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12826                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12827        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12828        msg.obj = params;
12829
12830        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12831                System.identityHashCode(msg.obj));
12832        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12833                System.identityHashCode(msg.obj));
12834
12835        mHandler.sendMessage(msg);
12836    }
12837
12838
12839    /**
12840     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12841     * it is acting on behalf on an enterprise or the user).
12842     *
12843     * Note that the ordering of the conditionals in this method is important. The checks we perform
12844     * are as follows, in this order:
12845     *
12846     * 1) If the install is being performed by a system app, we can trust the app to have set the
12847     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12848     *    what it is.
12849     * 2) If the install is being performed by a device or profile owner app, the install reason
12850     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12851     *    set the install reason correctly. If the app targets an older SDK version where install
12852     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12853     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12854     * 3) In all other cases, the install is being performed by a regular app that is neither part
12855     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12856     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12857     *    set to enterprise policy and if so, change it to unknown instead.
12858     */
12859    private int fixUpInstallReason(String installerPackageName, int installerUid,
12860            int installReason) {
12861        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12862                == PERMISSION_GRANTED) {
12863            // If the install is being performed by a system app, we trust that app to have set the
12864            // install reason correctly.
12865            return installReason;
12866        }
12867
12868        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12869            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12870        if (dpm != null) {
12871            ComponentName owner = null;
12872            try {
12873                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12874                if (owner == null) {
12875                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12876                }
12877            } catch (RemoteException e) {
12878            }
12879            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12880                // If the install is being performed by a device or profile owner, the install
12881                // reason should be enterprise policy.
12882                return PackageManager.INSTALL_REASON_POLICY;
12883            }
12884        }
12885
12886        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12887            // If the install is being performed by a regular app (i.e. neither system app nor
12888            // device or profile owner), we have no reason to believe that the app is acting on
12889            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12890            // change it to unknown instead.
12891            return PackageManager.INSTALL_REASON_UNKNOWN;
12892        }
12893
12894        // If the install is being performed by a regular app and the install reason was set to any
12895        // value but enterprise policy, leave the install reason unchanged.
12896        return installReason;
12897    }
12898
12899    void installStage(String packageName, File stagedDir,
12900            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12901            String installerPackageName, int installerUid, UserHandle user,
12902            Certificate[][] certificates) {
12903        if (DEBUG_EPHEMERAL) {
12904            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
12905                Slog.d(TAG, "Ephemeral install of " + packageName);
12906            }
12907        }
12908        final VerificationInfo verificationInfo = new VerificationInfo(
12909                sessionParams.originatingUri, sessionParams.referrerUri,
12910                sessionParams.originatingUid, installerUid);
12911
12912        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
12913
12914        final Message msg = mHandler.obtainMessage(INIT_COPY);
12915        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
12916                sessionParams.installReason);
12917        final InstallParams params = new InstallParams(origin, null, observer,
12918                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12919                verificationInfo, user, sessionParams.abiOverride,
12920                sessionParams.grantedRuntimePermissions, certificates, installReason);
12921        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12922        msg.obj = params;
12923
12924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12925                System.identityHashCode(msg.obj));
12926        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12927                System.identityHashCode(msg.obj));
12928
12929        mHandler.sendMessage(msg);
12930    }
12931
12932    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12933            int userId) {
12934        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12935        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
12936                false /*startReceiver*/, pkgSetting.appId, userId);
12937
12938        // Send a session commit broadcast
12939        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
12940        info.installReason = pkgSetting.getInstallReason(userId);
12941        info.appPackageName = packageName;
12942        sendSessionCommitBroadcast(info, userId);
12943    }
12944
12945    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
12946            boolean includeStopped, int appId, int... userIds) {
12947        if (ArrayUtils.isEmpty(userIds)) {
12948            return;
12949        }
12950        Bundle extras = new Bundle(1);
12951        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12952        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12953
12954        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12955                packageName, extras, 0, null, null, userIds);
12956        if (sendBootCompleted) {
12957            mHandler.post(() -> {
12958                        for (int userId : userIds) {
12959                            sendBootCompletedBroadcastToSystemApp(
12960                                    packageName, includeStopped, userId);
12961                        }
12962                    }
12963            );
12964        }
12965    }
12966
12967    /**
12968     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12969     * automatically without needing an explicit launch.
12970     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12971     */
12972    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
12973            int userId) {
12974        // If user is not running, the app didn't miss any broadcast
12975        if (!mUserManagerInternal.isUserRunning(userId)) {
12976            return;
12977        }
12978        final IActivityManager am = ActivityManager.getService();
12979        try {
12980            // Deliver LOCKED_BOOT_COMPLETED first
12981            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12982                    .setPackage(packageName);
12983            if (includeStopped) {
12984                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
12985            }
12986            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12987            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12988                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12989
12990            // Deliver BOOT_COMPLETED only if user is unlocked
12991            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12992                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12993                if (includeStopped) {
12994                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
12995                }
12996                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12997                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12998            }
12999        } catch (RemoteException e) {
13000            throw e.rethrowFromSystemServer();
13001        }
13002    }
13003
13004    @Override
13005    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13006            int userId) {
13007        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13008        PackageSetting pkgSetting;
13009        final int callingUid = Binder.getCallingUid();
13010        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13011                true /* requireFullPermission */, true /* checkShell */,
13012                "setApplicationHiddenSetting for user " + userId);
13013
13014        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13015            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13016            return false;
13017        }
13018
13019        long callingId = Binder.clearCallingIdentity();
13020        try {
13021            boolean sendAdded = false;
13022            boolean sendRemoved = false;
13023            // writer
13024            synchronized (mPackages) {
13025                pkgSetting = mSettings.mPackages.get(packageName);
13026                if (pkgSetting == null) {
13027                    return false;
13028                }
13029                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13030                    return false;
13031                }
13032                // Do not allow "android" is being disabled
13033                if ("android".equals(packageName)) {
13034                    Slog.w(TAG, "Cannot hide package: android");
13035                    return false;
13036                }
13037                // Cannot hide static shared libs as they are considered
13038                // a part of the using app (emulating static linking). Also
13039                // static libs are installed always on internal storage.
13040                PackageParser.Package pkg = mPackages.get(packageName);
13041                if (pkg != null && pkg.staticSharedLibName != null) {
13042                    Slog.w(TAG, "Cannot hide package: " + packageName
13043                            + " providing static shared library: "
13044                            + pkg.staticSharedLibName);
13045                    return false;
13046                }
13047                // Only allow protected packages to hide themselves.
13048                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13049                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13050                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13051                    return false;
13052                }
13053
13054                if (pkgSetting.getHidden(userId) != hidden) {
13055                    pkgSetting.setHidden(hidden, userId);
13056                    mSettings.writePackageRestrictionsLPr(userId);
13057                    if (hidden) {
13058                        sendRemoved = true;
13059                    } else {
13060                        sendAdded = true;
13061                    }
13062                }
13063            }
13064            if (sendAdded) {
13065                sendPackageAddedForUser(packageName, pkgSetting, userId);
13066                return true;
13067            }
13068            if (sendRemoved) {
13069                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13070                        "hiding pkg");
13071                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13072                return true;
13073            }
13074        } finally {
13075            Binder.restoreCallingIdentity(callingId);
13076        }
13077        return false;
13078    }
13079
13080    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13081            int userId) {
13082        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13083        info.removedPackage = packageName;
13084        info.installerPackageName = pkgSetting.installerPackageName;
13085        info.removedUsers = new int[] {userId};
13086        info.broadcastUsers = new int[] {userId};
13087        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13088        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13089    }
13090
13091    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13092        if (pkgList.length > 0) {
13093            Bundle extras = new Bundle(1);
13094            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13095
13096            sendPackageBroadcast(
13097                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13098                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13099                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13100                    new int[] {userId});
13101        }
13102    }
13103
13104    /**
13105     * Returns true if application is not found or there was an error. Otherwise it returns
13106     * the hidden state of the package for the given user.
13107     */
13108    @Override
13109    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13110        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13111        final int callingUid = Binder.getCallingUid();
13112        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13113                true /* requireFullPermission */, false /* checkShell */,
13114                "getApplicationHidden for user " + userId);
13115        PackageSetting ps;
13116        long callingId = Binder.clearCallingIdentity();
13117        try {
13118            // writer
13119            synchronized (mPackages) {
13120                ps = mSettings.mPackages.get(packageName);
13121                if (ps == null) {
13122                    return true;
13123                }
13124                if (filterAppAccessLPr(ps, callingUid, userId)) {
13125                    return true;
13126                }
13127                return ps.getHidden(userId);
13128            }
13129        } finally {
13130            Binder.restoreCallingIdentity(callingId);
13131        }
13132    }
13133
13134    /**
13135     * @hide
13136     */
13137    @Override
13138    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13139            int installReason) {
13140        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13141                null);
13142        PackageSetting pkgSetting;
13143        final int callingUid = Binder.getCallingUid();
13144        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13145                true /* requireFullPermission */, true /* checkShell */,
13146                "installExistingPackage for user " + userId);
13147        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13148            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13149        }
13150
13151        long callingId = Binder.clearCallingIdentity();
13152        try {
13153            boolean installed = false;
13154            final boolean instantApp =
13155                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13156            final boolean fullApp =
13157                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13158
13159            // writer
13160            synchronized (mPackages) {
13161                pkgSetting = mSettings.mPackages.get(packageName);
13162                if (pkgSetting == null) {
13163                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13164                }
13165                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13166                    // only allow the existing package to be used if it's installed as a full
13167                    // application for at least one user
13168                    boolean installAllowed = false;
13169                    for (int checkUserId : sUserManager.getUserIds()) {
13170                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13171                        if (installAllowed) {
13172                            break;
13173                        }
13174                    }
13175                    if (!installAllowed) {
13176                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13177                    }
13178                }
13179                if (!pkgSetting.getInstalled(userId)) {
13180                    pkgSetting.setInstalled(true, userId);
13181                    pkgSetting.setHidden(false, userId);
13182                    pkgSetting.setInstallReason(installReason, userId);
13183                    mSettings.writePackageRestrictionsLPr(userId);
13184                    mSettings.writeKernelMappingLPr(pkgSetting);
13185                    installed = true;
13186                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13187                    // upgrade app from instant to full; we don't allow app downgrade
13188                    installed = true;
13189                }
13190                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13191            }
13192
13193            if (installed) {
13194                if (pkgSetting.pkg != null) {
13195                    synchronized (mInstallLock) {
13196                        // We don't need to freeze for a brand new install
13197                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13198                    }
13199                }
13200                sendPackageAddedForUser(packageName, pkgSetting, userId);
13201                synchronized (mPackages) {
13202                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13203                }
13204            }
13205        } finally {
13206            Binder.restoreCallingIdentity(callingId);
13207        }
13208
13209        return PackageManager.INSTALL_SUCCEEDED;
13210    }
13211
13212    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13213            boolean instantApp, boolean fullApp) {
13214        // no state specified; do nothing
13215        if (!instantApp && !fullApp) {
13216            return;
13217        }
13218        if (userId != UserHandle.USER_ALL) {
13219            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13220                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13221            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13222                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13223            }
13224        } else {
13225            for (int currentUserId : sUserManager.getUserIds()) {
13226                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13227                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13228                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13229                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13230                }
13231            }
13232        }
13233    }
13234
13235    boolean isUserRestricted(int userId, String restrictionKey) {
13236        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13237        if (restrictions.getBoolean(restrictionKey, false)) {
13238            Log.w(TAG, "User is restricted: " + restrictionKey);
13239            return true;
13240        }
13241        return false;
13242    }
13243
13244    @Override
13245    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13246            int userId) {
13247        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13248        final int callingUid = Binder.getCallingUid();
13249        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13250                true /* requireFullPermission */, true /* checkShell */,
13251                "setPackagesSuspended for user " + userId);
13252
13253        if (ArrayUtils.isEmpty(packageNames)) {
13254            return packageNames;
13255        }
13256
13257        // List of package names for whom the suspended state has changed.
13258        List<String> changedPackages = new ArrayList<>(packageNames.length);
13259        // List of package names for whom the suspended state is not set as requested in this
13260        // method.
13261        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13262        long callingId = Binder.clearCallingIdentity();
13263        try {
13264            for (int i = 0; i < packageNames.length; i++) {
13265                String packageName = packageNames[i];
13266                boolean changed = false;
13267                final int appId;
13268                synchronized (mPackages) {
13269                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13270                    if (pkgSetting == null
13271                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13272                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13273                                + "\". Skipping suspending/un-suspending.");
13274                        unactionedPackages.add(packageName);
13275                        continue;
13276                    }
13277                    appId = pkgSetting.appId;
13278                    if (pkgSetting.getSuspended(userId) != suspended) {
13279                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13280                            unactionedPackages.add(packageName);
13281                            continue;
13282                        }
13283                        pkgSetting.setSuspended(suspended, userId);
13284                        mSettings.writePackageRestrictionsLPr(userId);
13285                        changed = true;
13286                        changedPackages.add(packageName);
13287                    }
13288                }
13289
13290                if (changed && suspended) {
13291                    killApplication(packageName, UserHandle.getUid(userId, appId),
13292                            "suspending package");
13293                }
13294            }
13295        } finally {
13296            Binder.restoreCallingIdentity(callingId);
13297        }
13298
13299        if (!changedPackages.isEmpty()) {
13300            sendPackagesSuspendedForUser(changedPackages.toArray(
13301                    new String[changedPackages.size()]), userId, suspended);
13302        }
13303
13304        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13305    }
13306
13307    @Override
13308    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13309        final int callingUid = Binder.getCallingUid();
13310        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13311                true /* requireFullPermission */, false /* checkShell */,
13312                "isPackageSuspendedForUser for user " + userId);
13313        synchronized (mPackages) {
13314            final PackageSetting ps = mSettings.mPackages.get(packageName);
13315            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13316                throw new IllegalArgumentException("Unknown target package: " + packageName);
13317            }
13318            return ps.getSuspended(userId);
13319        }
13320    }
13321
13322    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13323        if (isPackageDeviceAdmin(packageName, userId)) {
13324            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13325                    + "\": has an active device admin");
13326            return false;
13327        }
13328
13329        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13330        if (packageName.equals(activeLauncherPackageName)) {
13331            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13332                    + "\": contains the active launcher");
13333            return false;
13334        }
13335
13336        if (packageName.equals(mRequiredInstallerPackage)) {
13337            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13338                    + "\": required for package installation");
13339            return false;
13340        }
13341
13342        if (packageName.equals(mRequiredUninstallerPackage)) {
13343            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13344                    + "\": required for package uninstallation");
13345            return false;
13346        }
13347
13348        if (packageName.equals(mRequiredVerifierPackage)) {
13349            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13350                    + "\": required for package verification");
13351            return false;
13352        }
13353
13354        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13355            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13356                    + "\": is the default dialer");
13357            return false;
13358        }
13359
13360        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13361            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13362                    + "\": protected package");
13363            return false;
13364        }
13365
13366        // Cannot suspend static shared libs as they are considered
13367        // a part of the using app (emulating static linking). Also
13368        // static libs are installed always on internal storage.
13369        PackageParser.Package pkg = mPackages.get(packageName);
13370        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13371            Slog.w(TAG, "Cannot suspend package: " + packageName
13372                    + " providing static shared library: "
13373                    + pkg.staticSharedLibName);
13374            return false;
13375        }
13376
13377        return true;
13378    }
13379
13380    private String getActiveLauncherPackageName(int userId) {
13381        Intent intent = new Intent(Intent.ACTION_MAIN);
13382        intent.addCategory(Intent.CATEGORY_HOME);
13383        ResolveInfo resolveInfo = resolveIntent(
13384                intent,
13385                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13386                PackageManager.MATCH_DEFAULT_ONLY,
13387                userId);
13388
13389        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13390    }
13391
13392    private String getDefaultDialerPackageName(int userId) {
13393        synchronized (mPackages) {
13394            return mSettings.getDefaultDialerPackageNameLPw(userId);
13395        }
13396    }
13397
13398    @Override
13399    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13400        mContext.enforceCallingOrSelfPermission(
13401                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13402                "Only package verification agents can verify applications");
13403
13404        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13405        final PackageVerificationResponse response = new PackageVerificationResponse(
13406                verificationCode, Binder.getCallingUid());
13407        msg.arg1 = id;
13408        msg.obj = response;
13409        mHandler.sendMessage(msg);
13410    }
13411
13412    @Override
13413    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13414            long millisecondsToDelay) {
13415        mContext.enforceCallingOrSelfPermission(
13416                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13417                "Only package verification agents can extend verification timeouts");
13418
13419        final PackageVerificationState state = mPendingVerification.get(id);
13420        final PackageVerificationResponse response = new PackageVerificationResponse(
13421                verificationCodeAtTimeout, Binder.getCallingUid());
13422
13423        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13424            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13425        }
13426        if (millisecondsToDelay < 0) {
13427            millisecondsToDelay = 0;
13428        }
13429        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13430                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13431            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13432        }
13433
13434        if ((state != null) && !state.timeoutExtended()) {
13435            state.extendTimeout();
13436
13437            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13438            msg.arg1 = id;
13439            msg.obj = response;
13440            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13441        }
13442    }
13443
13444    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13445            int verificationCode, UserHandle user) {
13446        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13447        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13448        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13449        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13450        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13451
13452        mContext.sendBroadcastAsUser(intent, user,
13453                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13454    }
13455
13456    private ComponentName matchComponentForVerifier(String packageName,
13457            List<ResolveInfo> receivers) {
13458        ActivityInfo targetReceiver = null;
13459
13460        final int NR = receivers.size();
13461        for (int i = 0; i < NR; i++) {
13462            final ResolveInfo info = receivers.get(i);
13463            if (info.activityInfo == null) {
13464                continue;
13465            }
13466
13467            if (packageName.equals(info.activityInfo.packageName)) {
13468                targetReceiver = info.activityInfo;
13469                break;
13470            }
13471        }
13472
13473        if (targetReceiver == null) {
13474            return null;
13475        }
13476
13477        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13478    }
13479
13480    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13481            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13482        if (pkgInfo.verifiers.length == 0) {
13483            return null;
13484        }
13485
13486        final int N = pkgInfo.verifiers.length;
13487        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13488        for (int i = 0; i < N; i++) {
13489            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13490
13491            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13492                    receivers);
13493            if (comp == null) {
13494                continue;
13495            }
13496
13497            final int verifierUid = getUidForVerifier(verifierInfo);
13498            if (verifierUid == -1) {
13499                continue;
13500            }
13501
13502            if (DEBUG_VERIFY) {
13503                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13504                        + " with the correct signature");
13505            }
13506            sufficientVerifiers.add(comp);
13507            verificationState.addSufficientVerifier(verifierUid);
13508        }
13509
13510        return sufficientVerifiers;
13511    }
13512
13513    private int getUidForVerifier(VerifierInfo verifierInfo) {
13514        synchronized (mPackages) {
13515            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13516            if (pkg == null) {
13517                return -1;
13518            } else if (pkg.mSignatures.length != 1) {
13519                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13520                        + " has more than one signature; ignoring");
13521                return -1;
13522            }
13523
13524            /*
13525             * If the public key of the package's signature does not match
13526             * our expected public key, then this is a different package and
13527             * we should skip.
13528             */
13529
13530            final byte[] expectedPublicKey;
13531            try {
13532                final Signature verifierSig = pkg.mSignatures[0];
13533                final PublicKey publicKey = verifierSig.getPublicKey();
13534                expectedPublicKey = publicKey.getEncoded();
13535            } catch (CertificateException e) {
13536                return -1;
13537            }
13538
13539            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13540
13541            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13542                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13543                        + " does not have the expected public key; ignoring");
13544                return -1;
13545            }
13546
13547            return pkg.applicationInfo.uid;
13548        }
13549    }
13550
13551    @Override
13552    public void finishPackageInstall(int token, boolean didLaunch) {
13553        enforceSystemOrRoot("Only the system is allowed to finish installs");
13554
13555        if (DEBUG_INSTALL) {
13556            Slog.v(TAG, "BM finishing package install for " + token);
13557        }
13558        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13559
13560        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13561        mHandler.sendMessage(msg);
13562    }
13563
13564    /**
13565     * Get the verification agent timeout.  Used for both the APK verifier and the
13566     * intent filter verifier.
13567     *
13568     * @return verification timeout in milliseconds
13569     */
13570    private long getVerificationTimeout() {
13571        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13572                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13573                DEFAULT_VERIFICATION_TIMEOUT);
13574    }
13575
13576    /**
13577     * Get the default verification agent response code.
13578     *
13579     * @return default verification response code
13580     */
13581    private int getDefaultVerificationResponse(UserHandle user) {
13582        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13583            return PackageManager.VERIFICATION_REJECT;
13584        }
13585        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13586                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13587                DEFAULT_VERIFICATION_RESPONSE);
13588    }
13589
13590    /**
13591     * Check whether or not package verification has been enabled.
13592     *
13593     * @return true if verification should be performed
13594     */
13595    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13596        if (!DEFAULT_VERIFY_ENABLE) {
13597            return false;
13598        }
13599
13600        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13601
13602        // Check if installing from ADB
13603        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13604            // Do not run verification in a test harness environment
13605            if (ActivityManager.isRunningInTestHarness()) {
13606                return false;
13607            }
13608            if (ensureVerifyAppsEnabled) {
13609                return true;
13610            }
13611            // Check if the developer does not want package verification for ADB installs
13612            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13613                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13614                return false;
13615            }
13616        } else {
13617            // only when not installed from ADB, skip verification for instant apps when
13618            // the installer and verifier are the same.
13619            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13620                if (mInstantAppInstallerActivity != null
13621                        && mInstantAppInstallerActivity.packageName.equals(
13622                                mRequiredVerifierPackage)) {
13623                    try {
13624                        mContext.getSystemService(AppOpsManager.class)
13625                                .checkPackage(installerUid, mRequiredVerifierPackage);
13626                        if (DEBUG_VERIFY) {
13627                            Slog.i(TAG, "disable verification for instant app");
13628                        }
13629                        return false;
13630                    } catch (SecurityException ignore) { }
13631                }
13632            }
13633        }
13634
13635        if (ensureVerifyAppsEnabled) {
13636            return true;
13637        }
13638
13639        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13640                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13641    }
13642
13643    @Override
13644    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13645            throws RemoteException {
13646        mContext.enforceCallingOrSelfPermission(
13647                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13648                "Only intentfilter verification agents can verify applications");
13649
13650        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13651        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13652                Binder.getCallingUid(), verificationCode, failedDomains);
13653        msg.arg1 = id;
13654        msg.obj = response;
13655        mHandler.sendMessage(msg);
13656    }
13657
13658    @Override
13659    public int getIntentVerificationStatus(String packageName, int userId) {
13660        final int callingUid = Binder.getCallingUid();
13661        if (UserHandle.getUserId(callingUid) != userId) {
13662            mContext.enforceCallingOrSelfPermission(
13663                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13664                    "getIntentVerificationStatus" + userId);
13665        }
13666        if (getInstantAppPackageName(callingUid) != null) {
13667            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13668        }
13669        synchronized (mPackages) {
13670            final PackageSetting ps = mSettings.mPackages.get(packageName);
13671            if (ps == null
13672                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13673                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13674            }
13675            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13676        }
13677    }
13678
13679    @Override
13680    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13681        mContext.enforceCallingOrSelfPermission(
13682                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13683
13684        boolean result = false;
13685        synchronized (mPackages) {
13686            final PackageSetting ps = mSettings.mPackages.get(packageName);
13687            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13688                return false;
13689            }
13690            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13691        }
13692        if (result) {
13693            scheduleWritePackageRestrictionsLocked(userId);
13694        }
13695        return result;
13696    }
13697
13698    @Override
13699    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13700            String packageName) {
13701        final int callingUid = Binder.getCallingUid();
13702        if (getInstantAppPackageName(callingUid) != null) {
13703            return ParceledListSlice.emptyList();
13704        }
13705        synchronized (mPackages) {
13706            final PackageSetting ps = mSettings.mPackages.get(packageName);
13707            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13708                return ParceledListSlice.emptyList();
13709            }
13710            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13711        }
13712    }
13713
13714    @Override
13715    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13716        if (TextUtils.isEmpty(packageName)) {
13717            return ParceledListSlice.emptyList();
13718        }
13719        final int callingUid = Binder.getCallingUid();
13720        final int callingUserId = UserHandle.getUserId(callingUid);
13721        synchronized (mPackages) {
13722            PackageParser.Package pkg = mPackages.get(packageName);
13723            if (pkg == null || pkg.activities == null) {
13724                return ParceledListSlice.emptyList();
13725            }
13726            if (pkg.mExtras == null) {
13727                return ParceledListSlice.emptyList();
13728            }
13729            final PackageSetting ps = (PackageSetting) pkg.mExtras;
13730            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
13731                return ParceledListSlice.emptyList();
13732            }
13733            final int count = pkg.activities.size();
13734            ArrayList<IntentFilter> result = new ArrayList<>();
13735            for (int n=0; n<count; n++) {
13736                PackageParser.Activity activity = pkg.activities.get(n);
13737                if (activity.intents != null && activity.intents.size() > 0) {
13738                    result.addAll(activity.intents);
13739                }
13740            }
13741            return new ParceledListSlice<>(result);
13742        }
13743    }
13744
13745    @Override
13746    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13747        mContext.enforceCallingOrSelfPermission(
13748                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13749        if (UserHandle.getCallingUserId() != userId) {
13750            mContext.enforceCallingOrSelfPermission(
13751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13752        }
13753
13754        synchronized (mPackages) {
13755            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13756            if (packageName != null) {
13757                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
13758                        packageName, userId);
13759            }
13760            return result;
13761        }
13762    }
13763
13764    @Override
13765    public String getDefaultBrowserPackageName(int userId) {
13766        if (UserHandle.getCallingUserId() != userId) {
13767            mContext.enforceCallingOrSelfPermission(
13768                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13769        }
13770        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13771            return null;
13772        }
13773        synchronized (mPackages) {
13774            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13775        }
13776    }
13777
13778    /**
13779     * Get the "allow unknown sources" setting.
13780     *
13781     * @return the current "allow unknown sources" setting
13782     */
13783    private int getUnknownSourcesSettings() {
13784        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13785                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13786                -1);
13787    }
13788
13789    @Override
13790    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13791        final int callingUid = Binder.getCallingUid();
13792        if (getInstantAppPackageName(callingUid) != null) {
13793            return;
13794        }
13795        // writer
13796        synchronized (mPackages) {
13797            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13798            if (targetPackageSetting == null
13799                    || filterAppAccessLPr(
13800                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
13801                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13802            }
13803
13804            PackageSetting installerPackageSetting;
13805            if (installerPackageName != null) {
13806                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13807                if (installerPackageSetting == null) {
13808                    throw new IllegalArgumentException("Unknown installer package: "
13809                            + installerPackageName);
13810                }
13811            } else {
13812                installerPackageSetting = null;
13813            }
13814
13815            Signature[] callerSignature;
13816            Object obj = mSettings.getUserIdLPr(callingUid);
13817            if (obj != null) {
13818                if (obj instanceof SharedUserSetting) {
13819                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13820                } else if (obj instanceof PackageSetting) {
13821                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13822                } else {
13823                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
13824                }
13825            } else {
13826                throw new SecurityException("Unknown calling UID: " + callingUid);
13827            }
13828
13829            // Verify: can't set installerPackageName to a package that is
13830            // not signed with the same cert as the caller.
13831            if (installerPackageSetting != null) {
13832                if (compareSignatures(callerSignature,
13833                        installerPackageSetting.signatures.mSignatures)
13834                        != PackageManager.SIGNATURE_MATCH) {
13835                    throw new SecurityException(
13836                            "Caller does not have same cert as new installer package "
13837                            + installerPackageName);
13838                }
13839            }
13840
13841            // Verify: if target already has an installer package, it must
13842            // be signed with the same cert as the caller.
13843            if (targetPackageSetting.installerPackageName != null) {
13844                PackageSetting setting = mSettings.mPackages.get(
13845                        targetPackageSetting.installerPackageName);
13846                // If the currently set package isn't valid, then it's always
13847                // okay to change it.
13848                if (setting != null) {
13849                    if (compareSignatures(callerSignature,
13850                            setting.signatures.mSignatures)
13851                            != PackageManager.SIGNATURE_MATCH) {
13852                        throw new SecurityException(
13853                                "Caller does not have same cert as old installer package "
13854                                + targetPackageSetting.installerPackageName);
13855                    }
13856                }
13857            }
13858
13859            // Okay!
13860            targetPackageSetting.installerPackageName = installerPackageName;
13861            if (installerPackageName != null) {
13862                mSettings.mInstallerPackages.add(installerPackageName);
13863            }
13864            scheduleWriteSettingsLocked();
13865        }
13866    }
13867
13868    @Override
13869    public void setApplicationCategoryHint(String packageName, int categoryHint,
13870            String callerPackageName) {
13871        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13872            throw new SecurityException("Instant applications don't have access to this method");
13873        }
13874        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13875                callerPackageName);
13876        synchronized (mPackages) {
13877            PackageSetting ps = mSettings.mPackages.get(packageName);
13878            if (ps == null) {
13879                throw new IllegalArgumentException("Unknown target package " + packageName);
13880            }
13881            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13882                throw new IllegalArgumentException("Unknown target package " + packageName);
13883            }
13884            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13885                throw new IllegalArgumentException("Calling package " + callerPackageName
13886                        + " is not installer for " + packageName);
13887            }
13888
13889            if (ps.categoryHint != categoryHint) {
13890                ps.categoryHint = categoryHint;
13891                scheduleWriteSettingsLocked();
13892            }
13893        }
13894    }
13895
13896    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13897        // Queue up an async operation since the package installation may take a little while.
13898        mHandler.post(new Runnable() {
13899            public void run() {
13900                mHandler.removeCallbacks(this);
13901                 // Result object to be returned
13902                PackageInstalledInfo res = new PackageInstalledInfo();
13903                res.setReturnCode(currentStatus);
13904                res.uid = -1;
13905                res.pkg = null;
13906                res.removedInfo = null;
13907                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13908                    args.doPreInstall(res.returnCode);
13909                    synchronized (mInstallLock) {
13910                        installPackageTracedLI(args, res);
13911                    }
13912                    args.doPostInstall(res.returnCode, res.uid);
13913                }
13914
13915                // A restore should be performed at this point if (a) the install
13916                // succeeded, (b) the operation is not an update, and (c) the new
13917                // package has not opted out of backup participation.
13918                final boolean update = res.removedInfo != null
13919                        && res.removedInfo.removedPackage != null;
13920                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13921                boolean doRestore = !update
13922                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13923
13924                // Set up the post-install work request bookkeeping.  This will be used
13925                // and cleaned up by the post-install event handling regardless of whether
13926                // there's a restore pass performed.  Token values are >= 1.
13927                int token;
13928                if (mNextInstallToken < 0) mNextInstallToken = 1;
13929                token = mNextInstallToken++;
13930
13931                PostInstallData data = new PostInstallData(args, res);
13932                mRunningInstalls.put(token, data);
13933                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13934
13935                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13936                    // Pass responsibility to the Backup Manager.  It will perform a
13937                    // restore if appropriate, then pass responsibility back to the
13938                    // Package Manager to run the post-install observer callbacks
13939                    // and broadcasts.
13940                    IBackupManager bm = IBackupManager.Stub.asInterface(
13941                            ServiceManager.getService(Context.BACKUP_SERVICE));
13942                    if (bm != null) {
13943                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13944                                + " to BM for possible restore");
13945                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13946                        try {
13947                            // TODO: http://b/22388012
13948                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13949                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13950                            } else {
13951                                doRestore = false;
13952                            }
13953                        } catch (RemoteException e) {
13954                            // can't happen; the backup manager is local
13955                        } catch (Exception e) {
13956                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13957                            doRestore = false;
13958                        }
13959                    } else {
13960                        Slog.e(TAG, "Backup Manager not found!");
13961                        doRestore = false;
13962                    }
13963                }
13964
13965                if (!doRestore) {
13966                    // No restore possible, or the Backup Manager was mysteriously not
13967                    // available -- just fire the post-install work request directly.
13968                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13969
13970                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13971
13972                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13973                    mHandler.sendMessage(msg);
13974                }
13975            }
13976        });
13977    }
13978
13979    /**
13980     * Callback from PackageSettings whenever an app is first transitioned out of the
13981     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13982     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13983     * here whether the app is the target of an ongoing install, and only send the
13984     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13985     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13986     * handling.
13987     */
13988    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13989        // Serialize this with the rest of the install-process message chain.  In the
13990        // restore-at-install case, this Runnable will necessarily run before the
13991        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13992        // are coherent.  In the non-restore case, the app has already completed install
13993        // and been launched through some other means, so it is not in a problematic
13994        // state for observers to see the FIRST_LAUNCH signal.
13995        mHandler.post(new Runnable() {
13996            @Override
13997            public void run() {
13998                for (int i = 0; i < mRunningInstalls.size(); i++) {
13999                    final PostInstallData data = mRunningInstalls.valueAt(i);
14000                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14001                        continue;
14002                    }
14003                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14004                        // right package; but is it for the right user?
14005                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14006                            if (userId == data.res.newUsers[uIndex]) {
14007                                if (DEBUG_BACKUP) {
14008                                    Slog.i(TAG, "Package " + pkgName
14009                                            + " being restored so deferring FIRST_LAUNCH");
14010                                }
14011                                return;
14012                            }
14013                        }
14014                    }
14015                }
14016                // didn't find it, so not being restored
14017                if (DEBUG_BACKUP) {
14018                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14019                }
14020                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14021            }
14022        });
14023    }
14024
14025    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14026        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14027                installerPkg, null, userIds);
14028    }
14029
14030    private abstract class HandlerParams {
14031        private static final int MAX_RETRIES = 4;
14032
14033        /**
14034         * Number of times startCopy() has been attempted and had a non-fatal
14035         * error.
14036         */
14037        private int mRetries = 0;
14038
14039        /** User handle for the user requesting the information or installation. */
14040        private final UserHandle mUser;
14041        String traceMethod;
14042        int traceCookie;
14043
14044        HandlerParams(UserHandle user) {
14045            mUser = user;
14046        }
14047
14048        UserHandle getUser() {
14049            return mUser;
14050        }
14051
14052        HandlerParams setTraceMethod(String traceMethod) {
14053            this.traceMethod = traceMethod;
14054            return this;
14055        }
14056
14057        HandlerParams setTraceCookie(int traceCookie) {
14058            this.traceCookie = traceCookie;
14059            return this;
14060        }
14061
14062        final boolean startCopy() {
14063            boolean res;
14064            try {
14065                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14066
14067                if (++mRetries > MAX_RETRIES) {
14068                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14069                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14070                    handleServiceError();
14071                    return false;
14072                } else {
14073                    handleStartCopy();
14074                    res = true;
14075                }
14076            } catch (RemoteException e) {
14077                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14078                mHandler.sendEmptyMessage(MCS_RECONNECT);
14079                res = false;
14080            }
14081            handleReturnCode();
14082            return res;
14083        }
14084
14085        final void serviceError() {
14086            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14087            handleServiceError();
14088            handleReturnCode();
14089        }
14090
14091        abstract void handleStartCopy() throws RemoteException;
14092        abstract void handleServiceError();
14093        abstract void handleReturnCode();
14094    }
14095
14096    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14097        for (File path : paths) {
14098            try {
14099                mcs.clearDirectory(path.getAbsolutePath());
14100            } catch (RemoteException e) {
14101            }
14102        }
14103    }
14104
14105    static class OriginInfo {
14106        /**
14107         * Location where install is coming from, before it has been
14108         * copied/renamed into place. This could be a single monolithic APK
14109         * file, or a cluster directory. This location may be untrusted.
14110         */
14111        final File file;
14112
14113        /**
14114         * Flag indicating that {@link #file} or {@link #cid} has already been
14115         * staged, meaning downstream users don't need to defensively copy the
14116         * contents.
14117         */
14118        final boolean staged;
14119
14120        /**
14121         * Flag indicating that {@link #file} or {@link #cid} is an already
14122         * installed app that is being moved.
14123         */
14124        final boolean existing;
14125
14126        final String resolvedPath;
14127        final File resolvedFile;
14128
14129        static OriginInfo fromNothing() {
14130            return new OriginInfo(null, false, false);
14131        }
14132
14133        static OriginInfo fromUntrustedFile(File file) {
14134            return new OriginInfo(file, false, false);
14135        }
14136
14137        static OriginInfo fromExistingFile(File file) {
14138            return new OriginInfo(file, false, true);
14139        }
14140
14141        static OriginInfo fromStagedFile(File file) {
14142            return new OriginInfo(file, true, false);
14143        }
14144
14145        private OriginInfo(File file, boolean staged, boolean existing) {
14146            this.file = file;
14147            this.staged = staged;
14148            this.existing = existing;
14149
14150            if (file != null) {
14151                resolvedPath = file.getAbsolutePath();
14152                resolvedFile = file;
14153            } else {
14154                resolvedPath = null;
14155                resolvedFile = null;
14156            }
14157        }
14158    }
14159
14160    static class MoveInfo {
14161        final int moveId;
14162        final String fromUuid;
14163        final String toUuid;
14164        final String packageName;
14165        final String dataAppName;
14166        final int appId;
14167        final String seinfo;
14168        final int targetSdkVersion;
14169
14170        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14171                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14172            this.moveId = moveId;
14173            this.fromUuid = fromUuid;
14174            this.toUuid = toUuid;
14175            this.packageName = packageName;
14176            this.dataAppName = dataAppName;
14177            this.appId = appId;
14178            this.seinfo = seinfo;
14179            this.targetSdkVersion = targetSdkVersion;
14180        }
14181    }
14182
14183    static class VerificationInfo {
14184        /** A constant used to indicate that a uid value is not present. */
14185        public static final int NO_UID = -1;
14186
14187        /** URI referencing where the package was downloaded from. */
14188        final Uri originatingUri;
14189
14190        /** HTTP referrer URI associated with the originatingURI. */
14191        final Uri referrer;
14192
14193        /** UID of the application that the install request originated from. */
14194        final int originatingUid;
14195
14196        /** UID of application requesting the install */
14197        final int installerUid;
14198
14199        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14200            this.originatingUri = originatingUri;
14201            this.referrer = referrer;
14202            this.originatingUid = originatingUid;
14203            this.installerUid = installerUid;
14204        }
14205    }
14206
14207    class InstallParams extends HandlerParams {
14208        final OriginInfo origin;
14209        final MoveInfo move;
14210        final IPackageInstallObserver2 observer;
14211        int installFlags;
14212        final String installerPackageName;
14213        final String volumeUuid;
14214        private InstallArgs mArgs;
14215        private int mRet;
14216        final String packageAbiOverride;
14217        final String[] grantedRuntimePermissions;
14218        final VerificationInfo verificationInfo;
14219        final Certificate[][] certificates;
14220        final int installReason;
14221
14222        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14223                int installFlags, String installerPackageName, String volumeUuid,
14224                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14225                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14226            super(user);
14227            this.origin = origin;
14228            this.move = move;
14229            this.observer = observer;
14230            this.installFlags = installFlags;
14231            this.installerPackageName = installerPackageName;
14232            this.volumeUuid = volumeUuid;
14233            this.verificationInfo = verificationInfo;
14234            this.packageAbiOverride = packageAbiOverride;
14235            this.grantedRuntimePermissions = grantedPermissions;
14236            this.certificates = certificates;
14237            this.installReason = installReason;
14238        }
14239
14240        @Override
14241        public String toString() {
14242            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14243                    + " file=" + origin.file + "}";
14244        }
14245
14246        private int installLocationPolicy(PackageInfoLite pkgLite) {
14247            String packageName = pkgLite.packageName;
14248            int installLocation = pkgLite.installLocation;
14249            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14250            // reader
14251            synchronized (mPackages) {
14252                // Currently installed package which the new package is attempting to replace or
14253                // null if no such package is installed.
14254                PackageParser.Package installedPkg = mPackages.get(packageName);
14255                // Package which currently owns the data which the new package will own if installed.
14256                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14257                // will be null whereas dataOwnerPkg will contain information about the package
14258                // which was uninstalled while keeping its data.
14259                PackageParser.Package dataOwnerPkg = installedPkg;
14260                if (dataOwnerPkg  == null) {
14261                    PackageSetting ps = mSettings.mPackages.get(packageName);
14262                    if (ps != null) {
14263                        dataOwnerPkg = ps.pkg;
14264                    }
14265                }
14266
14267                if (dataOwnerPkg != null) {
14268                    // If installed, the package will get access to data left on the device by its
14269                    // predecessor. As a security measure, this is permited only if this is not a
14270                    // version downgrade or if the predecessor package is marked as debuggable and
14271                    // a downgrade is explicitly requested.
14272                    //
14273                    // On debuggable platform builds, downgrades are permitted even for
14274                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14275                    // not offer security guarantees and thus it's OK to disable some security
14276                    // mechanisms to make debugging/testing easier on those builds. However, even on
14277                    // debuggable builds downgrades of packages are permitted only if requested via
14278                    // installFlags. This is because we aim to keep the behavior of debuggable
14279                    // platform builds as close as possible to the behavior of non-debuggable
14280                    // platform builds.
14281                    final boolean downgradeRequested =
14282                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14283                    final boolean packageDebuggable =
14284                                (dataOwnerPkg.applicationInfo.flags
14285                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14286                    final boolean downgradePermitted =
14287                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14288                    if (!downgradePermitted) {
14289                        try {
14290                            checkDowngrade(dataOwnerPkg, pkgLite);
14291                        } catch (PackageManagerException e) {
14292                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14293                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14294                        }
14295                    }
14296                }
14297
14298                if (installedPkg != null) {
14299                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14300                        // Check for updated system application.
14301                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14302                            if (onSd) {
14303                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14304                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14305                            }
14306                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14307                        } else {
14308                            if (onSd) {
14309                                // Install flag overrides everything.
14310                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14311                            }
14312                            // If current upgrade specifies particular preference
14313                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14314                                // Application explicitly specified internal.
14315                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14316                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14317                                // App explictly prefers external. Let policy decide
14318                            } else {
14319                                // Prefer previous location
14320                                if (isExternal(installedPkg)) {
14321                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14322                                }
14323                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14324                            }
14325                        }
14326                    } else {
14327                        // Invalid install. Return error code
14328                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14329                    }
14330                }
14331            }
14332            // All the special cases have been taken care of.
14333            // Return result based on recommended install location.
14334            if (onSd) {
14335                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14336            }
14337            return pkgLite.recommendedInstallLocation;
14338        }
14339
14340        /*
14341         * Invoke remote method to get package information and install
14342         * location values. Override install location based on default
14343         * policy if needed and then create install arguments based
14344         * on the install location.
14345         */
14346        public void handleStartCopy() throws RemoteException {
14347            int ret = PackageManager.INSTALL_SUCCEEDED;
14348
14349            // If we're already staged, we've firmly committed to an install location
14350            if (origin.staged) {
14351                if (origin.file != null) {
14352                    installFlags |= PackageManager.INSTALL_INTERNAL;
14353                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14354                } else {
14355                    throw new IllegalStateException("Invalid stage location");
14356                }
14357            }
14358
14359            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14360            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14361            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14362            PackageInfoLite pkgLite = null;
14363
14364            if (onInt && onSd) {
14365                // Check if both bits are set.
14366                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14367                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14368            } else if (onSd && ephemeral) {
14369                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14370                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14371            } else {
14372                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14373                        packageAbiOverride);
14374
14375                if (DEBUG_EPHEMERAL && ephemeral) {
14376                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14377                }
14378
14379                /*
14380                 * If we have too little free space, try to free cache
14381                 * before giving up.
14382                 */
14383                if (!origin.staged && pkgLite.recommendedInstallLocation
14384                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14385                    // TODO: focus freeing disk space on the target device
14386                    final StorageManager storage = StorageManager.from(mContext);
14387                    final long lowThreshold = storage.getStorageLowBytes(
14388                            Environment.getDataDirectory());
14389
14390                    final long sizeBytes = mContainerService.calculateInstalledSize(
14391                            origin.resolvedPath, packageAbiOverride);
14392
14393                    try {
14394                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14395                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14396                                installFlags, packageAbiOverride);
14397                    } catch (InstallerException e) {
14398                        Slog.w(TAG, "Failed to free cache", e);
14399                    }
14400
14401                    /*
14402                     * The cache free must have deleted the file we
14403                     * downloaded to install.
14404                     *
14405                     * TODO: fix the "freeCache" call to not delete
14406                     *       the file we care about.
14407                     */
14408                    if (pkgLite.recommendedInstallLocation
14409                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14410                        pkgLite.recommendedInstallLocation
14411                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14412                    }
14413                }
14414            }
14415
14416            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14417                int loc = pkgLite.recommendedInstallLocation;
14418                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14419                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14420                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14421                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14422                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14423                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14424                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14425                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14426                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14427                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14428                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14429                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14430                } else {
14431                    // Override with defaults if needed.
14432                    loc = installLocationPolicy(pkgLite);
14433                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14434                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14435                    } else if (!onSd && !onInt) {
14436                        // Override install location with flags
14437                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14438                            // Set the flag to install on external media.
14439                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14440                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14441                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14442                            if (DEBUG_EPHEMERAL) {
14443                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14444                            }
14445                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14446                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14447                                    |PackageManager.INSTALL_INTERNAL);
14448                        } else {
14449                            // Make sure the flag for installing on external
14450                            // media is unset
14451                            installFlags |= PackageManager.INSTALL_INTERNAL;
14452                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14453                        }
14454                    }
14455                }
14456            }
14457
14458            final InstallArgs args = createInstallArgs(this);
14459            mArgs = args;
14460
14461            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14462                // TODO: http://b/22976637
14463                // Apps installed for "all" users use the device owner to verify the app
14464                UserHandle verifierUser = getUser();
14465                if (verifierUser == UserHandle.ALL) {
14466                    verifierUser = UserHandle.SYSTEM;
14467                }
14468
14469                /*
14470                 * Determine if we have any installed package verifiers. If we
14471                 * do, then we'll defer to them to verify the packages.
14472                 */
14473                final int requiredUid = mRequiredVerifierPackage == null ? -1
14474                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14475                                verifierUser.getIdentifier());
14476                final int installerUid =
14477                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14478                if (!origin.existing && requiredUid != -1
14479                        && isVerificationEnabled(
14480                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14481                    final Intent verification = new Intent(
14482                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14483                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14484                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14485                            PACKAGE_MIME_TYPE);
14486                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14487
14488                    // Query all live verifiers based on current user state
14489                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14490                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14491                            false /*allowDynamicSplits*/);
14492
14493                    if (DEBUG_VERIFY) {
14494                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14495                                + verification.toString() + " with " + pkgLite.verifiers.length
14496                                + " optional verifiers");
14497                    }
14498
14499                    final int verificationId = mPendingVerificationToken++;
14500
14501                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14502
14503                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14504                            installerPackageName);
14505
14506                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14507                            installFlags);
14508
14509                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14510                            pkgLite.packageName);
14511
14512                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14513                            pkgLite.versionCode);
14514
14515                    if (verificationInfo != null) {
14516                        if (verificationInfo.originatingUri != null) {
14517                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14518                                    verificationInfo.originatingUri);
14519                        }
14520                        if (verificationInfo.referrer != null) {
14521                            verification.putExtra(Intent.EXTRA_REFERRER,
14522                                    verificationInfo.referrer);
14523                        }
14524                        if (verificationInfo.originatingUid >= 0) {
14525                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14526                                    verificationInfo.originatingUid);
14527                        }
14528                        if (verificationInfo.installerUid >= 0) {
14529                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14530                                    verificationInfo.installerUid);
14531                        }
14532                    }
14533
14534                    final PackageVerificationState verificationState = new PackageVerificationState(
14535                            requiredUid, args);
14536
14537                    mPendingVerification.append(verificationId, verificationState);
14538
14539                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14540                            receivers, verificationState);
14541
14542                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14543                    final long idleDuration = getVerificationTimeout();
14544
14545                    /*
14546                     * If any sufficient verifiers were listed in the package
14547                     * manifest, attempt to ask them.
14548                     */
14549                    if (sufficientVerifiers != null) {
14550                        final int N = sufficientVerifiers.size();
14551                        if (N == 0) {
14552                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14553                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14554                        } else {
14555                            for (int i = 0; i < N; i++) {
14556                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14557                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14558                                        verifierComponent.getPackageName(), idleDuration,
14559                                        verifierUser.getIdentifier(), false, "package verifier");
14560
14561                                final Intent sufficientIntent = new Intent(verification);
14562                                sufficientIntent.setComponent(verifierComponent);
14563                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14564                            }
14565                        }
14566                    }
14567
14568                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14569                            mRequiredVerifierPackage, receivers);
14570                    if (ret == PackageManager.INSTALL_SUCCEEDED
14571                            && mRequiredVerifierPackage != null) {
14572                        Trace.asyncTraceBegin(
14573                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14574                        /*
14575                         * Send the intent to the required verification agent,
14576                         * but only start the verification timeout after the
14577                         * target BroadcastReceivers have run.
14578                         */
14579                        verification.setComponent(requiredVerifierComponent);
14580                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14581                                mRequiredVerifierPackage, idleDuration,
14582                                verifierUser.getIdentifier(), false, "package verifier");
14583                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14584                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14585                                new BroadcastReceiver() {
14586                                    @Override
14587                                    public void onReceive(Context context, Intent intent) {
14588                                        final Message msg = mHandler
14589                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14590                                        msg.arg1 = verificationId;
14591                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14592                                    }
14593                                }, null, 0, null, null);
14594
14595                        /*
14596                         * We don't want the copy to proceed until verification
14597                         * succeeds, so null out this field.
14598                         */
14599                        mArgs = null;
14600                    }
14601                } else {
14602                    /*
14603                     * No package verification is enabled, so immediately start
14604                     * the remote call to initiate copy using temporary file.
14605                     */
14606                    ret = args.copyApk(mContainerService, true);
14607                }
14608            }
14609
14610            mRet = ret;
14611        }
14612
14613        @Override
14614        void handleReturnCode() {
14615            // If mArgs is null, then MCS couldn't be reached. When it
14616            // reconnects, it will try again to install. At that point, this
14617            // will succeed.
14618            if (mArgs != null) {
14619                processPendingInstall(mArgs, mRet);
14620            }
14621        }
14622
14623        @Override
14624        void handleServiceError() {
14625            mArgs = createInstallArgs(this);
14626            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14627        }
14628    }
14629
14630    private InstallArgs createInstallArgs(InstallParams params) {
14631        if (params.move != null) {
14632            return new MoveInstallArgs(params);
14633        } else {
14634            return new FileInstallArgs(params);
14635        }
14636    }
14637
14638    /**
14639     * Create args that describe an existing installed package. Typically used
14640     * when cleaning up old installs, or used as a move source.
14641     */
14642    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14643            String resourcePath, String[] instructionSets) {
14644        return new FileInstallArgs(codePath, resourcePath, instructionSets);
14645    }
14646
14647    static abstract class InstallArgs {
14648        /** @see InstallParams#origin */
14649        final OriginInfo origin;
14650        /** @see InstallParams#move */
14651        final MoveInfo move;
14652
14653        final IPackageInstallObserver2 observer;
14654        // Always refers to PackageManager flags only
14655        final int installFlags;
14656        final String installerPackageName;
14657        final String volumeUuid;
14658        final UserHandle user;
14659        final String abiOverride;
14660        final String[] installGrantPermissions;
14661        /** If non-null, drop an async trace when the install completes */
14662        final String traceMethod;
14663        final int traceCookie;
14664        final Certificate[][] certificates;
14665        final int installReason;
14666
14667        // The list of instruction sets supported by this app. This is currently
14668        // only used during the rmdex() phase to clean up resources. We can get rid of this
14669        // if we move dex files under the common app path.
14670        /* nullable */ String[] instructionSets;
14671
14672        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14673                int installFlags, String installerPackageName, String volumeUuid,
14674                UserHandle user, String[] instructionSets,
14675                String abiOverride, String[] installGrantPermissions,
14676                String traceMethod, int traceCookie, Certificate[][] certificates,
14677                int installReason) {
14678            this.origin = origin;
14679            this.move = move;
14680            this.installFlags = installFlags;
14681            this.observer = observer;
14682            this.installerPackageName = installerPackageName;
14683            this.volumeUuid = volumeUuid;
14684            this.user = user;
14685            this.instructionSets = instructionSets;
14686            this.abiOverride = abiOverride;
14687            this.installGrantPermissions = installGrantPermissions;
14688            this.traceMethod = traceMethod;
14689            this.traceCookie = traceCookie;
14690            this.certificates = certificates;
14691            this.installReason = installReason;
14692        }
14693
14694        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14695        abstract int doPreInstall(int status);
14696
14697        /**
14698         * Rename package into final resting place. All paths on the given
14699         * scanned package should be updated to reflect the rename.
14700         */
14701        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14702        abstract int doPostInstall(int status, int uid);
14703
14704        /** @see PackageSettingBase#codePathString */
14705        abstract String getCodePath();
14706        /** @see PackageSettingBase#resourcePathString */
14707        abstract String getResourcePath();
14708
14709        // Need installer lock especially for dex file removal.
14710        abstract void cleanUpResourcesLI();
14711        abstract boolean doPostDeleteLI(boolean delete);
14712
14713        /**
14714         * Called before the source arguments are copied. This is used mostly
14715         * for MoveParams when it needs to read the source file to put it in the
14716         * destination.
14717         */
14718        int doPreCopy() {
14719            return PackageManager.INSTALL_SUCCEEDED;
14720        }
14721
14722        /**
14723         * Called after the source arguments are copied. This is used mostly for
14724         * MoveParams when it needs to read the source file to put it in the
14725         * destination.
14726         */
14727        int doPostCopy(int uid) {
14728            return PackageManager.INSTALL_SUCCEEDED;
14729        }
14730
14731        protected boolean isFwdLocked() {
14732            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14733        }
14734
14735        protected boolean isExternalAsec() {
14736            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14737        }
14738
14739        protected boolean isEphemeral() {
14740            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14741        }
14742
14743        UserHandle getUser() {
14744            return user;
14745        }
14746    }
14747
14748    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14749        if (!allCodePaths.isEmpty()) {
14750            if (instructionSets == null) {
14751                throw new IllegalStateException("instructionSet == null");
14752            }
14753            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14754            for (String codePath : allCodePaths) {
14755                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14756                    try {
14757                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14758                    } catch (InstallerException ignored) {
14759                    }
14760                }
14761            }
14762        }
14763    }
14764
14765    /**
14766     * Logic to handle installation of non-ASEC applications, including copying
14767     * and renaming logic.
14768     */
14769    class FileInstallArgs extends InstallArgs {
14770        private File codeFile;
14771        private File resourceFile;
14772
14773        // Example topology:
14774        // /data/app/com.example/base.apk
14775        // /data/app/com.example/split_foo.apk
14776        // /data/app/com.example/lib/arm/libfoo.so
14777        // /data/app/com.example/lib/arm64/libfoo.so
14778        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14779
14780        /** New install */
14781        FileInstallArgs(InstallParams params) {
14782            super(params.origin, params.move, params.observer, params.installFlags,
14783                    params.installerPackageName, params.volumeUuid,
14784                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14785                    params.grantedRuntimePermissions,
14786                    params.traceMethod, params.traceCookie, params.certificates,
14787                    params.installReason);
14788            if (isFwdLocked()) {
14789                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14790            }
14791        }
14792
14793        /** Existing install */
14794        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14795            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14796                    null, null, null, 0, null /*certificates*/,
14797                    PackageManager.INSTALL_REASON_UNKNOWN);
14798            this.codeFile = (codePath != null) ? new File(codePath) : null;
14799            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14800        }
14801
14802        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14803            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14804            try {
14805                return doCopyApk(imcs, temp);
14806            } finally {
14807                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14808            }
14809        }
14810
14811        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14812            if (origin.staged) {
14813                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14814                codeFile = origin.file;
14815                resourceFile = origin.file;
14816                return PackageManager.INSTALL_SUCCEEDED;
14817            }
14818
14819            try {
14820                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14821                final File tempDir =
14822                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14823                codeFile = tempDir;
14824                resourceFile = tempDir;
14825            } catch (IOException e) {
14826                Slog.w(TAG, "Failed to create copy file: " + e);
14827                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14828            }
14829
14830            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14831                @Override
14832                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14833                    if (!FileUtils.isValidExtFilename(name)) {
14834                        throw new IllegalArgumentException("Invalid filename: " + name);
14835                    }
14836                    try {
14837                        final File file = new File(codeFile, name);
14838                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14839                                O_RDWR | O_CREAT, 0644);
14840                        Os.chmod(file.getAbsolutePath(), 0644);
14841                        return new ParcelFileDescriptor(fd);
14842                    } catch (ErrnoException e) {
14843                        throw new RemoteException("Failed to open: " + e.getMessage());
14844                    }
14845                }
14846            };
14847
14848            int ret = PackageManager.INSTALL_SUCCEEDED;
14849            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14850            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14851                Slog.e(TAG, "Failed to copy package");
14852                return ret;
14853            }
14854
14855            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14856            NativeLibraryHelper.Handle handle = null;
14857            try {
14858                handle = NativeLibraryHelper.Handle.create(codeFile);
14859                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14860                        abiOverride);
14861            } catch (IOException e) {
14862                Slog.e(TAG, "Copying native libraries failed", e);
14863                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14864            } finally {
14865                IoUtils.closeQuietly(handle);
14866            }
14867
14868            return ret;
14869        }
14870
14871        int doPreInstall(int status) {
14872            if (status != PackageManager.INSTALL_SUCCEEDED) {
14873                cleanUp();
14874            }
14875            return status;
14876        }
14877
14878        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14879            if (status != PackageManager.INSTALL_SUCCEEDED) {
14880                cleanUp();
14881                return false;
14882            }
14883
14884            final File targetDir = codeFile.getParentFile();
14885            final File beforeCodeFile = codeFile;
14886            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14887
14888            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14889            try {
14890                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14891            } catch (ErrnoException e) {
14892                Slog.w(TAG, "Failed to rename", e);
14893                return false;
14894            }
14895
14896            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14897                Slog.w(TAG, "Failed to restorecon");
14898                return false;
14899            }
14900
14901            // Reflect the rename internally
14902            codeFile = afterCodeFile;
14903            resourceFile = afterCodeFile;
14904
14905            // Reflect the rename in scanned details
14906            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14907            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14908                    afterCodeFile, pkg.baseCodePath));
14909            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14910                    afterCodeFile, pkg.splitCodePaths));
14911
14912            // Reflect the rename in app info
14913            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14914            pkg.setApplicationInfoCodePath(pkg.codePath);
14915            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14916            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14917            pkg.setApplicationInfoResourcePath(pkg.codePath);
14918            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14919            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14920
14921            return true;
14922        }
14923
14924        int doPostInstall(int status, int uid) {
14925            if (status != PackageManager.INSTALL_SUCCEEDED) {
14926                cleanUp();
14927            }
14928            return status;
14929        }
14930
14931        @Override
14932        String getCodePath() {
14933            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14934        }
14935
14936        @Override
14937        String getResourcePath() {
14938            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14939        }
14940
14941        private boolean cleanUp() {
14942            if (codeFile == null || !codeFile.exists()) {
14943                return false;
14944            }
14945
14946            removeCodePathLI(codeFile);
14947
14948            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14949                resourceFile.delete();
14950            }
14951
14952            return true;
14953        }
14954
14955        void cleanUpResourcesLI() {
14956            // Try enumerating all code paths before deleting
14957            List<String> allCodePaths = Collections.EMPTY_LIST;
14958            if (codeFile != null && codeFile.exists()) {
14959                try {
14960                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14961                    allCodePaths = pkg.getAllCodePaths();
14962                } catch (PackageParserException e) {
14963                    // Ignored; we tried our best
14964                }
14965            }
14966
14967            cleanUp();
14968            removeDexFiles(allCodePaths, instructionSets);
14969        }
14970
14971        boolean doPostDeleteLI(boolean delete) {
14972            // XXX err, shouldn't we respect the delete flag?
14973            cleanUpResourcesLI();
14974            return true;
14975        }
14976    }
14977
14978    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14979            PackageManagerException {
14980        if (copyRet < 0) {
14981            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14982                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14983                throw new PackageManagerException(copyRet, message);
14984            }
14985        }
14986    }
14987
14988    /**
14989     * Extract the StorageManagerService "container ID" from the full code path of an
14990     * .apk.
14991     */
14992    static String cidFromCodePath(String fullCodePath) {
14993        int eidx = fullCodePath.lastIndexOf("/");
14994        String subStr1 = fullCodePath.substring(0, eidx);
14995        int sidx = subStr1.lastIndexOf("/");
14996        return subStr1.substring(sidx+1, eidx);
14997    }
14998
14999    /**
15000     * Logic to handle movement of existing installed applications.
15001     */
15002    class MoveInstallArgs extends InstallArgs {
15003        private File codeFile;
15004        private File resourceFile;
15005
15006        /** New install */
15007        MoveInstallArgs(InstallParams params) {
15008            super(params.origin, params.move, params.observer, params.installFlags,
15009                    params.installerPackageName, params.volumeUuid,
15010                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15011                    params.grantedRuntimePermissions,
15012                    params.traceMethod, params.traceCookie, params.certificates,
15013                    params.installReason);
15014        }
15015
15016        int copyApk(IMediaContainerService imcs, boolean temp) {
15017            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15018                    + move.fromUuid + " to " + move.toUuid);
15019            synchronized (mInstaller) {
15020                try {
15021                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15022                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15023                } catch (InstallerException e) {
15024                    Slog.w(TAG, "Failed to move app", e);
15025                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15026                }
15027            }
15028
15029            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15030            resourceFile = codeFile;
15031            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15032
15033            return PackageManager.INSTALL_SUCCEEDED;
15034        }
15035
15036        int doPreInstall(int status) {
15037            if (status != PackageManager.INSTALL_SUCCEEDED) {
15038                cleanUp(move.toUuid);
15039            }
15040            return status;
15041        }
15042
15043        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15044            if (status != PackageManager.INSTALL_SUCCEEDED) {
15045                cleanUp(move.toUuid);
15046                return false;
15047            }
15048
15049            // Reflect the move in app info
15050            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15051            pkg.setApplicationInfoCodePath(pkg.codePath);
15052            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15053            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15054            pkg.setApplicationInfoResourcePath(pkg.codePath);
15055            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15056            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15057
15058            return true;
15059        }
15060
15061        int doPostInstall(int status, int uid) {
15062            if (status == PackageManager.INSTALL_SUCCEEDED) {
15063                cleanUp(move.fromUuid);
15064            } else {
15065                cleanUp(move.toUuid);
15066            }
15067            return status;
15068        }
15069
15070        @Override
15071        String getCodePath() {
15072            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15073        }
15074
15075        @Override
15076        String getResourcePath() {
15077            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15078        }
15079
15080        private boolean cleanUp(String volumeUuid) {
15081            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15082                    move.dataAppName);
15083            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15084            final int[] userIds = sUserManager.getUserIds();
15085            synchronized (mInstallLock) {
15086                // Clean up both app data and code
15087                // All package moves are frozen until finished
15088                for (int userId : userIds) {
15089                    try {
15090                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15091                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15092                    } catch (InstallerException e) {
15093                        Slog.w(TAG, String.valueOf(e));
15094                    }
15095                }
15096                removeCodePathLI(codeFile);
15097            }
15098            return true;
15099        }
15100
15101        void cleanUpResourcesLI() {
15102            throw new UnsupportedOperationException();
15103        }
15104
15105        boolean doPostDeleteLI(boolean delete) {
15106            throw new UnsupportedOperationException();
15107        }
15108    }
15109
15110    static String getAsecPackageName(String packageCid) {
15111        int idx = packageCid.lastIndexOf("-");
15112        if (idx == -1) {
15113            return packageCid;
15114        }
15115        return packageCid.substring(0, idx);
15116    }
15117
15118    // Utility method used to create code paths based on package name and available index.
15119    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15120        String idxStr = "";
15121        int idx = 1;
15122        // Fall back to default value of idx=1 if prefix is not
15123        // part of oldCodePath
15124        if (oldCodePath != null) {
15125            String subStr = oldCodePath;
15126            // Drop the suffix right away
15127            if (suffix != null && subStr.endsWith(suffix)) {
15128                subStr = subStr.substring(0, subStr.length() - suffix.length());
15129            }
15130            // If oldCodePath already contains prefix find out the
15131            // ending index to either increment or decrement.
15132            int sidx = subStr.lastIndexOf(prefix);
15133            if (sidx != -1) {
15134                subStr = subStr.substring(sidx + prefix.length());
15135                if (subStr != null) {
15136                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15137                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15138                    }
15139                    try {
15140                        idx = Integer.parseInt(subStr);
15141                        if (idx <= 1) {
15142                            idx++;
15143                        } else {
15144                            idx--;
15145                        }
15146                    } catch(NumberFormatException e) {
15147                    }
15148                }
15149            }
15150        }
15151        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15152        return prefix + idxStr;
15153    }
15154
15155    private File getNextCodePath(File targetDir, String packageName) {
15156        File result;
15157        SecureRandom random = new SecureRandom();
15158        byte[] bytes = new byte[16];
15159        do {
15160            random.nextBytes(bytes);
15161            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15162            result = new File(targetDir, packageName + "-" + suffix);
15163        } while (result.exists());
15164        return result;
15165    }
15166
15167    // Utility method that returns the relative package path with respect
15168    // to the installation directory. Like say for /data/data/com.test-1.apk
15169    // string com.test-1 is returned.
15170    static String deriveCodePathName(String codePath) {
15171        if (codePath == null) {
15172            return null;
15173        }
15174        final File codeFile = new File(codePath);
15175        final String name = codeFile.getName();
15176        if (codeFile.isDirectory()) {
15177            return name;
15178        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15179            final int lastDot = name.lastIndexOf('.');
15180            return name.substring(0, lastDot);
15181        } else {
15182            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15183            return null;
15184        }
15185    }
15186
15187    static class PackageInstalledInfo {
15188        String name;
15189        int uid;
15190        // The set of users that originally had this package installed.
15191        int[] origUsers;
15192        // The set of users that now have this package installed.
15193        int[] newUsers;
15194        PackageParser.Package pkg;
15195        int returnCode;
15196        String returnMsg;
15197        String installerPackageName;
15198        PackageRemovedInfo removedInfo;
15199        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15200
15201        public void setError(int code, String msg) {
15202            setReturnCode(code);
15203            setReturnMessage(msg);
15204            Slog.w(TAG, msg);
15205        }
15206
15207        public void setError(String msg, PackageParserException e) {
15208            setReturnCode(e.error);
15209            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15210            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15211            for (int i = 0; i < childCount; i++) {
15212                addedChildPackages.valueAt(i).setError(msg, e);
15213            }
15214            Slog.w(TAG, msg, e);
15215        }
15216
15217        public void setError(String msg, PackageManagerException e) {
15218            returnCode = e.error;
15219            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15220            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15221            for (int i = 0; i < childCount; i++) {
15222                addedChildPackages.valueAt(i).setError(msg, e);
15223            }
15224            Slog.w(TAG, msg, e);
15225        }
15226
15227        public void setReturnCode(int returnCode) {
15228            this.returnCode = returnCode;
15229            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15230            for (int i = 0; i < childCount; i++) {
15231                addedChildPackages.valueAt(i).returnCode = returnCode;
15232            }
15233        }
15234
15235        private void setReturnMessage(String returnMsg) {
15236            this.returnMsg = returnMsg;
15237            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15238            for (int i = 0; i < childCount; i++) {
15239                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15240            }
15241        }
15242
15243        // In some error cases we want to convey more info back to the observer
15244        String origPackage;
15245        String origPermission;
15246    }
15247
15248    /*
15249     * Install a non-existing package.
15250     */
15251    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15252            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15253            PackageInstalledInfo res, int installReason) {
15254        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15255
15256        // Remember this for later, in case we need to rollback this install
15257        String pkgName = pkg.packageName;
15258
15259        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15260
15261        synchronized(mPackages) {
15262            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15263            if (renamedPackage != null) {
15264                // A package with the same name is already installed, though
15265                // it has been renamed to an older name.  The package we
15266                // are trying to install should be installed as an update to
15267                // the existing one, but that has not been requested, so bail.
15268                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15269                        + " without first uninstalling package running as "
15270                        + renamedPackage);
15271                return;
15272            }
15273            if (mPackages.containsKey(pkgName)) {
15274                // Don't allow installation over an existing package with the same name.
15275                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15276                        + " without first uninstalling.");
15277                return;
15278            }
15279        }
15280
15281        try {
15282            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15283                    System.currentTimeMillis(), user);
15284
15285            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15286
15287            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15288                prepareAppDataAfterInstallLIF(newPackage);
15289
15290            } else {
15291                // Remove package from internal structures, but keep around any
15292                // data that might have already existed
15293                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15294                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15295            }
15296        } catch (PackageManagerException e) {
15297            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15298        }
15299
15300        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15301    }
15302
15303    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15304        try (DigestInputStream digestStream =
15305                new DigestInputStream(new FileInputStream(file), digest)) {
15306            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15307        }
15308    }
15309
15310    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15311            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15312            int installReason) {
15313        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15314
15315        final PackageParser.Package oldPackage;
15316        final PackageSetting ps;
15317        final String pkgName = pkg.packageName;
15318        final int[] allUsers;
15319        final int[] installedUsers;
15320
15321        synchronized(mPackages) {
15322            oldPackage = mPackages.get(pkgName);
15323            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15324
15325            // don't allow upgrade to target a release SDK from a pre-release SDK
15326            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15327                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15328            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15329                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15330            if (oldTargetsPreRelease
15331                    && !newTargetsPreRelease
15332                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15333                Slog.w(TAG, "Can't install package targeting released sdk");
15334                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15335                return;
15336            }
15337
15338            ps = mSettings.mPackages.get(pkgName);
15339
15340            // verify signatures are valid
15341            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15342            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15343                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15344                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15345                            "New package not signed by keys specified by upgrade-keysets: "
15346                                    + pkgName);
15347                    return;
15348                }
15349            } else {
15350                // default to original signature matching
15351                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15352                        != PackageManager.SIGNATURE_MATCH) {
15353                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15354                            "New package has a different signature: " + pkgName);
15355                    return;
15356                }
15357            }
15358
15359            // don't allow a system upgrade unless the upgrade hash matches
15360            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15361                byte[] digestBytes = null;
15362                try {
15363                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15364                    updateDigest(digest, new File(pkg.baseCodePath));
15365                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15366                        for (String path : pkg.splitCodePaths) {
15367                            updateDigest(digest, new File(path));
15368                        }
15369                    }
15370                    digestBytes = digest.digest();
15371                } catch (NoSuchAlgorithmException | IOException e) {
15372                    res.setError(INSTALL_FAILED_INVALID_APK,
15373                            "Could not compute hash: " + pkgName);
15374                    return;
15375                }
15376                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15377                    res.setError(INSTALL_FAILED_INVALID_APK,
15378                            "New package fails restrict-update check: " + pkgName);
15379                    return;
15380                }
15381                // retain upgrade restriction
15382                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15383            }
15384
15385            // Check for shared user id changes
15386            String invalidPackageName =
15387                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15388            if (invalidPackageName != null) {
15389                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15390                        "Package " + invalidPackageName + " tried to change user "
15391                                + oldPackage.mSharedUserId);
15392                return;
15393            }
15394
15395            // In case of rollback, remember per-user/profile install state
15396            allUsers = sUserManager.getUserIds();
15397            installedUsers = ps.queryInstalledUsers(allUsers, true);
15398
15399            // don't allow an upgrade from full to ephemeral
15400            if (isInstantApp) {
15401                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15402                    for (int currentUser : allUsers) {
15403                        if (!ps.getInstantApp(currentUser)) {
15404                            // can't downgrade from full to instant
15405                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15406                                    + " for user: " + currentUser);
15407                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15408                            return;
15409                        }
15410                    }
15411                } else if (!ps.getInstantApp(user.getIdentifier())) {
15412                    // can't downgrade from full to instant
15413                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15414                            + " for user: " + user.getIdentifier());
15415                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15416                    return;
15417                }
15418            }
15419        }
15420
15421        // Update what is removed
15422        res.removedInfo = new PackageRemovedInfo(this);
15423        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15424        res.removedInfo.removedPackage = oldPackage.packageName;
15425        res.removedInfo.installerPackageName = ps.installerPackageName;
15426        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15427        res.removedInfo.isUpdate = true;
15428        res.removedInfo.origUsers = installedUsers;
15429        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15430        for (int i = 0; i < installedUsers.length; i++) {
15431            final int userId = installedUsers[i];
15432            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15433        }
15434
15435        final int childCount = (oldPackage.childPackages != null)
15436                ? oldPackage.childPackages.size() : 0;
15437        for (int i = 0; i < childCount; i++) {
15438            boolean childPackageUpdated = false;
15439            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15440            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15441            if (res.addedChildPackages != null) {
15442                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15443                if (childRes != null) {
15444                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15445                    childRes.removedInfo.removedPackage = childPkg.packageName;
15446                    if (childPs != null) {
15447                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15448                    }
15449                    childRes.removedInfo.isUpdate = true;
15450                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15451                    childPackageUpdated = true;
15452                }
15453            }
15454            if (!childPackageUpdated) {
15455                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15456                childRemovedRes.removedPackage = childPkg.packageName;
15457                if (childPs != null) {
15458                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15459                }
15460                childRemovedRes.isUpdate = false;
15461                childRemovedRes.dataRemoved = true;
15462                synchronized (mPackages) {
15463                    if (childPs != null) {
15464                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15465                    }
15466                }
15467                if (res.removedInfo.removedChildPackages == null) {
15468                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15469                }
15470                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15471            }
15472        }
15473
15474        boolean sysPkg = (isSystemApp(oldPackage));
15475        if (sysPkg) {
15476            // Set the system/privileged/oem flags as needed
15477            final boolean privileged =
15478                    (oldPackage.applicationInfo.privateFlags
15479                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15480            final boolean oem =
15481                    (oldPackage.applicationInfo.privateFlags
15482                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15483            final int systemPolicyFlags = policyFlags
15484                    | PackageParser.PARSE_IS_SYSTEM
15485                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
15486                    | (oem ? PARSE_IS_OEM : 0);
15487
15488            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15489                    user, allUsers, installerPackageName, res, installReason);
15490        } else {
15491            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15492                    user, allUsers, installerPackageName, res, installReason);
15493        }
15494    }
15495
15496    @Override
15497    public List<String> getPreviousCodePaths(String packageName) {
15498        final int callingUid = Binder.getCallingUid();
15499        final List<String> result = new ArrayList<>();
15500        if (getInstantAppPackageName(callingUid) != null) {
15501            return result;
15502        }
15503        final PackageSetting ps = mSettings.mPackages.get(packageName);
15504        if (ps != null
15505                && ps.oldCodePaths != null
15506                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15507            result.addAll(ps.oldCodePaths);
15508        }
15509        return result;
15510    }
15511
15512    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15513            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15514            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15515            int installReason) {
15516        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15517                + deletedPackage);
15518
15519        String pkgName = deletedPackage.packageName;
15520        boolean deletedPkg = true;
15521        boolean addedPkg = false;
15522        boolean updatedSettings = false;
15523        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15524        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15525                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15526
15527        final long origUpdateTime = (pkg.mExtras != null)
15528                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15529
15530        // First delete the existing package while retaining the data directory
15531        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15532                res.removedInfo, true, pkg)) {
15533            // If the existing package wasn't successfully deleted
15534            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15535            deletedPkg = false;
15536        } else {
15537            // Successfully deleted the old package; proceed with replace.
15538
15539            // If deleted package lived in a container, give users a chance to
15540            // relinquish resources before killing.
15541            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15542                if (DEBUG_INSTALL) {
15543                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15544                }
15545                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15546                final ArrayList<String> pkgList = new ArrayList<String>(1);
15547                pkgList.add(deletedPackage.applicationInfo.packageName);
15548                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15549            }
15550
15551            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15552                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15553            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15554
15555            try {
15556                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15557                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15558                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15559                        installReason);
15560
15561                // Update the in-memory copy of the previous code paths.
15562                PackageSetting ps = mSettings.mPackages.get(pkgName);
15563                if (!killApp) {
15564                    if (ps.oldCodePaths == null) {
15565                        ps.oldCodePaths = new ArraySet<>();
15566                    }
15567                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15568                    if (deletedPackage.splitCodePaths != null) {
15569                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15570                    }
15571                } else {
15572                    ps.oldCodePaths = null;
15573                }
15574                if (ps.childPackageNames != null) {
15575                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15576                        final String childPkgName = ps.childPackageNames.get(i);
15577                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15578                        childPs.oldCodePaths = ps.oldCodePaths;
15579                    }
15580                }
15581                // set instant app status, but, only if it's explicitly specified
15582                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15583                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15584                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15585                prepareAppDataAfterInstallLIF(newPackage);
15586                addedPkg = true;
15587                mDexManager.notifyPackageUpdated(newPackage.packageName,
15588                        newPackage.baseCodePath, newPackage.splitCodePaths);
15589            } catch (PackageManagerException e) {
15590                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15591            }
15592        }
15593
15594        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15595            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15596
15597            // Revert all internal state mutations and added folders for the failed install
15598            if (addedPkg) {
15599                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15600                        res.removedInfo, true, null);
15601            }
15602
15603            // Restore the old package
15604            if (deletedPkg) {
15605                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15606                File restoreFile = new File(deletedPackage.codePath);
15607                // Parse old package
15608                boolean oldExternal = isExternal(deletedPackage);
15609                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15610                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15611                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15612                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15613                try {
15614                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15615                            null);
15616                } catch (PackageManagerException e) {
15617                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15618                            + e.getMessage());
15619                    return;
15620                }
15621
15622                synchronized (mPackages) {
15623                    // Ensure the installer package name up to date
15624                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15625
15626                    // Update permissions for restored package
15627                    mPermissionManager.updatePermissions(
15628                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15629                            mPermissionCallback);
15630
15631                    mSettings.writeLPr();
15632                }
15633
15634                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15635            }
15636        } else {
15637            synchronized (mPackages) {
15638                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15639                if (ps != null) {
15640                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15641                    if (res.removedInfo.removedChildPackages != null) {
15642                        final int childCount = res.removedInfo.removedChildPackages.size();
15643                        // Iterate in reverse as we may modify the collection
15644                        for (int i = childCount - 1; i >= 0; i--) {
15645                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15646                            if (res.addedChildPackages.containsKey(childPackageName)) {
15647                                res.removedInfo.removedChildPackages.removeAt(i);
15648                            } else {
15649                                PackageRemovedInfo childInfo = res.removedInfo
15650                                        .removedChildPackages.valueAt(i);
15651                                childInfo.removedForAllUsers = mPackages.get(
15652                                        childInfo.removedPackage) == null;
15653                            }
15654                        }
15655                    }
15656                }
15657            }
15658        }
15659    }
15660
15661    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15662            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15663            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15664            int installReason) {
15665        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15666                + ", old=" + deletedPackage);
15667
15668        final boolean disabledSystem;
15669
15670        // Remove existing system package
15671        removePackageLI(deletedPackage, true);
15672
15673        synchronized (mPackages) {
15674            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15675        }
15676        if (!disabledSystem) {
15677            // We didn't need to disable the .apk as a current system package,
15678            // which means we are replacing another update that is already
15679            // installed.  We need to make sure to delete the older one's .apk.
15680            res.removedInfo.args = createInstallArgsForExisting(0,
15681                    deletedPackage.applicationInfo.getCodePath(),
15682                    deletedPackage.applicationInfo.getResourcePath(),
15683                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15684        } else {
15685            res.removedInfo.args = null;
15686        }
15687
15688        // Successfully disabled the old package. Now proceed with re-installation
15689        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15690                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15691        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15692
15693        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15694        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15695                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15696
15697        PackageParser.Package newPackage = null;
15698        try {
15699            // Add the package to the internal data structures
15700            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15701
15702            // Set the update and install times
15703            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15704            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15705                    System.currentTimeMillis());
15706
15707            // Update the package dynamic state if succeeded
15708            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15709                // Now that the install succeeded make sure we remove data
15710                // directories for any child package the update removed.
15711                final int deletedChildCount = (deletedPackage.childPackages != null)
15712                        ? deletedPackage.childPackages.size() : 0;
15713                final int newChildCount = (newPackage.childPackages != null)
15714                        ? newPackage.childPackages.size() : 0;
15715                for (int i = 0; i < deletedChildCount; i++) {
15716                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15717                    boolean childPackageDeleted = true;
15718                    for (int j = 0; j < newChildCount; j++) {
15719                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15720                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15721                            childPackageDeleted = false;
15722                            break;
15723                        }
15724                    }
15725                    if (childPackageDeleted) {
15726                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15727                                deletedChildPkg.packageName);
15728                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15729                            PackageRemovedInfo removedChildRes = res.removedInfo
15730                                    .removedChildPackages.get(deletedChildPkg.packageName);
15731                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15732                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15733                        }
15734                    }
15735                }
15736
15737                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15738                        installReason);
15739                prepareAppDataAfterInstallLIF(newPackage);
15740
15741                mDexManager.notifyPackageUpdated(newPackage.packageName,
15742                            newPackage.baseCodePath, newPackage.splitCodePaths);
15743            }
15744        } catch (PackageManagerException e) {
15745            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15746            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15747        }
15748
15749        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15750            // Re installation failed. Restore old information
15751            // Remove new pkg information
15752            if (newPackage != null) {
15753                removeInstalledPackageLI(newPackage, true);
15754            }
15755            // Add back the old system package
15756            try {
15757                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15758            } catch (PackageManagerException e) {
15759                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15760            }
15761
15762            synchronized (mPackages) {
15763                if (disabledSystem) {
15764                    enableSystemPackageLPw(deletedPackage);
15765                }
15766
15767                // Ensure the installer package name up to date
15768                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15769
15770                // Update permissions for restored package
15771                mPermissionManager.updatePermissions(
15772                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15773                        mPermissionCallback);
15774
15775                mSettings.writeLPr();
15776            }
15777
15778            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15779                    + " after failed upgrade");
15780        }
15781    }
15782
15783    /**
15784     * Checks whether the parent or any of the child packages have a change shared
15785     * user. For a package to be a valid update the shred users of the parent and
15786     * the children should match. We may later support changing child shared users.
15787     * @param oldPkg The updated package.
15788     * @param newPkg The update package.
15789     * @return The shared user that change between the versions.
15790     */
15791    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15792            PackageParser.Package newPkg) {
15793        // Check parent shared user
15794        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15795            return newPkg.packageName;
15796        }
15797        // Check child shared users
15798        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15799        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15800        for (int i = 0; i < newChildCount; i++) {
15801            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15802            // If this child was present, did it have the same shared user?
15803            for (int j = 0; j < oldChildCount; j++) {
15804                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15805                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15806                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15807                    return newChildPkg.packageName;
15808                }
15809            }
15810        }
15811        return null;
15812    }
15813
15814    private void removeNativeBinariesLI(PackageSetting ps) {
15815        // Remove the lib path for the parent package
15816        if (ps != null) {
15817            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15818            // Remove the lib path for the child packages
15819            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15820            for (int i = 0; i < childCount; i++) {
15821                PackageSetting childPs = null;
15822                synchronized (mPackages) {
15823                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15824                }
15825                if (childPs != null) {
15826                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15827                            .legacyNativeLibraryPathString);
15828                }
15829            }
15830        }
15831    }
15832
15833    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15834        // Enable the parent package
15835        mSettings.enableSystemPackageLPw(pkg.packageName);
15836        // Enable the child packages
15837        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15838        for (int i = 0; i < childCount; i++) {
15839            PackageParser.Package childPkg = pkg.childPackages.get(i);
15840            mSettings.enableSystemPackageLPw(childPkg.packageName);
15841        }
15842    }
15843
15844    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15845            PackageParser.Package newPkg) {
15846        // Disable the parent package (parent always replaced)
15847        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15848        // Disable the child packages
15849        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15850        for (int i = 0; i < childCount; i++) {
15851            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15852            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15853            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15854        }
15855        return disabled;
15856    }
15857
15858    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15859            String installerPackageName) {
15860        // Enable the parent package
15861        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15862        // Enable the child packages
15863        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15864        for (int i = 0; i < childCount; i++) {
15865            PackageParser.Package childPkg = pkg.childPackages.get(i);
15866            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15867        }
15868    }
15869
15870    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15871            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15872        // Update the parent package setting
15873        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15874                res, user, installReason);
15875        // Update the child packages setting
15876        final int childCount = (newPackage.childPackages != null)
15877                ? newPackage.childPackages.size() : 0;
15878        for (int i = 0; i < childCount; i++) {
15879            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15880            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15881            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15882                    childRes.origUsers, childRes, user, installReason);
15883        }
15884    }
15885
15886    private void updateSettingsInternalLI(PackageParser.Package pkg,
15887            String installerPackageName, int[] allUsers, int[] installedForUsers,
15888            PackageInstalledInfo res, UserHandle user, int installReason) {
15889        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15890
15891        String pkgName = pkg.packageName;
15892        synchronized (mPackages) {
15893            //write settings. the installStatus will be incomplete at this stage.
15894            //note that the new package setting would have already been
15895            //added to mPackages. It hasn't been persisted yet.
15896            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15897            // TODO: Remove this write? It's also written at the end of this method
15898            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15899            mSettings.writeLPr();
15900            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15901        }
15902
15903        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
15904        synchronized (mPackages) {
15905// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
15906            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
15907                    mPermissionCallback);
15908            // For system-bundled packages, we assume that installing an upgraded version
15909            // of the package implies that the user actually wants to run that new code,
15910            // so we enable the package.
15911            PackageSetting ps = mSettings.mPackages.get(pkgName);
15912            final int userId = user.getIdentifier();
15913            if (ps != null) {
15914                if (isSystemApp(pkg)) {
15915                    if (DEBUG_INSTALL) {
15916                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15917                    }
15918                    // Enable system package for requested users
15919                    if (res.origUsers != null) {
15920                        for (int origUserId : res.origUsers) {
15921                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15922                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15923                                        origUserId, installerPackageName);
15924                            }
15925                        }
15926                    }
15927                    // Also convey the prior install/uninstall state
15928                    if (allUsers != null && installedForUsers != null) {
15929                        for (int currentUserId : allUsers) {
15930                            final boolean installed = ArrayUtils.contains(
15931                                    installedForUsers, currentUserId);
15932                            if (DEBUG_INSTALL) {
15933                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15934                            }
15935                            ps.setInstalled(installed, currentUserId);
15936                        }
15937                        // these install state changes will be persisted in the
15938                        // upcoming call to mSettings.writeLPr().
15939                    }
15940                }
15941                // It's implied that when a user requests installation, they want the app to be
15942                // installed and enabled.
15943                if (userId != UserHandle.USER_ALL) {
15944                    ps.setInstalled(true, userId);
15945                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15946                }
15947
15948                // When replacing an existing package, preserve the original install reason for all
15949                // users that had the package installed before.
15950                final Set<Integer> previousUserIds = new ArraySet<>();
15951                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15952                    final int installReasonCount = res.removedInfo.installReasons.size();
15953                    for (int i = 0; i < installReasonCount; i++) {
15954                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15955                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15956                        ps.setInstallReason(previousInstallReason, previousUserId);
15957                        previousUserIds.add(previousUserId);
15958                    }
15959                }
15960
15961                // Set install reason for users that are having the package newly installed.
15962                if (userId == UserHandle.USER_ALL) {
15963                    for (int currentUserId : sUserManager.getUserIds()) {
15964                        if (!previousUserIds.contains(currentUserId)) {
15965                            ps.setInstallReason(installReason, currentUserId);
15966                        }
15967                    }
15968                } else if (!previousUserIds.contains(userId)) {
15969                    ps.setInstallReason(installReason, userId);
15970                }
15971                mSettings.writeKernelMappingLPr(ps);
15972            }
15973            res.name = pkgName;
15974            res.uid = pkg.applicationInfo.uid;
15975            res.pkg = pkg;
15976            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15977            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15978            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15979            //to update install status
15980            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15981            mSettings.writeLPr();
15982            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15983        }
15984
15985        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15986    }
15987
15988    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15989        try {
15990            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15991            installPackageLI(args, res);
15992        } finally {
15993            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15994        }
15995    }
15996
15997    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15998        final int installFlags = args.installFlags;
15999        final String installerPackageName = args.installerPackageName;
16000        final String volumeUuid = args.volumeUuid;
16001        final File tmpPackageFile = new File(args.getCodePath());
16002        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16003        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16004                || (args.volumeUuid != null));
16005        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16006        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16007        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16008        final boolean virtualPreload =
16009                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16010        boolean replace = false;
16011        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16012        if (args.move != null) {
16013            // moving a complete application; perform an initial scan on the new install location
16014            scanFlags |= SCAN_INITIAL;
16015        }
16016        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16017            scanFlags |= SCAN_DONT_KILL_APP;
16018        }
16019        if (instantApp) {
16020            scanFlags |= SCAN_AS_INSTANT_APP;
16021        }
16022        if (fullApp) {
16023            scanFlags |= SCAN_AS_FULL_APP;
16024        }
16025        if (virtualPreload) {
16026            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16027        }
16028
16029        // Result object to be returned
16030        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16031        res.installerPackageName = installerPackageName;
16032
16033        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16034
16035        // Sanity check
16036        if (instantApp && (forwardLocked || onExternal)) {
16037            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16038                    + " external=" + onExternal);
16039            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16040            return;
16041        }
16042
16043        // Retrieve PackageSettings and parse package
16044        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16045                | PackageParser.PARSE_ENFORCE_CODE
16046                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16047                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16048                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16049                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16050        PackageParser pp = new PackageParser();
16051        pp.setSeparateProcesses(mSeparateProcesses);
16052        pp.setDisplayMetrics(mMetrics);
16053        pp.setCallback(mPackageParserCallback);
16054
16055        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16056        final PackageParser.Package pkg;
16057        try {
16058            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16059        } catch (PackageParserException e) {
16060            res.setError("Failed parse during installPackageLI", e);
16061            return;
16062        } finally {
16063            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16064        }
16065
16066        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16067        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16068            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16069            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16070                    "Instant app package must target O");
16071            return;
16072        }
16073        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16074            Slog.w(TAG, "Instant app package " + pkg.packageName
16075                    + " does not target targetSandboxVersion 2");
16076            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16077                    "Instant app package must use targetSanboxVersion 2");
16078            return;
16079        }
16080
16081        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16082            // Static shared libraries have synthetic package names
16083            renameStaticSharedLibraryPackage(pkg);
16084
16085            // No static shared libs on external storage
16086            if (onExternal) {
16087                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16088                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16089                        "Packages declaring static-shared libs cannot be updated");
16090                return;
16091            }
16092        }
16093
16094        // If we are installing a clustered package add results for the children
16095        if (pkg.childPackages != null) {
16096            synchronized (mPackages) {
16097                final int childCount = pkg.childPackages.size();
16098                for (int i = 0; i < childCount; i++) {
16099                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16100                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16101                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16102                    childRes.pkg = childPkg;
16103                    childRes.name = childPkg.packageName;
16104                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16105                    if (childPs != null) {
16106                        childRes.origUsers = childPs.queryInstalledUsers(
16107                                sUserManager.getUserIds(), true);
16108                    }
16109                    if ((mPackages.containsKey(childPkg.packageName))) {
16110                        childRes.removedInfo = new PackageRemovedInfo(this);
16111                        childRes.removedInfo.removedPackage = childPkg.packageName;
16112                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16113                    }
16114                    if (res.addedChildPackages == null) {
16115                        res.addedChildPackages = new ArrayMap<>();
16116                    }
16117                    res.addedChildPackages.put(childPkg.packageName, childRes);
16118                }
16119            }
16120        }
16121
16122        // If package doesn't declare API override, mark that we have an install
16123        // time CPU ABI override.
16124        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16125            pkg.cpuAbiOverride = args.abiOverride;
16126        }
16127
16128        String pkgName = res.name = pkg.packageName;
16129        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16130            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16131                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16132                return;
16133            }
16134        }
16135
16136        try {
16137            // either use what we've been given or parse directly from the APK
16138            if (args.certificates != null) {
16139                try {
16140                    PackageParser.populateCertificates(pkg, args.certificates);
16141                } catch (PackageParserException e) {
16142                    // there was something wrong with the certificates we were given;
16143                    // try to pull them from the APK
16144                    PackageParser.collectCertificates(pkg, parseFlags);
16145                }
16146            } else {
16147                PackageParser.collectCertificates(pkg, parseFlags);
16148            }
16149        } catch (PackageParserException e) {
16150            res.setError("Failed collect during installPackageLI", e);
16151            return;
16152        }
16153
16154        // Get rid of all references to package scan path via parser.
16155        pp = null;
16156        String oldCodePath = null;
16157        boolean systemApp = false;
16158        synchronized (mPackages) {
16159            // Check if installing already existing package
16160            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16161                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16162                if (pkg.mOriginalPackages != null
16163                        && pkg.mOriginalPackages.contains(oldName)
16164                        && mPackages.containsKey(oldName)) {
16165                    // This package is derived from an original package,
16166                    // and this device has been updating from that original
16167                    // name.  We must continue using the original name, so
16168                    // rename the new package here.
16169                    pkg.setPackageName(oldName);
16170                    pkgName = pkg.packageName;
16171                    replace = true;
16172                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16173                            + oldName + " pkgName=" + pkgName);
16174                } else if (mPackages.containsKey(pkgName)) {
16175                    // This package, under its official name, already exists
16176                    // on the device; we should replace it.
16177                    replace = true;
16178                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16179                }
16180
16181                // Child packages are installed through the parent package
16182                if (pkg.parentPackage != null) {
16183                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16184                            "Package " + pkg.packageName + " is child of package "
16185                                    + pkg.parentPackage.parentPackage + ". Child packages "
16186                                    + "can be updated only through the parent package.");
16187                    return;
16188                }
16189
16190                if (replace) {
16191                    // Prevent apps opting out from runtime permissions
16192                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16193                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16194                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16195                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16196                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16197                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16198                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16199                                        + " doesn't support runtime permissions but the old"
16200                                        + " target SDK " + oldTargetSdk + " does.");
16201                        return;
16202                    }
16203                    // Prevent apps from downgrading their targetSandbox.
16204                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16205                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16206                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16207                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16208                                "Package " + pkg.packageName + " new target sandbox "
16209                                + newTargetSandbox + " is incompatible with the previous value of"
16210                                + oldTargetSandbox + ".");
16211                        return;
16212                    }
16213
16214                    // Prevent installing of child packages
16215                    if (oldPackage.parentPackage != null) {
16216                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16217                                "Package " + pkg.packageName + " is child of package "
16218                                        + oldPackage.parentPackage + ". Child packages "
16219                                        + "can be updated only through the parent package.");
16220                        return;
16221                    }
16222                }
16223            }
16224
16225            PackageSetting ps = mSettings.mPackages.get(pkgName);
16226            if (ps != null) {
16227                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16228
16229                // Static shared libs have same package with different versions where
16230                // we internally use a synthetic package name to allow multiple versions
16231                // of the same package, therefore we need to compare signatures against
16232                // the package setting for the latest library version.
16233                PackageSetting signatureCheckPs = ps;
16234                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16235                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16236                    if (libraryEntry != null) {
16237                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16238                    }
16239                }
16240
16241                // Quick sanity check that we're signed correctly if updating;
16242                // we'll check this again later when scanning, but we want to
16243                // bail early here before tripping over redefined permissions.
16244                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16245                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16246                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16247                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16248                                + pkg.packageName + " upgrade keys do not match the "
16249                                + "previously installed version");
16250                        return;
16251                    }
16252                } else {
16253                    try {
16254                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16255                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16256                        final boolean compatMatch = verifySignatures(
16257                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16258                        // The new KeySets will be re-added later in the scanning process.
16259                        if (compatMatch) {
16260                            synchronized (mPackages) {
16261                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16262                            }
16263                        }
16264                    } catch (PackageManagerException e) {
16265                        res.setError(e.error, e.getMessage());
16266                        return;
16267                    }
16268                }
16269
16270                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16271                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16272                    systemApp = (ps.pkg.applicationInfo.flags &
16273                            ApplicationInfo.FLAG_SYSTEM) != 0;
16274                }
16275                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16276            }
16277
16278            int N = pkg.permissions.size();
16279            for (int i = N-1; i >= 0; i--) {
16280                final PackageParser.Permission perm = pkg.permissions.get(i);
16281                final BasePermission bp =
16282                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16283
16284                // Don't allow anyone but the system to define ephemeral permissions.
16285                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16286                        && !systemApp) {
16287                    Slog.w(TAG, "Non-System package " + pkg.packageName
16288                            + " attempting to delcare ephemeral permission "
16289                            + perm.info.name + "; Removing ephemeral.");
16290                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16291                }
16292
16293                // Check whether the newly-scanned package wants to define an already-defined perm
16294                if (bp != null) {
16295                    // If the defining package is signed with our cert, it's okay.  This
16296                    // also includes the "updating the same package" case, of course.
16297                    // "updating same package" could also involve key-rotation.
16298                    final boolean sigsOk;
16299                    final String sourcePackageName = bp.getSourcePackageName();
16300                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16301                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16302                    if (sourcePackageName.equals(pkg.packageName)
16303                            && (ksms.shouldCheckUpgradeKeySetLocked(
16304                                    sourcePackageSetting, scanFlags))) {
16305                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16306                    } else {
16307                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16308                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16309                    }
16310                    if (!sigsOk) {
16311                        // If the owning package is the system itself, we log but allow
16312                        // install to proceed; we fail the install on all other permission
16313                        // redefinitions.
16314                        if (!sourcePackageName.equals("android")) {
16315                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16316                                    + pkg.packageName + " attempting to redeclare permission "
16317                                    + perm.info.name + " already owned by " + sourcePackageName);
16318                            res.origPermission = perm.info.name;
16319                            res.origPackage = sourcePackageName;
16320                            return;
16321                        } else {
16322                            Slog.w(TAG, "Package " + pkg.packageName
16323                                    + " attempting to redeclare system permission "
16324                                    + perm.info.name + "; ignoring new declaration");
16325                            pkg.permissions.remove(i);
16326                        }
16327                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16328                        // Prevent apps to change protection level to dangerous from any other
16329                        // type as this would allow a privilege escalation where an app adds a
16330                        // normal/signature permission in other app's group and later redefines
16331                        // it as dangerous leading to the group auto-grant.
16332                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16333                                == PermissionInfo.PROTECTION_DANGEROUS) {
16334                            if (bp != null && !bp.isRuntime()) {
16335                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16336                                        + "non-runtime permission " + perm.info.name
16337                                        + " to runtime; keeping old protection level");
16338                                perm.info.protectionLevel = bp.getProtectionLevel();
16339                            }
16340                        }
16341                    }
16342                }
16343            }
16344        }
16345
16346        if (systemApp) {
16347            if (onExternal) {
16348                // Abort update; system app can't be replaced with app on sdcard
16349                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16350                        "Cannot install updates to system apps on sdcard");
16351                return;
16352            } else if (instantApp) {
16353                // Abort update; system app can't be replaced with an instant app
16354                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16355                        "Cannot update a system app with an instant app");
16356                return;
16357            }
16358        }
16359
16360        if (args.move != null) {
16361            // We did an in-place move, so dex is ready to roll
16362            scanFlags |= SCAN_NO_DEX;
16363            scanFlags |= SCAN_MOVE;
16364
16365            synchronized (mPackages) {
16366                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16367                if (ps == null) {
16368                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16369                            "Missing settings for moved package " + pkgName);
16370                }
16371
16372                // We moved the entire application as-is, so bring over the
16373                // previously derived ABI information.
16374                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16375                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16376            }
16377
16378        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16379            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16380            scanFlags |= SCAN_NO_DEX;
16381
16382            try {
16383                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16384                    args.abiOverride : pkg.cpuAbiOverride);
16385                final boolean extractNativeLibs = !pkg.isLibrary();
16386                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16387                        extractNativeLibs, mAppLib32InstallDir);
16388            } catch (PackageManagerException pme) {
16389                Slog.e(TAG, "Error deriving application ABI", pme);
16390                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16391                return;
16392            }
16393
16394            // Shared libraries for the package need to be updated.
16395            synchronized (mPackages) {
16396                try {
16397                    updateSharedLibrariesLPr(pkg, null);
16398                } catch (PackageManagerException e) {
16399                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16400                }
16401            }
16402        }
16403
16404        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16405            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16406            return;
16407        }
16408
16409        // Verify if we need to dexopt the app.
16410        //
16411        // NOTE: it is *important* to call dexopt after doRename which will sync the
16412        // package data from PackageParser.Package and its corresponding ApplicationInfo.
16413        //
16414        // We only need to dexopt if the package meets ALL of the following conditions:
16415        //   1) it is not forward locked.
16416        //   2) it is not on on an external ASEC container.
16417        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16418        //
16419        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16420        // complete, so we skip this step during installation. Instead, we'll take extra time
16421        // the first time the instant app starts. It's preferred to do it this way to provide
16422        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16423        // middle of running an instant app. The default behaviour can be overridden
16424        // via gservices.
16425        final boolean performDexopt = !forwardLocked
16426            && !pkg.applicationInfo.isExternalAsec()
16427            && (!instantApp || Global.getInt(mContext.getContentResolver(),
16428                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16429
16430        if (performDexopt) {
16431            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16432            // Do not run PackageDexOptimizer through the local performDexOpt
16433            // method because `pkg` may not be in `mPackages` yet.
16434            //
16435            // Also, don't fail application installs if the dexopt step fails.
16436            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16437                REASON_INSTALL,
16438                DexoptOptions.DEXOPT_BOOT_COMPLETE);
16439            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16440                null /* instructionSets */,
16441                getOrCreateCompilerPackageStats(pkg),
16442                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16443                dexoptOptions);
16444            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16445        }
16446
16447        // Notify BackgroundDexOptService that the package has been changed.
16448        // If this is an update of a package which used to fail to compile,
16449        // BackgroundDexOptService will remove it from its blacklist.
16450        // TODO: Layering violation
16451        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16452
16453        if (!instantApp) {
16454            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16455        } else {
16456            if (DEBUG_DOMAIN_VERIFICATION) {
16457                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16458            }
16459        }
16460
16461        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16462                "installPackageLI")) {
16463            if (replace) {
16464                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16465                    // Static libs have a synthetic package name containing the version
16466                    // and cannot be updated as an update would get a new package name,
16467                    // unless this is the exact same version code which is useful for
16468                    // development.
16469                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16470                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16471                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16472                                + "static-shared libs cannot be updated");
16473                        return;
16474                    }
16475                }
16476                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16477                        installerPackageName, res, args.installReason);
16478            } else {
16479                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16480                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16481            }
16482        }
16483
16484        synchronized (mPackages) {
16485            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16486            if (ps != null) {
16487                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16488                ps.setUpdateAvailable(false /*updateAvailable*/);
16489            }
16490
16491            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16492            for (int i = 0; i < childCount; i++) {
16493                PackageParser.Package childPkg = pkg.childPackages.get(i);
16494                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16495                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16496                if (childPs != null) {
16497                    childRes.newUsers = childPs.queryInstalledUsers(
16498                            sUserManager.getUserIds(), true);
16499                }
16500            }
16501
16502            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16503                updateSequenceNumberLP(ps, res.newUsers);
16504                updateInstantAppInstallerLocked(pkgName);
16505            }
16506        }
16507    }
16508
16509    private void startIntentFilterVerifications(int userId, boolean replacing,
16510            PackageParser.Package pkg) {
16511        if (mIntentFilterVerifierComponent == null) {
16512            Slog.w(TAG, "No IntentFilter verification will not be done as "
16513                    + "there is no IntentFilterVerifier available!");
16514            return;
16515        }
16516
16517        final int verifierUid = getPackageUid(
16518                mIntentFilterVerifierComponent.getPackageName(),
16519                MATCH_DEBUG_TRIAGED_MISSING,
16520                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16521
16522        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16523        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16524        mHandler.sendMessage(msg);
16525
16526        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16527        for (int i = 0; i < childCount; i++) {
16528            PackageParser.Package childPkg = pkg.childPackages.get(i);
16529            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16530            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16531            mHandler.sendMessage(msg);
16532        }
16533    }
16534
16535    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16536            PackageParser.Package pkg) {
16537        int size = pkg.activities.size();
16538        if (size == 0) {
16539            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16540                    "No activity, so no need to verify any IntentFilter!");
16541            return;
16542        }
16543
16544        final boolean hasDomainURLs = hasDomainURLs(pkg);
16545        if (!hasDomainURLs) {
16546            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16547                    "No domain URLs, so no need to verify any IntentFilter!");
16548            return;
16549        }
16550
16551        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16552                + " if any IntentFilter from the " + size
16553                + " Activities needs verification ...");
16554
16555        int count = 0;
16556        final String packageName = pkg.packageName;
16557
16558        synchronized (mPackages) {
16559            // If this is a new install and we see that we've already run verification for this
16560            // package, we have nothing to do: it means the state was restored from backup.
16561            if (!replacing) {
16562                IntentFilterVerificationInfo ivi =
16563                        mSettings.getIntentFilterVerificationLPr(packageName);
16564                if (ivi != null) {
16565                    if (DEBUG_DOMAIN_VERIFICATION) {
16566                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16567                                + ivi.getStatusString());
16568                    }
16569                    return;
16570                }
16571            }
16572
16573            // If any filters need to be verified, then all need to be.
16574            boolean needToVerify = false;
16575            for (PackageParser.Activity a : pkg.activities) {
16576                for (ActivityIntentInfo filter : a.intents) {
16577                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16578                        if (DEBUG_DOMAIN_VERIFICATION) {
16579                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16580                        }
16581                        needToVerify = true;
16582                        break;
16583                    }
16584                }
16585            }
16586
16587            if (needToVerify) {
16588                final int verificationId = mIntentFilterVerificationToken++;
16589                for (PackageParser.Activity a : pkg.activities) {
16590                    for (ActivityIntentInfo filter : a.intents) {
16591                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16592                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16593                                    "Verification needed for IntentFilter:" + filter.toString());
16594                            mIntentFilterVerifier.addOneIntentFilterVerification(
16595                                    verifierUid, userId, verificationId, filter, packageName);
16596                            count++;
16597                        }
16598                    }
16599                }
16600            }
16601        }
16602
16603        if (count > 0) {
16604            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16605                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16606                    +  " for userId:" + userId);
16607            mIntentFilterVerifier.startVerifications(userId);
16608        } else {
16609            if (DEBUG_DOMAIN_VERIFICATION) {
16610                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16611            }
16612        }
16613    }
16614
16615    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16616        final ComponentName cn  = filter.activity.getComponentName();
16617        final String packageName = cn.getPackageName();
16618
16619        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16620                packageName);
16621        if (ivi == null) {
16622            return true;
16623        }
16624        int status = ivi.getStatus();
16625        switch (status) {
16626            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16627            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16628                return true;
16629
16630            default:
16631                // Nothing to do
16632                return false;
16633        }
16634    }
16635
16636    private static boolean isMultiArch(ApplicationInfo info) {
16637        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16638    }
16639
16640    private static boolean isExternal(PackageParser.Package pkg) {
16641        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16642    }
16643
16644    private static boolean isExternal(PackageSetting ps) {
16645        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16646    }
16647
16648    private static boolean isSystemApp(PackageParser.Package pkg) {
16649        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16650    }
16651
16652    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16653        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16654    }
16655
16656    private static boolean isOemApp(PackageParser.Package pkg) {
16657        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16658    }
16659
16660    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16661        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16662    }
16663
16664    private static boolean isSystemApp(PackageSetting ps) {
16665        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16666    }
16667
16668    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16669        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16670    }
16671
16672    private int packageFlagsToInstallFlags(PackageSetting ps) {
16673        int installFlags = 0;
16674        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16675            // This existing package was an external ASEC install when we have
16676            // the external flag without a UUID
16677            installFlags |= PackageManager.INSTALL_EXTERNAL;
16678        }
16679        if (ps.isForwardLocked()) {
16680            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16681        }
16682        return installFlags;
16683    }
16684
16685    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16686        if (isExternal(pkg)) {
16687            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16688                return mSettings.getExternalVersion();
16689            } else {
16690                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16691            }
16692        } else {
16693            return mSettings.getInternalVersion();
16694        }
16695    }
16696
16697    private void deleteTempPackageFiles() {
16698        final FilenameFilter filter = new FilenameFilter() {
16699            public boolean accept(File dir, String name) {
16700                return name.startsWith("vmdl") && name.endsWith(".tmp");
16701            }
16702        };
16703        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16704            file.delete();
16705        }
16706    }
16707
16708    @Override
16709    public void deletePackageAsUser(String packageName, int versionCode,
16710            IPackageDeleteObserver observer, int userId, int flags) {
16711        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
16712                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
16713    }
16714
16715    @Override
16716    public void deletePackageVersioned(VersionedPackage versionedPackage,
16717            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16718        final int callingUid = Binder.getCallingUid();
16719        mContext.enforceCallingOrSelfPermission(
16720                android.Manifest.permission.DELETE_PACKAGES, null);
16721        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
16722        Preconditions.checkNotNull(versionedPackage);
16723        Preconditions.checkNotNull(observer);
16724        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
16725                PackageManager.VERSION_CODE_HIGHEST,
16726                Integer.MAX_VALUE, "versionCode must be >= -1");
16727
16728        final String packageName = versionedPackage.getPackageName();
16729        final int versionCode = versionedPackage.getVersionCode();
16730        final String internalPackageName;
16731        synchronized (mPackages) {
16732            // Normalize package name to handle renamed packages and static libs
16733            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
16734                    versionedPackage.getVersionCode());
16735        }
16736
16737        final int uid = Binder.getCallingUid();
16738        if (!isOrphaned(internalPackageName)
16739                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
16740            try {
16741                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16742                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16743                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16744                observer.onUserActionRequired(intent);
16745            } catch (RemoteException re) {
16746            }
16747            return;
16748        }
16749        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16750        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16751        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16752            mContext.enforceCallingOrSelfPermission(
16753                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16754                    "deletePackage for user " + userId);
16755        }
16756
16757        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16758            try {
16759                observer.onPackageDeleted(packageName,
16760                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16761            } catch (RemoteException re) {
16762            }
16763            return;
16764        }
16765
16766        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
16767            try {
16768                observer.onPackageDeleted(packageName,
16769                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16770            } catch (RemoteException re) {
16771            }
16772            return;
16773        }
16774
16775        if (DEBUG_REMOVE) {
16776            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
16777                    + " deleteAllUsers: " + deleteAllUsers + " version="
16778                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
16779                    ? "VERSION_CODE_HIGHEST" : versionCode));
16780        }
16781        // Queue up an async operation since the package deletion may take a little while.
16782        mHandler.post(new Runnable() {
16783            public void run() {
16784                mHandler.removeCallbacks(this);
16785                int returnCode;
16786                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
16787                boolean doDeletePackage = true;
16788                if (ps != null) {
16789                    final boolean targetIsInstantApp =
16790                            ps.getInstantApp(UserHandle.getUserId(callingUid));
16791                    doDeletePackage = !targetIsInstantApp
16792                            || canViewInstantApps;
16793                }
16794                if (doDeletePackage) {
16795                    if (!deleteAllUsers) {
16796                        returnCode = deletePackageX(internalPackageName, versionCode,
16797                                userId, deleteFlags);
16798                    } else {
16799                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
16800                                internalPackageName, users);
16801                        // If nobody is blocking uninstall, proceed with delete for all users
16802                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16803                            returnCode = deletePackageX(internalPackageName, versionCode,
16804                                    userId, deleteFlags);
16805                        } else {
16806                            // Otherwise uninstall individually for users with blockUninstalls=false
16807                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16808                            for (int userId : users) {
16809                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16810                                    returnCode = deletePackageX(internalPackageName, versionCode,
16811                                            userId, userFlags);
16812                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16813                                        Slog.w(TAG, "Package delete failed for user " + userId
16814                                                + ", returnCode " + returnCode);
16815                                    }
16816                                }
16817                            }
16818                            // The app has only been marked uninstalled for certain users.
16819                            // We still need to report that delete was blocked
16820                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16821                        }
16822                    }
16823                } else {
16824                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16825                }
16826                try {
16827                    observer.onPackageDeleted(packageName, returnCode, null);
16828                } catch (RemoteException e) {
16829                    Log.i(TAG, "Observer no longer exists.");
16830                } //end catch
16831            } //end run
16832        });
16833    }
16834
16835    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
16836        if (pkg.staticSharedLibName != null) {
16837            return pkg.manifestPackageName;
16838        }
16839        return pkg.packageName;
16840    }
16841
16842    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
16843        // Handle renamed packages
16844        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
16845        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
16846
16847        // Is this a static library?
16848        SparseArray<SharedLibraryEntry> versionedLib =
16849                mStaticLibsByDeclaringPackage.get(packageName);
16850        if (versionedLib == null || versionedLib.size() <= 0) {
16851            return packageName;
16852        }
16853
16854        // Figure out which lib versions the caller can see
16855        SparseIntArray versionsCallerCanSee = null;
16856        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
16857        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
16858                && callingAppId != Process.ROOT_UID) {
16859            versionsCallerCanSee = new SparseIntArray();
16860            String libName = versionedLib.valueAt(0).info.getName();
16861            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
16862            if (uidPackages != null) {
16863                for (String uidPackage : uidPackages) {
16864                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
16865                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
16866                    if (libIdx >= 0) {
16867                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
16868                        versionsCallerCanSee.append(libVersion, libVersion);
16869                    }
16870                }
16871            }
16872        }
16873
16874        // Caller can see nothing - done
16875        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
16876            return packageName;
16877        }
16878
16879        // Find the version the caller can see and the app version code
16880        SharedLibraryEntry highestVersion = null;
16881        final int versionCount = versionedLib.size();
16882        for (int i = 0; i < versionCount; i++) {
16883            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
16884            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
16885                    libEntry.info.getVersion()) < 0) {
16886                continue;
16887            }
16888            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
16889            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
16890                if (libVersionCode == versionCode) {
16891                    return libEntry.apk;
16892                }
16893            } else if (highestVersion == null) {
16894                highestVersion = libEntry;
16895            } else if (libVersionCode  > highestVersion.info
16896                    .getDeclaringPackage().getVersionCode()) {
16897                highestVersion = libEntry;
16898            }
16899        }
16900
16901        if (highestVersion != null) {
16902            return highestVersion.apk;
16903        }
16904
16905        return packageName;
16906    }
16907
16908    boolean isCallerVerifier(int callingUid) {
16909        final int callingUserId = UserHandle.getUserId(callingUid);
16910        return mRequiredVerifierPackage != null &&
16911                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
16912    }
16913
16914    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16915        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16916              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16917            return true;
16918        }
16919        final int callingUserId = UserHandle.getUserId(callingUid);
16920        // If the caller installed the pkgName, then allow it to silently uninstall.
16921        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16922            return true;
16923        }
16924
16925        // Allow package verifier to silently uninstall.
16926        if (mRequiredVerifierPackage != null &&
16927                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16928            return true;
16929        }
16930
16931        // Allow package uninstaller to silently uninstall.
16932        if (mRequiredUninstallerPackage != null &&
16933                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16934            return true;
16935        }
16936
16937        // Allow storage manager to silently uninstall.
16938        if (mStorageManagerPackage != null &&
16939                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16940            return true;
16941        }
16942
16943        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
16944        // uninstall for device owner provisioning.
16945        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
16946                == PERMISSION_GRANTED) {
16947            return true;
16948        }
16949
16950        return false;
16951    }
16952
16953    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16954        int[] result = EMPTY_INT_ARRAY;
16955        for (int userId : userIds) {
16956            if (getBlockUninstallForUser(packageName, userId)) {
16957                result = ArrayUtils.appendInt(result, userId);
16958            }
16959        }
16960        return result;
16961    }
16962
16963    @Override
16964    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16965        final int callingUid = Binder.getCallingUid();
16966        if (getInstantAppPackageName(callingUid) != null
16967                && !isCallerSameApp(packageName, callingUid)) {
16968            return false;
16969        }
16970        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16971    }
16972
16973    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16974        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16975                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16976        try {
16977            if (dpm != null) {
16978                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16979                        /* callingUserOnly =*/ false);
16980                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16981                        : deviceOwnerComponentName.getPackageName();
16982                // Does the package contains the device owner?
16983                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16984                // this check is probably not needed, since DO should be registered as a device
16985                // admin on some user too. (Original bug for this: b/17657954)
16986                if (packageName.equals(deviceOwnerPackageName)) {
16987                    return true;
16988                }
16989                // Does it contain a device admin for any user?
16990                int[] users;
16991                if (userId == UserHandle.USER_ALL) {
16992                    users = sUserManager.getUserIds();
16993                } else {
16994                    users = new int[]{userId};
16995                }
16996                for (int i = 0; i < users.length; ++i) {
16997                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16998                        return true;
16999                    }
17000                }
17001            }
17002        } catch (RemoteException e) {
17003        }
17004        return false;
17005    }
17006
17007    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17008        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17009    }
17010
17011    /**
17012     *  This method is an internal method that could be get invoked either
17013     *  to delete an installed package or to clean up a failed installation.
17014     *  After deleting an installed package, a broadcast is sent to notify any
17015     *  listeners that the package has been removed. For cleaning up a failed
17016     *  installation, the broadcast is not necessary since the package's
17017     *  installation wouldn't have sent the initial broadcast either
17018     *  The key steps in deleting a package are
17019     *  deleting the package information in internal structures like mPackages,
17020     *  deleting the packages base directories through installd
17021     *  updating mSettings to reflect current status
17022     *  persisting settings for later use
17023     *  sending a broadcast if necessary
17024     */
17025    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17026        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17027        final boolean res;
17028
17029        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17030                ? UserHandle.USER_ALL : userId;
17031
17032        if (isPackageDeviceAdmin(packageName, removeUser)) {
17033            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17034            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17035        }
17036
17037        PackageSetting uninstalledPs = null;
17038        PackageParser.Package pkg = null;
17039
17040        // for the uninstall-updates case and restricted profiles, remember the per-
17041        // user handle installed state
17042        int[] allUsers;
17043        synchronized (mPackages) {
17044            uninstalledPs = mSettings.mPackages.get(packageName);
17045            if (uninstalledPs == null) {
17046                Slog.w(TAG, "Not removing non-existent package " + packageName);
17047                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17048            }
17049
17050            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17051                    && uninstalledPs.versionCode != versionCode) {
17052                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17053                        + uninstalledPs.versionCode + " != " + versionCode);
17054                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17055            }
17056
17057            // Static shared libs can be declared by any package, so let us not
17058            // allow removing a package if it provides a lib others depend on.
17059            pkg = mPackages.get(packageName);
17060
17061            allUsers = sUserManager.getUserIds();
17062
17063            if (pkg != null && pkg.staticSharedLibName != null) {
17064                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17065                        pkg.staticSharedLibVersion);
17066                if (libEntry != null) {
17067                    for (int currUserId : allUsers) {
17068                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17069                            continue;
17070                        }
17071                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17072                                libEntry.info, 0, currUserId);
17073                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17074                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17075                                    + " hosting lib " + libEntry.info.getName() + " version "
17076                                    + libEntry.info.getVersion() + " used by " + libClientPackages
17077                                    + " for user " + currUserId);
17078                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17079                        }
17080                    }
17081                }
17082            }
17083
17084            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17085        }
17086
17087        final int freezeUser;
17088        if (isUpdatedSystemApp(uninstalledPs)
17089                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17090            // We're downgrading a system app, which will apply to all users, so
17091            // freeze them all during the downgrade
17092            freezeUser = UserHandle.USER_ALL;
17093        } else {
17094            freezeUser = removeUser;
17095        }
17096
17097        synchronized (mInstallLock) {
17098            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17099            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17100                    deleteFlags, "deletePackageX")) {
17101                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17102                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17103            }
17104            synchronized (mPackages) {
17105                if (res) {
17106                    if (pkg != null) {
17107                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17108                    }
17109                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17110                    updateInstantAppInstallerLocked(packageName);
17111                }
17112            }
17113        }
17114
17115        if (res) {
17116            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17117            info.sendPackageRemovedBroadcasts(killApp);
17118            info.sendSystemPackageUpdatedBroadcasts();
17119            info.sendSystemPackageAppearedBroadcasts();
17120        }
17121        // Force a gc here.
17122        Runtime.getRuntime().gc();
17123        // Delete the resources here after sending the broadcast to let
17124        // other processes clean up before deleting resources.
17125        if (info.args != null) {
17126            synchronized (mInstallLock) {
17127                info.args.doPostDeleteLI(true);
17128            }
17129        }
17130
17131        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17132    }
17133
17134    static class PackageRemovedInfo {
17135        final PackageSender packageSender;
17136        String removedPackage;
17137        String installerPackageName;
17138        int uid = -1;
17139        int removedAppId = -1;
17140        int[] origUsers;
17141        int[] removedUsers = null;
17142        int[] broadcastUsers = null;
17143        SparseArray<Integer> installReasons;
17144        boolean isRemovedPackageSystemUpdate = false;
17145        boolean isUpdate;
17146        boolean dataRemoved;
17147        boolean removedForAllUsers;
17148        boolean isStaticSharedLib;
17149        // Clean up resources deleted packages.
17150        InstallArgs args = null;
17151        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17152        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17153
17154        PackageRemovedInfo(PackageSender packageSender) {
17155            this.packageSender = packageSender;
17156        }
17157
17158        void sendPackageRemovedBroadcasts(boolean killApp) {
17159            sendPackageRemovedBroadcastInternal(killApp);
17160            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17161            for (int i = 0; i < childCount; i++) {
17162                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17163                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17164            }
17165        }
17166
17167        void sendSystemPackageUpdatedBroadcasts() {
17168            if (isRemovedPackageSystemUpdate) {
17169                sendSystemPackageUpdatedBroadcastsInternal();
17170                final int childCount = (removedChildPackages != null)
17171                        ? removedChildPackages.size() : 0;
17172                for (int i = 0; i < childCount; i++) {
17173                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17174                    if (childInfo.isRemovedPackageSystemUpdate) {
17175                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17176                    }
17177                }
17178            }
17179        }
17180
17181        void sendSystemPackageAppearedBroadcasts() {
17182            final int packageCount = (appearedChildPackages != null)
17183                    ? appearedChildPackages.size() : 0;
17184            for (int i = 0; i < packageCount; i++) {
17185                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17186                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17187                    true /*sendBootCompleted*/, false /*startReceiver*/,
17188                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17189            }
17190        }
17191
17192        private void sendSystemPackageUpdatedBroadcastsInternal() {
17193            Bundle extras = new Bundle(2);
17194            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17195            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17196            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17197                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17198            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17199                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17200            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17201                null, null, 0, removedPackage, null, null);
17202            if (installerPackageName != null) {
17203                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17204                        removedPackage, extras, 0 /*flags*/,
17205                        installerPackageName, null, null);
17206                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17207                        removedPackage, extras, 0 /*flags*/,
17208                        installerPackageName, null, null);
17209            }
17210        }
17211
17212        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17213            // Don't send static shared library removal broadcasts as these
17214            // libs are visible only the the apps that depend on them an one
17215            // cannot remove the library if it has a dependency.
17216            if (isStaticSharedLib) {
17217                return;
17218            }
17219            Bundle extras = new Bundle(2);
17220            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17221            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17222            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17223            if (isUpdate || isRemovedPackageSystemUpdate) {
17224                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17225            }
17226            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17227            if (removedPackage != null) {
17228                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17229                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17230                if (installerPackageName != null) {
17231                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17232                            removedPackage, extras, 0 /*flags*/,
17233                            installerPackageName, null, broadcastUsers);
17234                }
17235                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17236                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17237                        removedPackage, extras,
17238                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17239                        null, null, broadcastUsers);
17240                }
17241            }
17242            if (removedAppId >= 0) {
17243                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17244                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17245                    null, null, broadcastUsers);
17246            }
17247        }
17248
17249        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17250            removedUsers = userIds;
17251            if (removedUsers == null) {
17252                broadcastUsers = null;
17253                return;
17254            }
17255
17256            broadcastUsers = EMPTY_INT_ARRAY;
17257            for (int i = userIds.length - 1; i >= 0; --i) {
17258                final int userId = userIds[i];
17259                if (deletedPackageSetting.getInstantApp(userId)) {
17260                    continue;
17261                }
17262                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17263            }
17264        }
17265    }
17266
17267    /*
17268     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17269     * flag is not set, the data directory is removed as well.
17270     * make sure this flag is set for partially installed apps. If not its meaningless to
17271     * delete a partially installed application.
17272     */
17273    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17274            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17275        String packageName = ps.name;
17276        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17277        // Retrieve object to delete permissions for shared user later on
17278        final PackageParser.Package deletedPkg;
17279        final PackageSetting deletedPs;
17280        // reader
17281        synchronized (mPackages) {
17282            deletedPkg = mPackages.get(packageName);
17283            deletedPs = mSettings.mPackages.get(packageName);
17284            if (outInfo != null) {
17285                outInfo.removedPackage = packageName;
17286                outInfo.installerPackageName = ps.installerPackageName;
17287                outInfo.isStaticSharedLib = deletedPkg != null
17288                        && deletedPkg.staticSharedLibName != null;
17289                outInfo.populateUsers(deletedPs == null ? null
17290                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17291            }
17292        }
17293
17294        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17295
17296        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17297            final PackageParser.Package resolvedPkg;
17298            if (deletedPkg != null) {
17299                resolvedPkg = deletedPkg;
17300            } else {
17301                // We don't have a parsed package when it lives on an ejected
17302                // adopted storage device, so fake something together
17303                resolvedPkg = new PackageParser.Package(ps.name);
17304                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17305            }
17306            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17307                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17308            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17309            if (outInfo != null) {
17310                outInfo.dataRemoved = true;
17311            }
17312            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17313        }
17314
17315        int removedAppId = -1;
17316
17317        // writer
17318        synchronized (mPackages) {
17319            boolean installedStateChanged = false;
17320            if (deletedPs != null) {
17321                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17322                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17323                    clearDefaultBrowserIfNeeded(packageName);
17324                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17325                    removedAppId = mSettings.removePackageLPw(packageName);
17326                    if (outInfo != null) {
17327                        outInfo.removedAppId = removedAppId;
17328                    }
17329                    mPermissionManager.updatePermissions(
17330                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17331                    if (deletedPs.sharedUser != null) {
17332                        // Remove permissions associated with package. Since runtime
17333                        // permissions are per user we have to kill the removed package
17334                        // or packages running under the shared user of the removed
17335                        // package if revoking the permissions requested only by the removed
17336                        // package is successful and this causes a change in gids.
17337                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17338                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17339                                    userId);
17340                            if (userIdToKill == UserHandle.USER_ALL
17341                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17342                                // If gids changed for this user, kill all affected packages.
17343                                mHandler.post(new Runnable() {
17344                                    @Override
17345                                    public void run() {
17346                                        // This has to happen with no lock held.
17347                                        killApplication(deletedPs.name, deletedPs.appId,
17348                                                KILL_APP_REASON_GIDS_CHANGED);
17349                                    }
17350                                });
17351                                break;
17352                            }
17353                        }
17354                    }
17355                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17356                }
17357                // make sure to preserve per-user disabled state if this removal was just
17358                // a downgrade of a system app to the factory package
17359                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17360                    if (DEBUG_REMOVE) {
17361                        Slog.d(TAG, "Propagating install state across downgrade");
17362                    }
17363                    for (int userId : allUserHandles) {
17364                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17365                        if (DEBUG_REMOVE) {
17366                            Slog.d(TAG, "    user " + userId + " => " + installed);
17367                        }
17368                        if (installed != ps.getInstalled(userId)) {
17369                            installedStateChanged = true;
17370                        }
17371                        ps.setInstalled(installed, userId);
17372                    }
17373                }
17374            }
17375            // can downgrade to reader
17376            if (writeSettings) {
17377                // Save settings now
17378                mSettings.writeLPr();
17379            }
17380            if (installedStateChanged) {
17381                mSettings.writeKernelMappingLPr(ps);
17382            }
17383        }
17384        if (removedAppId != -1) {
17385            // A user ID was deleted here. Go through all users and remove it
17386            // from KeyStore.
17387            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17388        }
17389    }
17390
17391    static boolean locationIsPrivileged(File path) {
17392        try {
17393            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17394                    .getCanonicalPath();
17395            return path.getCanonicalPath().startsWith(privilegedAppDir);
17396        } catch (IOException e) {
17397            Slog.e(TAG, "Unable to access code path " + path);
17398        }
17399        return false;
17400    }
17401
17402    static boolean locationIsOem(File path) {
17403        try {
17404            return path.getCanonicalPath().startsWith(
17405                    Environment.getOemDirectory().getCanonicalPath());
17406        } catch (IOException e) {
17407            Slog.e(TAG, "Unable to access code path " + path);
17408        }
17409        return false;
17410    }
17411
17412    /*
17413     * Tries to delete system package.
17414     */
17415    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17416            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17417            boolean writeSettings) {
17418        if (deletedPs.parentPackageName != null) {
17419            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17420            return false;
17421        }
17422
17423        final boolean applyUserRestrictions
17424                = (allUserHandles != null) && (outInfo.origUsers != null);
17425        final PackageSetting disabledPs;
17426        // Confirm if the system package has been updated
17427        // An updated system app can be deleted. This will also have to restore
17428        // the system pkg from system partition
17429        // reader
17430        synchronized (mPackages) {
17431            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17432        }
17433
17434        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17435                + " disabledPs=" + disabledPs);
17436
17437        if (disabledPs == null) {
17438            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17439            return false;
17440        } else if (DEBUG_REMOVE) {
17441            Slog.d(TAG, "Deleting system pkg from data partition");
17442        }
17443
17444        if (DEBUG_REMOVE) {
17445            if (applyUserRestrictions) {
17446                Slog.d(TAG, "Remembering install states:");
17447                for (int userId : allUserHandles) {
17448                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17449                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17450                }
17451            }
17452        }
17453
17454        // Delete the updated package
17455        outInfo.isRemovedPackageSystemUpdate = true;
17456        if (outInfo.removedChildPackages != null) {
17457            final int childCount = (deletedPs.childPackageNames != null)
17458                    ? deletedPs.childPackageNames.size() : 0;
17459            for (int i = 0; i < childCount; i++) {
17460                String childPackageName = deletedPs.childPackageNames.get(i);
17461                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17462                        .contains(childPackageName)) {
17463                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17464                            childPackageName);
17465                    if (childInfo != null) {
17466                        childInfo.isRemovedPackageSystemUpdate = true;
17467                    }
17468                }
17469            }
17470        }
17471
17472        if (disabledPs.versionCode < deletedPs.versionCode) {
17473            // Delete data for downgrades
17474            flags &= ~PackageManager.DELETE_KEEP_DATA;
17475        } else {
17476            // Preserve data by setting flag
17477            flags |= PackageManager.DELETE_KEEP_DATA;
17478        }
17479
17480        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17481                outInfo, writeSettings, disabledPs.pkg);
17482        if (!ret) {
17483            return false;
17484        }
17485
17486        // writer
17487        synchronized (mPackages) {
17488            // NOTE: The system package always needs to be enabled; even if it's for
17489            // a compressed stub. If we don't, installing the system package fails
17490            // during scan [scanning checks the disabled packages]. We will reverse
17491            // this later, after we've "installed" the stub.
17492            // Reinstate the old system package
17493            enableSystemPackageLPw(disabledPs.pkg);
17494            // Remove any native libraries from the upgraded package.
17495            removeNativeBinariesLI(deletedPs);
17496        }
17497
17498        // Install the system package
17499        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17500        try {
17501            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
17502                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17503        } catch (PackageManagerException e) {
17504            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17505                    + e.getMessage());
17506            return false;
17507        } finally {
17508            if (disabledPs.pkg.isStub) {
17509                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17510            }
17511        }
17512        return true;
17513    }
17514
17515    /**
17516     * Installs a package that's already on the system partition.
17517     */
17518    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
17519            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17520            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17521                    throws PackageManagerException {
17522        int parseFlags = mDefParseFlags
17523                | PackageParser.PARSE_MUST_BE_APK
17524                | PackageParser.PARSE_IS_SYSTEM
17525                | PackageParser.PARSE_IS_SYSTEM_DIR;
17526        if (isPrivileged || locationIsPrivileged(codePath)) {
17527            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17528        }
17529        if (locationIsOem(codePath)) {
17530            parseFlags |= PackageParser.PARSE_IS_OEM;
17531        }
17532
17533        final PackageParser.Package pkg =
17534                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
17535
17536        try {
17537            // update shared libraries for the newly re-installed system package
17538            updateSharedLibrariesLPr(pkg, null);
17539        } catch (PackageManagerException e) {
17540            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17541        }
17542
17543        prepareAppDataAfterInstallLIF(pkg);
17544
17545        // writer
17546        synchronized (mPackages) {
17547            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17548
17549            // Propagate the permissions state as we do not want to drop on the floor
17550            // runtime permissions. The update permissions method below will take
17551            // care of removing obsolete permissions and grant install permissions.
17552            if (origPermissionState != null) {
17553                ps.getPermissionsState().copyFrom(origPermissionState);
17554            }
17555            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17556                    mPermissionCallback);
17557
17558            final boolean applyUserRestrictions
17559                    = (allUserHandles != null) && (origUserHandles != null);
17560            if (applyUserRestrictions) {
17561                boolean installedStateChanged = false;
17562                if (DEBUG_REMOVE) {
17563                    Slog.d(TAG, "Propagating install state across reinstall");
17564                }
17565                for (int userId : allUserHandles) {
17566                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17567                    if (DEBUG_REMOVE) {
17568                        Slog.d(TAG, "    user " + userId + " => " + installed);
17569                    }
17570                    if (installed != ps.getInstalled(userId)) {
17571                        installedStateChanged = true;
17572                    }
17573                    ps.setInstalled(installed, userId);
17574
17575                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17576                }
17577                // Regardless of writeSettings we need to ensure that this restriction
17578                // state propagation is persisted
17579                mSettings.writeAllUsersPackageRestrictionsLPr();
17580                if (installedStateChanged) {
17581                    mSettings.writeKernelMappingLPr(ps);
17582                }
17583            }
17584            // can downgrade to reader here
17585            if (writeSettings) {
17586                mSettings.writeLPr();
17587            }
17588        }
17589        return pkg;
17590    }
17591
17592    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17593            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17594            PackageRemovedInfo outInfo, boolean writeSettings,
17595            PackageParser.Package replacingPackage) {
17596        synchronized (mPackages) {
17597            if (outInfo != null) {
17598                outInfo.uid = ps.appId;
17599            }
17600
17601            if (outInfo != null && outInfo.removedChildPackages != null) {
17602                final int childCount = (ps.childPackageNames != null)
17603                        ? ps.childPackageNames.size() : 0;
17604                for (int i = 0; i < childCount; i++) {
17605                    String childPackageName = ps.childPackageNames.get(i);
17606                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17607                    if (childPs == null) {
17608                        return false;
17609                    }
17610                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17611                            childPackageName);
17612                    if (childInfo != null) {
17613                        childInfo.uid = childPs.appId;
17614                    }
17615                }
17616            }
17617        }
17618
17619        // Delete package data from internal structures and also remove data if flag is set
17620        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17621
17622        // Delete the child packages data
17623        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17624        for (int i = 0; i < childCount; i++) {
17625            PackageSetting childPs;
17626            synchronized (mPackages) {
17627                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17628            }
17629            if (childPs != null) {
17630                PackageRemovedInfo childOutInfo = (outInfo != null
17631                        && outInfo.removedChildPackages != null)
17632                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17633                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17634                        && (replacingPackage != null
17635                        && !replacingPackage.hasChildPackage(childPs.name))
17636                        ? flags & ~DELETE_KEEP_DATA : flags;
17637                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17638                        deleteFlags, writeSettings);
17639            }
17640        }
17641
17642        // Delete application code and resources only for parent packages
17643        if (ps.parentPackageName == null) {
17644            if (deleteCodeAndResources && (outInfo != null)) {
17645                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17646                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17647                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17648            }
17649        }
17650
17651        return true;
17652    }
17653
17654    @Override
17655    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17656            int userId) {
17657        mContext.enforceCallingOrSelfPermission(
17658                android.Manifest.permission.DELETE_PACKAGES, null);
17659        synchronized (mPackages) {
17660            // Cannot block uninstall of static shared libs as they are
17661            // considered a part of the using app (emulating static linking).
17662            // Also static libs are installed always on internal storage.
17663            PackageParser.Package pkg = mPackages.get(packageName);
17664            if (pkg != null && pkg.staticSharedLibName != null) {
17665                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17666                        + " providing static shared library: " + pkg.staticSharedLibName);
17667                return false;
17668            }
17669            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
17670            mSettings.writePackageRestrictionsLPr(userId);
17671        }
17672        return true;
17673    }
17674
17675    @Override
17676    public boolean getBlockUninstallForUser(String packageName, int userId) {
17677        synchronized (mPackages) {
17678            final PackageSetting ps = mSettings.mPackages.get(packageName);
17679            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
17680                return false;
17681            }
17682            return mSettings.getBlockUninstallLPr(userId, packageName);
17683        }
17684    }
17685
17686    @Override
17687    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17688        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
17689        synchronized (mPackages) {
17690            PackageSetting ps = mSettings.mPackages.get(packageName);
17691            if (ps == null) {
17692                Log.w(TAG, "Package doesn't exist: " + packageName);
17693                return false;
17694            }
17695            if (systemUserApp) {
17696                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17697            } else {
17698                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17699            }
17700            mSettings.writeLPr();
17701        }
17702        return true;
17703    }
17704
17705    /*
17706     * This method handles package deletion in general
17707     */
17708    private boolean deletePackageLIF(String packageName, UserHandle user,
17709            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17710            PackageRemovedInfo outInfo, boolean writeSettings,
17711            PackageParser.Package replacingPackage) {
17712        if (packageName == null) {
17713            Slog.w(TAG, "Attempt to delete null packageName.");
17714            return false;
17715        }
17716
17717        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17718
17719        PackageSetting ps;
17720        synchronized (mPackages) {
17721            ps = mSettings.mPackages.get(packageName);
17722            if (ps == null) {
17723                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17724                return false;
17725            }
17726
17727            if (ps.parentPackageName != null && (!isSystemApp(ps)
17728                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17729                if (DEBUG_REMOVE) {
17730                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17731                            + ((user == null) ? UserHandle.USER_ALL : user));
17732                }
17733                final int removedUserId = (user != null) ? user.getIdentifier()
17734                        : UserHandle.USER_ALL;
17735                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17736                    return false;
17737                }
17738                markPackageUninstalledForUserLPw(ps, user);
17739                scheduleWritePackageRestrictionsLocked(user);
17740                return true;
17741            }
17742        }
17743
17744        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17745                && user.getIdentifier() != UserHandle.USER_ALL)) {
17746            // The caller is asking that the package only be deleted for a single
17747            // user.  To do this, we just mark its uninstalled state and delete
17748            // its data. If this is a system app, we only allow this to happen if
17749            // they have set the special DELETE_SYSTEM_APP which requests different
17750            // semantics than normal for uninstalling system apps.
17751            markPackageUninstalledForUserLPw(ps, user);
17752
17753            if (!isSystemApp(ps)) {
17754                // Do not uninstall the APK if an app should be cached
17755                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17756                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17757                    // Other user still have this package installed, so all
17758                    // we need to do is clear this user's data and save that
17759                    // it is uninstalled.
17760                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17761                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17762                        return false;
17763                    }
17764                    scheduleWritePackageRestrictionsLocked(user);
17765                    return true;
17766                } else {
17767                    // We need to set it back to 'installed' so the uninstall
17768                    // broadcasts will be sent correctly.
17769                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17770                    ps.setInstalled(true, user.getIdentifier());
17771                    mSettings.writeKernelMappingLPr(ps);
17772                }
17773            } else {
17774                // This is a system app, so we assume that the
17775                // other users still have this package installed, so all
17776                // we need to do is clear this user's data and save that
17777                // it is uninstalled.
17778                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17779                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17780                    return false;
17781                }
17782                scheduleWritePackageRestrictionsLocked(user);
17783                return true;
17784            }
17785        }
17786
17787        // If we are deleting a composite package for all users, keep track
17788        // of result for each child.
17789        if (ps.childPackageNames != null && outInfo != null) {
17790            synchronized (mPackages) {
17791                final int childCount = ps.childPackageNames.size();
17792                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17793                for (int i = 0; i < childCount; i++) {
17794                    String childPackageName = ps.childPackageNames.get(i);
17795                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
17796                    childInfo.removedPackage = childPackageName;
17797                    childInfo.installerPackageName = ps.installerPackageName;
17798                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17799                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17800                    if (childPs != null) {
17801                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17802                    }
17803                }
17804            }
17805        }
17806
17807        boolean ret = false;
17808        if (isSystemApp(ps)) {
17809            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17810            // When an updated system application is deleted we delete the existing resources
17811            // as well and fall back to existing code in system partition
17812            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17813        } else {
17814            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17815            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17816                    outInfo, writeSettings, replacingPackage);
17817        }
17818
17819        // Take a note whether we deleted the package for all users
17820        if (outInfo != null) {
17821            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17822            if (outInfo.removedChildPackages != null) {
17823                synchronized (mPackages) {
17824                    final int childCount = outInfo.removedChildPackages.size();
17825                    for (int i = 0; i < childCount; i++) {
17826                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17827                        if (childInfo != null) {
17828                            childInfo.removedForAllUsers = mPackages.get(
17829                                    childInfo.removedPackage) == null;
17830                        }
17831                    }
17832                }
17833            }
17834            // If we uninstalled an update to a system app there may be some
17835            // child packages that appeared as they are declared in the system
17836            // app but were not declared in the update.
17837            if (isSystemApp(ps)) {
17838                synchronized (mPackages) {
17839                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17840                    final int childCount = (updatedPs.childPackageNames != null)
17841                            ? updatedPs.childPackageNames.size() : 0;
17842                    for (int i = 0; i < childCount; i++) {
17843                        String childPackageName = updatedPs.childPackageNames.get(i);
17844                        if (outInfo.removedChildPackages == null
17845                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17846                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17847                            if (childPs == null) {
17848                                continue;
17849                            }
17850                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17851                            installRes.name = childPackageName;
17852                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17853                            installRes.pkg = mPackages.get(childPackageName);
17854                            installRes.uid = childPs.pkg.applicationInfo.uid;
17855                            if (outInfo.appearedChildPackages == null) {
17856                                outInfo.appearedChildPackages = new ArrayMap<>();
17857                            }
17858                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17859                        }
17860                    }
17861                }
17862            }
17863        }
17864
17865        return ret;
17866    }
17867
17868    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17869        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17870                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17871        for (int nextUserId : userIds) {
17872            if (DEBUG_REMOVE) {
17873                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17874            }
17875            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17876                    false /*installed*/,
17877                    true /*stopped*/,
17878                    true /*notLaunched*/,
17879                    false /*hidden*/,
17880                    false /*suspended*/,
17881                    false /*instantApp*/,
17882                    false /*virtualPreload*/,
17883                    null /*lastDisableAppCaller*/,
17884                    null /*enabledComponents*/,
17885                    null /*disabledComponents*/,
17886                    ps.readUserState(nextUserId).domainVerificationStatus,
17887                    0, PackageManager.INSTALL_REASON_UNKNOWN);
17888        }
17889        mSettings.writeKernelMappingLPr(ps);
17890    }
17891
17892    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17893            PackageRemovedInfo outInfo) {
17894        final PackageParser.Package pkg;
17895        synchronized (mPackages) {
17896            pkg = mPackages.get(ps.name);
17897        }
17898
17899        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17900                : new int[] {userId};
17901        for (int nextUserId : userIds) {
17902            if (DEBUG_REMOVE) {
17903                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17904                        + nextUserId);
17905            }
17906
17907            destroyAppDataLIF(pkg, userId,
17908                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17909            destroyAppProfilesLIF(pkg, userId);
17910            clearDefaultBrowserIfNeededForUser(ps.name, userId);
17911            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17912            schedulePackageCleaning(ps.name, nextUserId, false);
17913            synchronized (mPackages) {
17914                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17915                    scheduleWritePackageRestrictionsLocked(nextUserId);
17916                }
17917                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17918            }
17919        }
17920
17921        if (outInfo != null) {
17922            outInfo.removedPackage = ps.name;
17923            outInfo.installerPackageName = ps.installerPackageName;
17924            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
17925            outInfo.removedAppId = ps.appId;
17926            outInfo.removedUsers = userIds;
17927            outInfo.broadcastUsers = userIds;
17928        }
17929
17930        return true;
17931    }
17932
17933    private final class ClearStorageConnection implements ServiceConnection {
17934        IMediaContainerService mContainerService;
17935
17936        @Override
17937        public void onServiceConnected(ComponentName name, IBinder service) {
17938            synchronized (this) {
17939                mContainerService = IMediaContainerService.Stub
17940                        .asInterface(Binder.allowBlocking(service));
17941                notifyAll();
17942            }
17943        }
17944
17945        @Override
17946        public void onServiceDisconnected(ComponentName name) {
17947        }
17948    }
17949
17950    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17951        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17952
17953        final boolean mounted;
17954        if (Environment.isExternalStorageEmulated()) {
17955            mounted = true;
17956        } else {
17957            final String status = Environment.getExternalStorageState();
17958
17959            mounted = status.equals(Environment.MEDIA_MOUNTED)
17960                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17961        }
17962
17963        if (!mounted) {
17964            return;
17965        }
17966
17967        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17968        int[] users;
17969        if (userId == UserHandle.USER_ALL) {
17970            users = sUserManager.getUserIds();
17971        } else {
17972            users = new int[] { userId };
17973        }
17974        final ClearStorageConnection conn = new ClearStorageConnection();
17975        if (mContext.bindServiceAsUser(
17976                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17977            try {
17978                for (int curUser : users) {
17979                    long timeout = SystemClock.uptimeMillis() + 5000;
17980                    synchronized (conn) {
17981                        long now;
17982                        while (conn.mContainerService == null &&
17983                                (now = SystemClock.uptimeMillis()) < timeout) {
17984                            try {
17985                                conn.wait(timeout - now);
17986                            } catch (InterruptedException e) {
17987                            }
17988                        }
17989                    }
17990                    if (conn.mContainerService == null) {
17991                        return;
17992                    }
17993
17994                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17995                    clearDirectory(conn.mContainerService,
17996                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17997                    if (allData) {
17998                        clearDirectory(conn.mContainerService,
17999                                userEnv.buildExternalStorageAppDataDirs(packageName));
18000                        clearDirectory(conn.mContainerService,
18001                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18002                    }
18003                }
18004            } finally {
18005                mContext.unbindService(conn);
18006            }
18007        }
18008    }
18009
18010    @Override
18011    public void clearApplicationProfileData(String packageName) {
18012        enforceSystemOrRoot("Only the system can clear all profile data");
18013
18014        final PackageParser.Package pkg;
18015        synchronized (mPackages) {
18016            pkg = mPackages.get(packageName);
18017        }
18018
18019        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18020            synchronized (mInstallLock) {
18021                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18022            }
18023        }
18024    }
18025
18026    @Override
18027    public void clearApplicationUserData(final String packageName,
18028            final IPackageDataObserver observer, final int userId) {
18029        mContext.enforceCallingOrSelfPermission(
18030                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18031
18032        final int callingUid = Binder.getCallingUid();
18033        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18034                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18035
18036        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18037        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18038        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18039            throw new SecurityException("Cannot clear data for a protected package: "
18040                    + packageName);
18041        }
18042        // Queue up an async operation since the package deletion may take a little while.
18043        mHandler.post(new Runnable() {
18044            public void run() {
18045                mHandler.removeCallbacks(this);
18046                final boolean succeeded;
18047                if (!filterApp) {
18048                    try (PackageFreezer freezer = freezePackage(packageName,
18049                            "clearApplicationUserData")) {
18050                        synchronized (mInstallLock) {
18051                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18052                        }
18053                        clearExternalStorageDataSync(packageName, userId, true);
18054                        synchronized (mPackages) {
18055                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18056                                    packageName, userId);
18057                        }
18058                    }
18059                    if (succeeded) {
18060                        // invoke DeviceStorageMonitor's update method to clear any notifications
18061                        DeviceStorageMonitorInternal dsm = LocalServices
18062                                .getService(DeviceStorageMonitorInternal.class);
18063                        if (dsm != null) {
18064                            dsm.checkMemory();
18065                        }
18066                    }
18067                } else {
18068                    succeeded = false;
18069                }
18070                if (observer != null) {
18071                    try {
18072                        observer.onRemoveCompleted(packageName, succeeded);
18073                    } catch (RemoteException e) {
18074                        Log.i(TAG, "Observer no longer exists.");
18075                    }
18076                } //end if observer
18077            } //end run
18078        });
18079    }
18080
18081    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18082        if (packageName == null) {
18083            Slog.w(TAG, "Attempt to delete null packageName.");
18084            return false;
18085        }
18086
18087        // Try finding details about the requested package
18088        PackageParser.Package pkg;
18089        synchronized (mPackages) {
18090            pkg = mPackages.get(packageName);
18091            if (pkg == null) {
18092                final PackageSetting ps = mSettings.mPackages.get(packageName);
18093                if (ps != null) {
18094                    pkg = ps.pkg;
18095                }
18096            }
18097
18098            if (pkg == null) {
18099                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18100                return false;
18101            }
18102
18103            PackageSetting ps = (PackageSetting) pkg.mExtras;
18104            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18105        }
18106
18107        clearAppDataLIF(pkg, userId,
18108                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18109
18110        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18111        removeKeystoreDataIfNeeded(userId, appId);
18112
18113        UserManagerInternal umInternal = getUserManagerInternal();
18114        final int flags;
18115        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18116            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18117        } else if (umInternal.isUserRunning(userId)) {
18118            flags = StorageManager.FLAG_STORAGE_DE;
18119        } else {
18120            flags = 0;
18121        }
18122        prepareAppDataContentsLIF(pkg, userId, flags);
18123
18124        return true;
18125    }
18126
18127    /**
18128     * Reverts user permission state changes (permissions and flags) in
18129     * all packages for a given user.
18130     *
18131     * @param userId The device user for which to do a reset.
18132     */
18133    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18134        final int packageCount = mPackages.size();
18135        for (int i = 0; i < packageCount; i++) {
18136            PackageParser.Package pkg = mPackages.valueAt(i);
18137            PackageSetting ps = (PackageSetting) pkg.mExtras;
18138            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18139        }
18140    }
18141
18142    private void resetNetworkPolicies(int userId) {
18143        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18144    }
18145
18146    /**
18147     * Reverts user permission state changes (permissions and flags).
18148     *
18149     * @param ps The package for which to reset.
18150     * @param userId The device user for which to do a reset.
18151     */
18152    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18153            final PackageSetting ps, final int userId) {
18154        if (ps.pkg == null) {
18155            return;
18156        }
18157
18158        // These are flags that can change base on user actions.
18159        final int userSettableMask = FLAG_PERMISSION_USER_SET
18160                | FLAG_PERMISSION_USER_FIXED
18161                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18162                | FLAG_PERMISSION_REVIEW_REQUIRED;
18163
18164        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18165                | FLAG_PERMISSION_POLICY_FIXED;
18166
18167        boolean writeInstallPermissions = false;
18168        boolean writeRuntimePermissions = false;
18169
18170        final int permissionCount = ps.pkg.requestedPermissions.size();
18171        for (int i = 0; i < permissionCount; i++) {
18172            final String permName = ps.pkg.requestedPermissions.get(i);
18173            final BasePermission bp =
18174                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18175            if (bp == null) {
18176                continue;
18177            }
18178
18179            // If shared user we just reset the state to which only this app contributed.
18180            if (ps.sharedUser != null) {
18181                boolean used = false;
18182                final int packageCount = ps.sharedUser.packages.size();
18183                for (int j = 0; j < packageCount; j++) {
18184                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18185                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18186                            && pkg.pkg.requestedPermissions.contains(permName)) {
18187                        used = true;
18188                        break;
18189                    }
18190                }
18191                if (used) {
18192                    continue;
18193                }
18194            }
18195
18196            final PermissionsState permissionsState = ps.getPermissionsState();
18197
18198            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18199
18200            // Always clear the user settable flags.
18201            final boolean hasInstallState =
18202                    permissionsState.getInstallPermissionState(permName) != null;
18203            // If permission review is enabled and this is a legacy app, mark the
18204            // permission as requiring a review as this is the initial state.
18205            int flags = 0;
18206            if (mSettings.mPermissions.mPermissionReviewRequired
18207                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18208                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18209            }
18210            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18211                if (hasInstallState) {
18212                    writeInstallPermissions = true;
18213                } else {
18214                    writeRuntimePermissions = true;
18215                }
18216            }
18217
18218            // Below is only runtime permission handling.
18219            if (!bp.isRuntime()) {
18220                continue;
18221            }
18222
18223            // Never clobber system or policy.
18224            if ((oldFlags & policyOrSystemFlags) != 0) {
18225                continue;
18226            }
18227
18228            // If this permission was granted by default, make sure it is.
18229            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18230                if (permissionsState.grantRuntimePermission(bp, userId)
18231                        != PERMISSION_OPERATION_FAILURE) {
18232                    writeRuntimePermissions = true;
18233                }
18234            // If permission review is enabled the permissions for a legacy apps
18235            // are represented as constantly granted runtime ones, so don't revoke.
18236            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18237                // Otherwise, reset the permission.
18238                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18239                switch (revokeResult) {
18240                    case PERMISSION_OPERATION_SUCCESS:
18241                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18242                        writeRuntimePermissions = true;
18243                        final int appId = ps.appId;
18244                        mHandler.post(new Runnable() {
18245                            @Override
18246                            public void run() {
18247                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18248                            }
18249                        });
18250                    } break;
18251                }
18252            }
18253        }
18254
18255        // Synchronously write as we are taking permissions away.
18256        if (writeRuntimePermissions) {
18257            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18258        }
18259
18260        // Synchronously write as we are taking permissions away.
18261        if (writeInstallPermissions) {
18262            mSettings.writeLPr();
18263        }
18264    }
18265
18266    /**
18267     * Remove entries from the keystore daemon. Will only remove it if the
18268     * {@code appId} is valid.
18269     */
18270    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18271        if (appId < 0) {
18272            return;
18273        }
18274
18275        final KeyStore keyStore = KeyStore.getInstance();
18276        if (keyStore != null) {
18277            if (userId == UserHandle.USER_ALL) {
18278                for (final int individual : sUserManager.getUserIds()) {
18279                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18280                }
18281            } else {
18282                keyStore.clearUid(UserHandle.getUid(userId, appId));
18283            }
18284        } else {
18285            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18286        }
18287    }
18288
18289    @Override
18290    public void deleteApplicationCacheFiles(final String packageName,
18291            final IPackageDataObserver observer) {
18292        final int userId = UserHandle.getCallingUserId();
18293        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18294    }
18295
18296    @Override
18297    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18298            final IPackageDataObserver observer) {
18299        final int callingUid = Binder.getCallingUid();
18300        mContext.enforceCallingOrSelfPermission(
18301                android.Manifest.permission.DELETE_CACHE_FILES, null);
18302        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18303                /* requireFullPermission= */ true, /* checkShell= */ false,
18304                "delete application cache files");
18305        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18306                android.Manifest.permission.ACCESS_INSTANT_APPS);
18307
18308        final PackageParser.Package pkg;
18309        synchronized (mPackages) {
18310            pkg = mPackages.get(packageName);
18311        }
18312
18313        // Queue up an async operation since the package deletion may take a little while.
18314        mHandler.post(new Runnable() {
18315            public void run() {
18316                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18317                boolean doClearData = true;
18318                if (ps != null) {
18319                    final boolean targetIsInstantApp =
18320                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18321                    doClearData = !targetIsInstantApp
18322                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18323                }
18324                if (doClearData) {
18325                    synchronized (mInstallLock) {
18326                        final int flags = StorageManager.FLAG_STORAGE_DE
18327                                | StorageManager.FLAG_STORAGE_CE;
18328                        // We're only clearing cache files, so we don't care if the
18329                        // app is unfrozen and still able to run
18330                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18331                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18332                    }
18333                    clearExternalStorageDataSync(packageName, userId, false);
18334                }
18335                if (observer != null) {
18336                    try {
18337                        observer.onRemoveCompleted(packageName, true);
18338                    } catch (RemoteException e) {
18339                        Log.i(TAG, "Observer no longer exists.");
18340                    }
18341                }
18342            }
18343        });
18344    }
18345
18346    @Override
18347    public void getPackageSizeInfo(final String packageName, int userHandle,
18348            final IPackageStatsObserver observer) {
18349        throw new UnsupportedOperationException(
18350                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18351    }
18352
18353    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18354        final PackageSetting ps;
18355        synchronized (mPackages) {
18356            ps = mSettings.mPackages.get(packageName);
18357            if (ps == null) {
18358                Slog.w(TAG, "Failed to find settings for " + packageName);
18359                return false;
18360            }
18361        }
18362
18363        final String[] packageNames = { packageName };
18364        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18365        final String[] codePaths = { ps.codePathString };
18366
18367        try {
18368            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18369                    ps.appId, ceDataInodes, codePaths, stats);
18370
18371            // For now, ignore code size of packages on system partition
18372            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18373                stats.codeSize = 0;
18374            }
18375
18376            // External clients expect these to be tracked separately
18377            stats.dataSize -= stats.cacheSize;
18378
18379        } catch (InstallerException e) {
18380            Slog.w(TAG, String.valueOf(e));
18381            return false;
18382        }
18383
18384        return true;
18385    }
18386
18387    private int getUidTargetSdkVersionLockedLPr(int uid) {
18388        Object obj = mSettings.getUserIdLPr(uid);
18389        if (obj instanceof SharedUserSetting) {
18390            final SharedUserSetting sus = (SharedUserSetting) obj;
18391            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18392            final Iterator<PackageSetting> it = sus.packages.iterator();
18393            while (it.hasNext()) {
18394                final PackageSetting ps = it.next();
18395                if (ps.pkg != null) {
18396                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18397                    if (v < vers) vers = v;
18398                }
18399            }
18400            return vers;
18401        } else if (obj instanceof PackageSetting) {
18402            final PackageSetting ps = (PackageSetting) obj;
18403            if (ps.pkg != null) {
18404                return ps.pkg.applicationInfo.targetSdkVersion;
18405            }
18406        }
18407        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18408    }
18409
18410    @Override
18411    public void addPreferredActivity(IntentFilter filter, int match,
18412            ComponentName[] set, ComponentName activity, int userId) {
18413        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18414                "Adding preferred");
18415    }
18416
18417    private void addPreferredActivityInternal(IntentFilter filter, int match,
18418            ComponentName[] set, ComponentName activity, boolean always, int userId,
18419            String opname) {
18420        // writer
18421        int callingUid = Binder.getCallingUid();
18422        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18423                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18424        if (filter.countActions() == 0) {
18425            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18426            return;
18427        }
18428        synchronized (mPackages) {
18429            if (mContext.checkCallingOrSelfPermission(
18430                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18431                    != PackageManager.PERMISSION_GRANTED) {
18432                if (getUidTargetSdkVersionLockedLPr(callingUid)
18433                        < Build.VERSION_CODES.FROYO) {
18434                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18435                            + callingUid);
18436                    return;
18437                }
18438                mContext.enforceCallingOrSelfPermission(
18439                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18440            }
18441
18442            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18443            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18444                    + userId + ":");
18445            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18446            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18447            scheduleWritePackageRestrictionsLocked(userId);
18448            postPreferredActivityChangedBroadcast(userId);
18449        }
18450    }
18451
18452    private void postPreferredActivityChangedBroadcast(int userId) {
18453        mHandler.post(() -> {
18454            final IActivityManager am = ActivityManager.getService();
18455            if (am == null) {
18456                return;
18457            }
18458
18459            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18460            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18461            try {
18462                am.broadcastIntent(null, intent, null, null,
18463                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18464                        null, false, false, userId);
18465            } catch (RemoteException e) {
18466            }
18467        });
18468    }
18469
18470    @Override
18471    public void replacePreferredActivity(IntentFilter filter, int match,
18472            ComponentName[] set, ComponentName activity, int userId) {
18473        if (filter.countActions() != 1) {
18474            throw new IllegalArgumentException(
18475                    "replacePreferredActivity expects filter to have only 1 action.");
18476        }
18477        if (filter.countDataAuthorities() != 0
18478                || filter.countDataPaths() != 0
18479                || filter.countDataSchemes() > 1
18480                || filter.countDataTypes() != 0) {
18481            throw new IllegalArgumentException(
18482                    "replacePreferredActivity expects filter to have no data authorities, " +
18483                    "paths, or types; and at most one scheme.");
18484        }
18485
18486        final int callingUid = Binder.getCallingUid();
18487        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18488                true /* requireFullPermission */, false /* checkShell */,
18489                "replace preferred activity");
18490        synchronized (mPackages) {
18491            if (mContext.checkCallingOrSelfPermission(
18492                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18493                    != PackageManager.PERMISSION_GRANTED) {
18494                if (getUidTargetSdkVersionLockedLPr(callingUid)
18495                        < Build.VERSION_CODES.FROYO) {
18496                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18497                            + Binder.getCallingUid());
18498                    return;
18499                }
18500                mContext.enforceCallingOrSelfPermission(
18501                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18502            }
18503
18504            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18505            if (pir != null) {
18506                // Get all of the existing entries that exactly match this filter.
18507                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18508                if (existing != null && existing.size() == 1) {
18509                    PreferredActivity cur = existing.get(0);
18510                    if (DEBUG_PREFERRED) {
18511                        Slog.i(TAG, "Checking replace of preferred:");
18512                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18513                        if (!cur.mPref.mAlways) {
18514                            Slog.i(TAG, "  -- CUR; not mAlways!");
18515                        } else {
18516                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18517                            Slog.i(TAG, "  -- CUR: mSet="
18518                                    + Arrays.toString(cur.mPref.mSetComponents));
18519                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18520                            Slog.i(TAG, "  -- NEW: mMatch="
18521                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18522                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18523                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18524                        }
18525                    }
18526                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18527                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18528                            && cur.mPref.sameSet(set)) {
18529                        // Setting the preferred activity to what it happens to be already
18530                        if (DEBUG_PREFERRED) {
18531                            Slog.i(TAG, "Replacing with same preferred activity "
18532                                    + cur.mPref.mShortComponent + " for user "
18533                                    + userId + ":");
18534                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18535                        }
18536                        return;
18537                    }
18538                }
18539
18540                if (existing != null) {
18541                    if (DEBUG_PREFERRED) {
18542                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18543                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18544                    }
18545                    for (int i = 0; i < existing.size(); i++) {
18546                        PreferredActivity pa = existing.get(i);
18547                        if (DEBUG_PREFERRED) {
18548                            Slog.i(TAG, "Removing existing preferred activity "
18549                                    + pa.mPref.mComponent + ":");
18550                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18551                        }
18552                        pir.removeFilter(pa);
18553                    }
18554                }
18555            }
18556            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18557                    "Replacing preferred");
18558        }
18559    }
18560
18561    @Override
18562    public void clearPackagePreferredActivities(String packageName) {
18563        final int callingUid = Binder.getCallingUid();
18564        if (getInstantAppPackageName(callingUid) != null) {
18565            return;
18566        }
18567        // writer
18568        synchronized (mPackages) {
18569            PackageParser.Package pkg = mPackages.get(packageName);
18570            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18571                if (mContext.checkCallingOrSelfPermission(
18572                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18573                        != PackageManager.PERMISSION_GRANTED) {
18574                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18575                            < Build.VERSION_CODES.FROYO) {
18576                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18577                                + callingUid);
18578                        return;
18579                    }
18580                    mContext.enforceCallingOrSelfPermission(
18581                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18582                }
18583            }
18584            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18585            if (ps != null
18586                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18587                return;
18588            }
18589            int user = UserHandle.getCallingUserId();
18590            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18591                scheduleWritePackageRestrictionsLocked(user);
18592            }
18593        }
18594    }
18595
18596    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18597    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18598        ArrayList<PreferredActivity> removed = null;
18599        boolean changed = false;
18600        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18601            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18602            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18603            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18604                continue;
18605            }
18606            Iterator<PreferredActivity> it = pir.filterIterator();
18607            while (it.hasNext()) {
18608                PreferredActivity pa = it.next();
18609                // Mark entry for removal only if it matches the package name
18610                // and the entry is of type "always".
18611                if (packageName == null ||
18612                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18613                                && pa.mPref.mAlways)) {
18614                    if (removed == null) {
18615                        removed = new ArrayList<PreferredActivity>();
18616                    }
18617                    removed.add(pa);
18618                }
18619            }
18620            if (removed != null) {
18621                for (int j=0; j<removed.size(); j++) {
18622                    PreferredActivity pa = removed.get(j);
18623                    pir.removeFilter(pa);
18624                }
18625                changed = true;
18626            }
18627        }
18628        if (changed) {
18629            postPreferredActivityChangedBroadcast(userId);
18630        }
18631        return changed;
18632    }
18633
18634    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18635    private void clearIntentFilterVerificationsLPw(int userId) {
18636        final int packageCount = mPackages.size();
18637        for (int i = 0; i < packageCount; i++) {
18638            PackageParser.Package pkg = mPackages.valueAt(i);
18639            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18640        }
18641    }
18642
18643    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18644    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18645        if (userId == UserHandle.USER_ALL) {
18646            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18647                    sUserManager.getUserIds())) {
18648                for (int oneUserId : sUserManager.getUserIds()) {
18649                    scheduleWritePackageRestrictionsLocked(oneUserId);
18650                }
18651            }
18652        } else {
18653            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18654                scheduleWritePackageRestrictionsLocked(userId);
18655            }
18656        }
18657    }
18658
18659    /** Clears state for all users, and touches intent filter verification policy */
18660    void clearDefaultBrowserIfNeeded(String packageName) {
18661        for (int oneUserId : sUserManager.getUserIds()) {
18662            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
18663        }
18664    }
18665
18666    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
18667        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
18668        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
18669            if (packageName.equals(defaultBrowserPackageName)) {
18670                setDefaultBrowserPackageName(null, userId);
18671            }
18672        }
18673    }
18674
18675    @Override
18676    public void resetApplicationPreferences(int userId) {
18677        mContext.enforceCallingOrSelfPermission(
18678                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18679        final long identity = Binder.clearCallingIdentity();
18680        // writer
18681        try {
18682            synchronized (mPackages) {
18683                clearPackagePreferredActivitiesLPw(null, userId);
18684                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18685                // TODO: We have to reset the default SMS and Phone. This requires
18686                // significant refactoring to keep all default apps in the package
18687                // manager (cleaner but more work) or have the services provide
18688                // callbacks to the package manager to request a default app reset.
18689                applyFactoryDefaultBrowserLPw(userId);
18690                clearIntentFilterVerificationsLPw(userId);
18691                primeDomainVerificationsLPw(userId);
18692                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18693                scheduleWritePackageRestrictionsLocked(userId);
18694            }
18695            resetNetworkPolicies(userId);
18696        } finally {
18697            Binder.restoreCallingIdentity(identity);
18698        }
18699    }
18700
18701    @Override
18702    public int getPreferredActivities(List<IntentFilter> outFilters,
18703            List<ComponentName> outActivities, String packageName) {
18704        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
18705            return 0;
18706        }
18707        int num = 0;
18708        final int userId = UserHandle.getCallingUserId();
18709        // reader
18710        synchronized (mPackages) {
18711            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18712            if (pir != null) {
18713                final Iterator<PreferredActivity> it = pir.filterIterator();
18714                while (it.hasNext()) {
18715                    final PreferredActivity pa = it.next();
18716                    if (packageName == null
18717                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18718                                    && pa.mPref.mAlways)) {
18719                        if (outFilters != null) {
18720                            outFilters.add(new IntentFilter(pa));
18721                        }
18722                        if (outActivities != null) {
18723                            outActivities.add(pa.mPref.mComponent);
18724                        }
18725                    }
18726                }
18727            }
18728        }
18729
18730        return num;
18731    }
18732
18733    @Override
18734    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18735            int userId) {
18736        int callingUid = Binder.getCallingUid();
18737        if (callingUid != Process.SYSTEM_UID) {
18738            throw new SecurityException(
18739                    "addPersistentPreferredActivity can only be run by the system");
18740        }
18741        if (filter.countActions() == 0) {
18742            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18743            return;
18744        }
18745        synchronized (mPackages) {
18746            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18747                    ":");
18748            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18749            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18750                    new PersistentPreferredActivity(filter, activity));
18751            scheduleWritePackageRestrictionsLocked(userId);
18752            postPreferredActivityChangedBroadcast(userId);
18753        }
18754    }
18755
18756    @Override
18757    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18758        int callingUid = Binder.getCallingUid();
18759        if (callingUid != Process.SYSTEM_UID) {
18760            throw new SecurityException(
18761                    "clearPackagePersistentPreferredActivities can only be run by the system");
18762        }
18763        ArrayList<PersistentPreferredActivity> removed = null;
18764        boolean changed = false;
18765        synchronized (mPackages) {
18766            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18767                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18768                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18769                        .valueAt(i);
18770                if (userId != thisUserId) {
18771                    continue;
18772                }
18773                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18774                while (it.hasNext()) {
18775                    PersistentPreferredActivity ppa = it.next();
18776                    // Mark entry for removal only if it matches the package name.
18777                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18778                        if (removed == null) {
18779                            removed = new ArrayList<PersistentPreferredActivity>();
18780                        }
18781                        removed.add(ppa);
18782                    }
18783                }
18784                if (removed != null) {
18785                    for (int j=0; j<removed.size(); j++) {
18786                        PersistentPreferredActivity ppa = removed.get(j);
18787                        ppir.removeFilter(ppa);
18788                    }
18789                    changed = true;
18790                }
18791            }
18792
18793            if (changed) {
18794                scheduleWritePackageRestrictionsLocked(userId);
18795                postPreferredActivityChangedBroadcast(userId);
18796            }
18797        }
18798    }
18799
18800    /**
18801     * Common machinery for picking apart a restored XML blob and passing
18802     * it to a caller-supplied functor to be applied to the running system.
18803     */
18804    private void restoreFromXml(XmlPullParser parser, int userId,
18805            String expectedStartTag, BlobXmlRestorer functor)
18806            throws IOException, XmlPullParserException {
18807        int type;
18808        while ((type = parser.next()) != XmlPullParser.START_TAG
18809                && type != XmlPullParser.END_DOCUMENT) {
18810        }
18811        if (type != XmlPullParser.START_TAG) {
18812            // oops didn't find a start tag?!
18813            if (DEBUG_BACKUP) {
18814                Slog.e(TAG, "Didn't find start tag during restore");
18815            }
18816            return;
18817        }
18818Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18819        // this is supposed to be TAG_PREFERRED_BACKUP
18820        if (!expectedStartTag.equals(parser.getName())) {
18821            if (DEBUG_BACKUP) {
18822                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18823            }
18824            return;
18825        }
18826
18827        // skip interfering stuff, then we're aligned with the backing implementation
18828        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18829Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18830        functor.apply(parser, userId);
18831    }
18832
18833    private interface BlobXmlRestorer {
18834        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18835    }
18836
18837    /**
18838     * Non-Binder method, support for the backup/restore mechanism: write the
18839     * full set of preferred activities in its canonical XML format.  Returns the
18840     * XML output as a byte array, or null if there is none.
18841     */
18842    @Override
18843    public byte[] getPreferredActivityBackup(int userId) {
18844        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18845            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18846        }
18847
18848        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18849        try {
18850            final XmlSerializer serializer = new FastXmlSerializer();
18851            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18852            serializer.startDocument(null, true);
18853            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18854
18855            synchronized (mPackages) {
18856                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18857            }
18858
18859            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18860            serializer.endDocument();
18861            serializer.flush();
18862        } catch (Exception e) {
18863            if (DEBUG_BACKUP) {
18864                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18865            }
18866            return null;
18867        }
18868
18869        return dataStream.toByteArray();
18870    }
18871
18872    @Override
18873    public void restorePreferredActivities(byte[] backup, int userId) {
18874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18875            throw new SecurityException("Only the system may call restorePreferredActivities()");
18876        }
18877
18878        try {
18879            final XmlPullParser parser = Xml.newPullParser();
18880            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18881            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18882                    new BlobXmlRestorer() {
18883                        @Override
18884                        public void apply(XmlPullParser parser, int userId)
18885                                throws XmlPullParserException, IOException {
18886                            synchronized (mPackages) {
18887                                mSettings.readPreferredActivitiesLPw(parser, userId);
18888                            }
18889                        }
18890                    } );
18891        } catch (Exception e) {
18892            if (DEBUG_BACKUP) {
18893                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18894            }
18895        }
18896    }
18897
18898    /**
18899     * Non-Binder method, support for the backup/restore mechanism: write the
18900     * default browser (etc) settings in its canonical XML format.  Returns the default
18901     * browser XML representation as a byte array, or null if there is none.
18902     */
18903    @Override
18904    public byte[] getDefaultAppsBackup(int userId) {
18905        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18906            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18907        }
18908
18909        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18910        try {
18911            final XmlSerializer serializer = new FastXmlSerializer();
18912            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18913            serializer.startDocument(null, true);
18914            serializer.startTag(null, TAG_DEFAULT_APPS);
18915
18916            synchronized (mPackages) {
18917                mSettings.writeDefaultAppsLPr(serializer, userId);
18918            }
18919
18920            serializer.endTag(null, TAG_DEFAULT_APPS);
18921            serializer.endDocument();
18922            serializer.flush();
18923        } catch (Exception e) {
18924            if (DEBUG_BACKUP) {
18925                Slog.e(TAG, "Unable to write default apps for backup", e);
18926            }
18927            return null;
18928        }
18929
18930        return dataStream.toByteArray();
18931    }
18932
18933    @Override
18934    public void restoreDefaultApps(byte[] backup, int userId) {
18935        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18936            throw new SecurityException("Only the system may call restoreDefaultApps()");
18937        }
18938
18939        try {
18940            final XmlPullParser parser = Xml.newPullParser();
18941            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18942            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18943                    new BlobXmlRestorer() {
18944                        @Override
18945                        public void apply(XmlPullParser parser, int userId)
18946                                throws XmlPullParserException, IOException {
18947                            synchronized (mPackages) {
18948                                mSettings.readDefaultAppsLPw(parser, userId);
18949                            }
18950                        }
18951                    } );
18952        } catch (Exception e) {
18953            if (DEBUG_BACKUP) {
18954                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18955            }
18956        }
18957    }
18958
18959    @Override
18960    public byte[] getIntentFilterVerificationBackup(int userId) {
18961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18962            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18963        }
18964
18965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18966        try {
18967            final XmlSerializer serializer = new FastXmlSerializer();
18968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18969            serializer.startDocument(null, true);
18970            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18971
18972            synchronized (mPackages) {
18973                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18974            }
18975
18976            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18977            serializer.endDocument();
18978            serializer.flush();
18979        } catch (Exception e) {
18980            if (DEBUG_BACKUP) {
18981                Slog.e(TAG, "Unable to write default apps for backup", e);
18982            }
18983            return null;
18984        }
18985
18986        return dataStream.toByteArray();
18987    }
18988
18989    @Override
18990    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18992            throw new SecurityException("Only the system may call restorePreferredActivities()");
18993        }
18994
18995        try {
18996            final XmlPullParser parser = Xml.newPullParser();
18997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18998            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18999                    new BlobXmlRestorer() {
19000                        @Override
19001                        public void apply(XmlPullParser parser, int userId)
19002                                throws XmlPullParserException, IOException {
19003                            synchronized (mPackages) {
19004                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19005                                mSettings.writeLPr();
19006                            }
19007                        }
19008                    } );
19009        } catch (Exception e) {
19010            if (DEBUG_BACKUP) {
19011                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19012            }
19013        }
19014    }
19015
19016    @Override
19017    public byte[] getPermissionGrantBackup(int userId) {
19018        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19019            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19020        }
19021
19022        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19023        try {
19024            final XmlSerializer serializer = new FastXmlSerializer();
19025            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19026            serializer.startDocument(null, true);
19027            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19028
19029            synchronized (mPackages) {
19030                serializeRuntimePermissionGrantsLPr(serializer, userId);
19031            }
19032
19033            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19034            serializer.endDocument();
19035            serializer.flush();
19036        } catch (Exception e) {
19037            if (DEBUG_BACKUP) {
19038                Slog.e(TAG, "Unable to write default apps for backup", e);
19039            }
19040            return null;
19041        }
19042
19043        return dataStream.toByteArray();
19044    }
19045
19046    @Override
19047    public void restorePermissionGrants(byte[] backup, int userId) {
19048        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19049            throw new SecurityException("Only the system may call restorePermissionGrants()");
19050        }
19051
19052        try {
19053            final XmlPullParser parser = Xml.newPullParser();
19054            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19055            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19056                    new BlobXmlRestorer() {
19057                        @Override
19058                        public void apply(XmlPullParser parser, int userId)
19059                                throws XmlPullParserException, IOException {
19060                            synchronized (mPackages) {
19061                                processRestoredPermissionGrantsLPr(parser, userId);
19062                            }
19063                        }
19064                    } );
19065        } catch (Exception e) {
19066            if (DEBUG_BACKUP) {
19067                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19068            }
19069        }
19070    }
19071
19072    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19073            throws IOException {
19074        serializer.startTag(null, TAG_ALL_GRANTS);
19075
19076        final int N = mSettings.mPackages.size();
19077        for (int i = 0; i < N; i++) {
19078            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19079            boolean pkgGrantsKnown = false;
19080
19081            PermissionsState packagePerms = ps.getPermissionsState();
19082
19083            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19084                final int grantFlags = state.getFlags();
19085                // only look at grants that are not system/policy fixed
19086                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19087                    final boolean isGranted = state.isGranted();
19088                    // And only back up the user-twiddled state bits
19089                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19090                        final String packageName = mSettings.mPackages.keyAt(i);
19091                        if (!pkgGrantsKnown) {
19092                            serializer.startTag(null, TAG_GRANT);
19093                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19094                            pkgGrantsKnown = true;
19095                        }
19096
19097                        final boolean userSet =
19098                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19099                        final boolean userFixed =
19100                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19101                        final boolean revoke =
19102                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19103
19104                        serializer.startTag(null, TAG_PERMISSION);
19105                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19106                        if (isGranted) {
19107                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19108                        }
19109                        if (userSet) {
19110                            serializer.attribute(null, ATTR_USER_SET, "true");
19111                        }
19112                        if (userFixed) {
19113                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19114                        }
19115                        if (revoke) {
19116                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19117                        }
19118                        serializer.endTag(null, TAG_PERMISSION);
19119                    }
19120                }
19121            }
19122
19123            if (pkgGrantsKnown) {
19124                serializer.endTag(null, TAG_GRANT);
19125            }
19126        }
19127
19128        serializer.endTag(null, TAG_ALL_GRANTS);
19129    }
19130
19131    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19132            throws XmlPullParserException, IOException {
19133        String pkgName = null;
19134        int outerDepth = parser.getDepth();
19135        int type;
19136        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19137                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19138            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19139                continue;
19140            }
19141
19142            final String tagName = parser.getName();
19143            if (tagName.equals(TAG_GRANT)) {
19144                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19145                if (DEBUG_BACKUP) {
19146                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19147                }
19148            } else if (tagName.equals(TAG_PERMISSION)) {
19149
19150                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19151                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19152
19153                int newFlagSet = 0;
19154                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19155                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19156                }
19157                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19158                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19159                }
19160                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19161                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19162                }
19163                if (DEBUG_BACKUP) {
19164                    Slog.v(TAG, "  + Restoring grant:"
19165                            + " pkg=" + pkgName
19166                            + " perm=" + permName
19167                            + " granted=" + isGranted
19168                            + " bits=0x" + Integer.toHexString(newFlagSet));
19169                }
19170                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19171                if (ps != null) {
19172                    // Already installed so we apply the grant immediately
19173                    if (DEBUG_BACKUP) {
19174                        Slog.v(TAG, "        + already installed; applying");
19175                    }
19176                    PermissionsState perms = ps.getPermissionsState();
19177                    BasePermission bp =
19178                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19179                    if (bp != null) {
19180                        if (isGranted) {
19181                            perms.grantRuntimePermission(bp, userId);
19182                        }
19183                        if (newFlagSet != 0) {
19184                            perms.updatePermissionFlags(
19185                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19186                        }
19187                    }
19188                } else {
19189                    // Need to wait for post-restore install to apply the grant
19190                    if (DEBUG_BACKUP) {
19191                        Slog.v(TAG, "        - not yet installed; saving for later");
19192                    }
19193                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19194                            isGranted, newFlagSet, userId);
19195                }
19196            } else {
19197                PackageManagerService.reportSettingsProblem(Log.WARN,
19198                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19199                XmlUtils.skipCurrentTag(parser);
19200            }
19201        }
19202
19203        scheduleWriteSettingsLocked();
19204        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19205    }
19206
19207    @Override
19208    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19209            int sourceUserId, int targetUserId, int flags) {
19210        mContext.enforceCallingOrSelfPermission(
19211                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19212        int callingUid = Binder.getCallingUid();
19213        enforceOwnerRights(ownerPackage, callingUid);
19214        PackageManagerServiceUtils.enforceShellRestriction(
19215                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19216        if (intentFilter.countActions() == 0) {
19217            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19218            return;
19219        }
19220        synchronized (mPackages) {
19221            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19222                    ownerPackage, targetUserId, flags);
19223            CrossProfileIntentResolver resolver =
19224                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19225            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19226            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19227            if (existing != null) {
19228                int size = existing.size();
19229                for (int i = 0; i < size; i++) {
19230                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19231                        return;
19232                    }
19233                }
19234            }
19235            resolver.addFilter(newFilter);
19236            scheduleWritePackageRestrictionsLocked(sourceUserId);
19237        }
19238    }
19239
19240    @Override
19241    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19242        mContext.enforceCallingOrSelfPermission(
19243                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19244        final int callingUid = Binder.getCallingUid();
19245        enforceOwnerRights(ownerPackage, callingUid);
19246        PackageManagerServiceUtils.enforceShellRestriction(
19247                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19248        synchronized (mPackages) {
19249            CrossProfileIntentResolver resolver =
19250                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19251            ArraySet<CrossProfileIntentFilter> set =
19252                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19253            for (CrossProfileIntentFilter filter : set) {
19254                if (filter.getOwnerPackage().equals(ownerPackage)) {
19255                    resolver.removeFilter(filter);
19256                }
19257            }
19258            scheduleWritePackageRestrictionsLocked(sourceUserId);
19259        }
19260    }
19261
19262    // Enforcing that callingUid is owning pkg on userId
19263    private void enforceOwnerRights(String pkg, int callingUid) {
19264        // The system owns everything.
19265        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19266            return;
19267        }
19268        final int callingUserId = UserHandle.getUserId(callingUid);
19269        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19270        if (pi == null) {
19271            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19272                    + callingUserId);
19273        }
19274        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19275            throw new SecurityException("Calling uid " + callingUid
19276                    + " does not own package " + pkg);
19277        }
19278    }
19279
19280    @Override
19281    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19282        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19283            return null;
19284        }
19285        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19286    }
19287
19288    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19289        UserManagerService ums = UserManagerService.getInstance();
19290        if (ums != null) {
19291            final UserInfo parent = ums.getProfileParent(userId);
19292            final int launcherUid = (parent != null) ? parent.id : userId;
19293            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19294            if (launcherComponent != null) {
19295                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19296                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19297                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19298                        .setPackage(launcherComponent.getPackageName());
19299                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19300            }
19301        }
19302    }
19303
19304    /**
19305     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19306     * then reports the most likely home activity or null if there are more than one.
19307     */
19308    private ComponentName getDefaultHomeActivity(int userId) {
19309        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19310        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19311        if (cn != null) {
19312            return cn;
19313        }
19314
19315        // Find the launcher with the highest priority and return that component if there are no
19316        // other home activity with the same priority.
19317        int lastPriority = Integer.MIN_VALUE;
19318        ComponentName lastComponent = null;
19319        final int size = allHomeCandidates.size();
19320        for (int i = 0; i < size; i++) {
19321            final ResolveInfo ri = allHomeCandidates.get(i);
19322            if (ri.priority > lastPriority) {
19323                lastComponent = ri.activityInfo.getComponentName();
19324                lastPriority = ri.priority;
19325            } else if (ri.priority == lastPriority) {
19326                // Two components found with same priority.
19327                lastComponent = null;
19328            }
19329        }
19330        return lastComponent;
19331    }
19332
19333    private Intent getHomeIntent() {
19334        Intent intent = new Intent(Intent.ACTION_MAIN);
19335        intent.addCategory(Intent.CATEGORY_HOME);
19336        intent.addCategory(Intent.CATEGORY_DEFAULT);
19337        return intent;
19338    }
19339
19340    private IntentFilter getHomeFilter() {
19341        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19342        filter.addCategory(Intent.CATEGORY_HOME);
19343        filter.addCategory(Intent.CATEGORY_DEFAULT);
19344        return filter;
19345    }
19346
19347    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19348            int userId) {
19349        Intent intent  = getHomeIntent();
19350        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19351                PackageManager.GET_META_DATA, userId);
19352        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19353                true, false, false, userId);
19354
19355        allHomeCandidates.clear();
19356        if (list != null) {
19357            for (ResolveInfo ri : list) {
19358                allHomeCandidates.add(ri);
19359            }
19360        }
19361        return (preferred == null || preferred.activityInfo == null)
19362                ? null
19363                : new ComponentName(preferred.activityInfo.packageName,
19364                        preferred.activityInfo.name);
19365    }
19366
19367    @Override
19368    public void setHomeActivity(ComponentName comp, int userId) {
19369        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19370            return;
19371        }
19372        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19373        getHomeActivitiesAsUser(homeActivities, userId);
19374
19375        boolean found = false;
19376
19377        final int size = homeActivities.size();
19378        final ComponentName[] set = new ComponentName[size];
19379        for (int i = 0; i < size; i++) {
19380            final ResolveInfo candidate = homeActivities.get(i);
19381            final ActivityInfo info = candidate.activityInfo;
19382            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19383            set[i] = activityName;
19384            if (!found && activityName.equals(comp)) {
19385                found = true;
19386            }
19387        }
19388        if (!found) {
19389            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19390                    + userId);
19391        }
19392        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19393                set, comp, userId);
19394    }
19395
19396    private @Nullable String getSetupWizardPackageName() {
19397        final Intent intent = new Intent(Intent.ACTION_MAIN);
19398        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19399
19400        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19401                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19402                        | MATCH_DISABLED_COMPONENTS,
19403                UserHandle.myUserId());
19404        if (matches.size() == 1) {
19405            return matches.get(0).getComponentInfo().packageName;
19406        } else {
19407            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19408                    + ": matches=" + matches);
19409            return null;
19410        }
19411    }
19412
19413    private @Nullable String getStorageManagerPackageName() {
19414        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19415
19416        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19417                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19418                        | MATCH_DISABLED_COMPONENTS,
19419                UserHandle.myUserId());
19420        if (matches.size() == 1) {
19421            return matches.get(0).getComponentInfo().packageName;
19422        } else {
19423            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19424                    + matches.size() + ": matches=" + matches);
19425            return null;
19426        }
19427    }
19428
19429    @Override
19430    public void setApplicationEnabledSetting(String appPackageName,
19431            int newState, int flags, int userId, String callingPackage) {
19432        if (!sUserManager.exists(userId)) return;
19433        if (callingPackage == null) {
19434            callingPackage = Integer.toString(Binder.getCallingUid());
19435        }
19436        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19437    }
19438
19439    @Override
19440    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19441        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19442        synchronized (mPackages) {
19443            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19444            if (pkgSetting != null) {
19445                pkgSetting.setUpdateAvailable(updateAvailable);
19446            }
19447        }
19448    }
19449
19450    @Override
19451    public void setComponentEnabledSetting(ComponentName componentName,
19452            int newState, int flags, int userId) {
19453        if (!sUserManager.exists(userId)) return;
19454        setEnabledSetting(componentName.getPackageName(),
19455                componentName.getClassName(), newState, flags, userId, null);
19456    }
19457
19458    private void setEnabledSetting(final String packageName, String className, int newState,
19459            final int flags, int userId, String callingPackage) {
19460        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19461              || newState == COMPONENT_ENABLED_STATE_ENABLED
19462              || newState == COMPONENT_ENABLED_STATE_DISABLED
19463              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19464              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19465            throw new IllegalArgumentException("Invalid new component state: "
19466                    + newState);
19467        }
19468        PackageSetting pkgSetting;
19469        final int callingUid = Binder.getCallingUid();
19470        final int permission;
19471        if (callingUid == Process.SYSTEM_UID) {
19472            permission = PackageManager.PERMISSION_GRANTED;
19473        } else {
19474            permission = mContext.checkCallingOrSelfPermission(
19475                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19476        }
19477        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19478                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19479        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19480        boolean sendNow = false;
19481        boolean isApp = (className == null);
19482        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19483        String componentName = isApp ? packageName : className;
19484        int packageUid = -1;
19485        ArrayList<String> components;
19486
19487        // reader
19488        synchronized (mPackages) {
19489            pkgSetting = mSettings.mPackages.get(packageName);
19490            if (pkgSetting == null) {
19491                if (!isCallerInstantApp) {
19492                    if (className == null) {
19493                        throw new IllegalArgumentException("Unknown package: " + packageName);
19494                    }
19495                    throw new IllegalArgumentException(
19496                            "Unknown component: " + packageName + "/" + className);
19497                } else {
19498                    // throw SecurityException to prevent leaking package information
19499                    throw new SecurityException(
19500                            "Attempt to change component state; "
19501                            + "pid=" + Binder.getCallingPid()
19502                            + ", uid=" + callingUid
19503                            + (className == null
19504                                    ? ", package=" + packageName
19505                                    : ", component=" + packageName + "/" + className));
19506                }
19507            }
19508        }
19509
19510        // Limit who can change which apps
19511        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19512            // Don't allow apps that don't have permission to modify other apps
19513            if (!allowedByPermission
19514                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19515                throw new SecurityException(
19516                        "Attempt to change component state; "
19517                        + "pid=" + Binder.getCallingPid()
19518                        + ", uid=" + callingUid
19519                        + (className == null
19520                                ? ", package=" + packageName
19521                                : ", component=" + packageName + "/" + className));
19522            }
19523            // Don't allow changing protected packages.
19524            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19525                throw new SecurityException("Cannot disable a protected package: " + packageName);
19526            }
19527        }
19528
19529        synchronized (mPackages) {
19530            if (callingUid == Process.SHELL_UID
19531                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19532                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19533                // unless it is a test package.
19534                int oldState = pkgSetting.getEnabled(userId);
19535                if (className == null
19536                        &&
19537                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19538                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19539                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19540                        &&
19541                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19542                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19543                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19544                    // ok
19545                } else {
19546                    throw new SecurityException(
19547                            "Shell cannot change component state for " + packageName + "/"
19548                                    + className + " to " + newState);
19549                }
19550            }
19551        }
19552        if (className == null) {
19553            // We're dealing with an application/package level state change
19554            synchronized (mPackages) {
19555                if (pkgSetting.getEnabled(userId) == newState) {
19556                    // Nothing to do
19557                    return;
19558                }
19559            }
19560            // If we're enabling a system stub, there's a little more work to do.
19561            // Prior to enabling the package, we need to decompress the APK(s) to the
19562            // data partition and then replace the version on the system partition.
19563            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19564            final boolean isSystemStub = deletedPkg.isStub
19565                    && deletedPkg.isSystem();
19566            if (isSystemStub
19567                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19568                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19569                final File codePath = decompressPackage(deletedPkg);
19570                if (codePath == null) {
19571                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19572                    return;
19573                }
19574                // TODO remove direct parsing of the package object during internal cleanup
19575                // of scan package
19576                // We need to call parse directly here for no other reason than we need
19577                // the new package in order to disable the old one [we use the information
19578                // for some internal optimization to optionally create a new package setting
19579                // object on replace]. However, we can't get the package from the scan
19580                // because the scan modifies live structures and we need to remove the
19581                // old [system] package from the system before a scan can be attempted.
19582                // Once scan is indempotent we can remove this parse and use the package
19583                // object we scanned, prior to adding it to package settings.
19584                final PackageParser pp = new PackageParser();
19585                pp.setSeparateProcesses(mSeparateProcesses);
19586                pp.setDisplayMetrics(mMetrics);
19587                pp.setCallback(mPackageParserCallback);
19588                final PackageParser.Package tmpPkg;
19589                try {
19590                    final int parseFlags = mDefParseFlags
19591                            | PackageParser.PARSE_MUST_BE_APK
19592                            | PackageParser.PARSE_IS_SYSTEM
19593                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19594                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19595                } catch (PackageParserException e) {
19596                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19597                    return;
19598                }
19599                synchronized (mInstallLock) {
19600                    // Disable the stub and remove any package entries
19601                    removePackageLI(deletedPkg, true);
19602                    synchronized (mPackages) {
19603                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19604                    }
19605                    final PackageParser.Package pkg;
19606                    try (PackageFreezer freezer =
19607                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19608                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
19609                                | PackageParser.PARSE_ENFORCE_CODE;
19610                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
19611                                0 /*currentTime*/, null /*user*/);
19612                        prepareAppDataAfterInstallLIF(pkg);
19613                        synchronized (mPackages) {
19614                            try {
19615                                updateSharedLibrariesLPr(pkg, null);
19616                            } catch (PackageManagerException e) {
19617                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
19618                            }
19619                            mPermissionManager.updatePermissions(
19620                                    pkg.packageName, pkg, true, mPackages.values(),
19621                                    mPermissionCallback);
19622                            mSettings.writeLPr();
19623                        }
19624                    } catch (PackageManagerException e) {
19625                        // Whoops! Something went wrong; try to roll back to the stub
19626                        Slog.w(TAG, "Failed to install compressed system package:"
19627                                + pkgSetting.name, e);
19628                        // Remove the failed install
19629                        removeCodePathLI(codePath);
19630
19631                        // Install the system package
19632                        try (PackageFreezer freezer =
19633                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19634                            synchronized (mPackages) {
19635                                // NOTE: The system package always needs to be enabled; even
19636                                // if it's for a compressed stub. If we don't, installing the
19637                                // system package fails during scan [scanning checks the disabled
19638                                // packages]. We will reverse this later, after we've "installed"
19639                                // the stub.
19640                                // This leaves us in a fragile state; the stub should never be
19641                                // enabled, so, cross your fingers and hope nothing goes wrong
19642                                // until we can disable the package later.
19643                                enableSystemPackageLPw(deletedPkg);
19644                            }
19645                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
19646                                    false /*isPrivileged*/, null /*allUserHandles*/,
19647                                    null /*origUserHandles*/, null /*origPermissionsState*/,
19648                                    true /*writeSettings*/);
19649                        } catch (PackageManagerException pme) {
19650                            Slog.w(TAG, "Failed to restore system package:"
19651                                    + deletedPkg.packageName, pme);
19652                        } finally {
19653                            synchronized (mPackages) {
19654                                mSettings.disableSystemPackageLPw(
19655                                        deletedPkg.packageName, true /*replaced*/);
19656                                mSettings.writeLPr();
19657                            }
19658                        }
19659                        return;
19660                    }
19661                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
19662                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19663                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19664                    mDexManager.notifyPackageUpdated(pkg.packageName,
19665                            pkg.baseCodePath, pkg.splitCodePaths);
19666                }
19667            }
19668            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19669                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19670                // Don't care about who enables an app.
19671                callingPackage = null;
19672            }
19673            synchronized (mPackages) {
19674                pkgSetting.setEnabled(newState, userId, callingPackage);
19675            }
19676        } else {
19677            synchronized (mPackages) {
19678                // We're dealing with a component level state change
19679                // First, verify that this is a valid class name.
19680                PackageParser.Package pkg = pkgSetting.pkg;
19681                if (pkg == null || !pkg.hasComponentClassName(className)) {
19682                    if (pkg != null &&
19683                            pkg.applicationInfo.targetSdkVersion >=
19684                                    Build.VERSION_CODES.JELLY_BEAN) {
19685                        throw new IllegalArgumentException("Component class " + className
19686                                + " does not exist in " + packageName);
19687                    } else {
19688                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19689                                + className + " does not exist in " + packageName);
19690                    }
19691                }
19692                switch (newState) {
19693                    case COMPONENT_ENABLED_STATE_ENABLED:
19694                        if (!pkgSetting.enableComponentLPw(className, userId)) {
19695                            return;
19696                        }
19697                        break;
19698                    case COMPONENT_ENABLED_STATE_DISABLED:
19699                        if (!pkgSetting.disableComponentLPw(className, userId)) {
19700                            return;
19701                        }
19702                        break;
19703                    case COMPONENT_ENABLED_STATE_DEFAULT:
19704                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
19705                            return;
19706                        }
19707                        break;
19708                    default:
19709                        Slog.e(TAG, "Invalid new component state: " + newState);
19710                        return;
19711                }
19712            }
19713        }
19714        synchronized (mPackages) {
19715            scheduleWritePackageRestrictionsLocked(userId);
19716            updateSequenceNumberLP(pkgSetting, new int[] { userId });
19717            final long callingId = Binder.clearCallingIdentity();
19718            try {
19719                updateInstantAppInstallerLocked(packageName);
19720            } finally {
19721                Binder.restoreCallingIdentity(callingId);
19722            }
19723            components = mPendingBroadcasts.get(userId, packageName);
19724            final boolean newPackage = components == null;
19725            if (newPackage) {
19726                components = new ArrayList<String>();
19727            }
19728            if (!components.contains(componentName)) {
19729                components.add(componentName);
19730            }
19731            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19732                sendNow = true;
19733                // Purge entry from pending broadcast list if another one exists already
19734                // since we are sending one right away.
19735                mPendingBroadcasts.remove(userId, packageName);
19736            } else {
19737                if (newPackage) {
19738                    mPendingBroadcasts.put(userId, packageName, components);
19739                }
19740                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19741                    // Schedule a message
19742                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19743                }
19744            }
19745        }
19746
19747        long callingId = Binder.clearCallingIdentity();
19748        try {
19749            if (sendNow) {
19750                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19751                sendPackageChangedBroadcast(packageName,
19752                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19753            }
19754        } finally {
19755            Binder.restoreCallingIdentity(callingId);
19756        }
19757    }
19758
19759    @Override
19760    public void flushPackageRestrictionsAsUser(int userId) {
19761        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19762            return;
19763        }
19764        if (!sUserManager.exists(userId)) {
19765            return;
19766        }
19767        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19768                false /* checkShell */, "flushPackageRestrictions");
19769        synchronized (mPackages) {
19770            mSettings.writePackageRestrictionsLPr(userId);
19771            mDirtyUsers.remove(userId);
19772            if (mDirtyUsers.isEmpty()) {
19773                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19774            }
19775        }
19776    }
19777
19778    private void sendPackageChangedBroadcast(String packageName,
19779            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19780        if (DEBUG_INSTALL)
19781            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19782                    + componentNames);
19783        Bundle extras = new Bundle(4);
19784        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19785        String nameList[] = new String[componentNames.size()];
19786        componentNames.toArray(nameList);
19787        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19788        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19789        extras.putInt(Intent.EXTRA_UID, packageUid);
19790        // If this is not reporting a change of the overall package, then only send it
19791        // to registered receivers.  We don't want to launch a swath of apps for every
19792        // little component state change.
19793        final int flags = !componentNames.contains(packageName)
19794                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19795        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19796                new int[] {UserHandle.getUserId(packageUid)});
19797    }
19798
19799    @Override
19800    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19801        if (!sUserManager.exists(userId)) return;
19802        final int callingUid = Binder.getCallingUid();
19803        if (getInstantAppPackageName(callingUid) != null) {
19804            return;
19805        }
19806        final int permission = mContext.checkCallingOrSelfPermission(
19807                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19808        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19809        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19810                true /* requireFullPermission */, true /* checkShell */, "stop package");
19811        // writer
19812        synchronized (mPackages) {
19813            final PackageSetting ps = mSettings.mPackages.get(packageName);
19814            if (!filterAppAccessLPr(ps, callingUid, userId)
19815                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19816                            allowedByPermission, callingUid, userId)) {
19817                scheduleWritePackageRestrictionsLocked(userId);
19818            }
19819        }
19820    }
19821
19822    @Override
19823    public String getInstallerPackageName(String packageName) {
19824        final int callingUid = Binder.getCallingUid();
19825        if (getInstantAppPackageName(callingUid) != null) {
19826            return null;
19827        }
19828        // reader
19829        synchronized (mPackages) {
19830            final PackageSetting ps = mSettings.mPackages.get(packageName);
19831            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19832                return null;
19833            }
19834            return mSettings.getInstallerPackageNameLPr(packageName);
19835        }
19836    }
19837
19838    public boolean isOrphaned(String packageName) {
19839        // reader
19840        synchronized (mPackages) {
19841            return mSettings.isOrphaned(packageName);
19842        }
19843    }
19844
19845    @Override
19846    public int getApplicationEnabledSetting(String packageName, int userId) {
19847        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19848        int callingUid = Binder.getCallingUid();
19849        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19850                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19851        // reader
19852        synchronized (mPackages) {
19853            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
19854                return COMPONENT_ENABLED_STATE_DISABLED;
19855            }
19856            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19857        }
19858    }
19859
19860    @Override
19861    public int getComponentEnabledSetting(ComponentName component, int userId) {
19862        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19863        int callingUid = Binder.getCallingUid();
19864        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19865                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
19866        synchronized (mPackages) {
19867            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
19868                    component, TYPE_UNKNOWN, userId)) {
19869                return COMPONENT_ENABLED_STATE_DISABLED;
19870            }
19871            return mSettings.getComponentEnabledSettingLPr(component, userId);
19872        }
19873    }
19874
19875    @Override
19876    public void enterSafeMode() {
19877        enforceSystemOrRoot("Only the system can request entering safe mode");
19878
19879        if (!mSystemReady) {
19880            mSafeMode = true;
19881        }
19882    }
19883
19884    @Override
19885    public void systemReady() {
19886        enforceSystemOrRoot("Only the system can claim the system is ready");
19887
19888        mSystemReady = true;
19889        final ContentResolver resolver = mContext.getContentResolver();
19890        ContentObserver co = new ContentObserver(mHandler) {
19891            @Override
19892            public void onChange(boolean selfChange) {
19893                mEphemeralAppsDisabled =
19894                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
19895                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
19896            }
19897        };
19898        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19899                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
19900                false, co, UserHandle.USER_SYSTEM);
19901        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19902                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
19903        co.onChange(true);
19904
19905        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
19906        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
19907        // it is done.
19908        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
19909            @Override
19910            public void onChange(boolean selfChange) {
19911                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
19912                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
19913                        oobEnabled == 1 ? "true" : "false");
19914            }
19915        };
19916        mContext.getContentResolver().registerContentObserver(
19917                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
19918                UserHandle.USER_SYSTEM);
19919        // At boot, restore the value from the setting, which persists across reboot.
19920        privAppOobObserver.onChange(true);
19921
19922        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19923        // disabled after already being started.
19924        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19925                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19926
19927        // Read the compatibilty setting when the system is ready.
19928        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19929                mContext.getContentResolver(),
19930                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19931        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19932        if (DEBUG_SETTINGS) {
19933            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19934        }
19935
19936        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19937
19938        synchronized (mPackages) {
19939            // Verify that all of the preferred activity components actually
19940            // exist.  It is possible for applications to be updated and at
19941            // that point remove a previously declared activity component that
19942            // had been set as a preferred activity.  We try to clean this up
19943            // the next time we encounter that preferred activity, but it is
19944            // possible for the user flow to never be able to return to that
19945            // situation so here we do a sanity check to make sure we haven't
19946            // left any junk around.
19947            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19948            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19949                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19950                removed.clear();
19951                for (PreferredActivity pa : pir.filterSet()) {
19952                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19953                        removed.add(pa);
19954                    }
19955                }
19956                if (removed.size() > 0) {
19957                    for (int r=0; r<removed.size(); r++) {
19958                        PreferredActivity pa = removed.get(r);
19959                        Slog.w(TAG, "Removing dangling preferred activity: "
19960                                + pa.mPref.mComponent);
19961                        pir.removeFilter(pa);
19962                    }
19963                    mSettings.writePackageRestrictionsLPr(
19964                            mSettings.mPreferredActivities.keyAt(i));
19965                }
19966            }
19967
19968            for (int userId : UserManagerService.getInstance().getUserIds()) {
19969                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19970                    grantPermissionsUserIds = ArrayUtils.appendInt(
19971                            grantPermissionsUserIds, userId);
19972                }
19973            }
19974        }
19975        sUserManager.systemReady();
19976
19977        // If we upgraded grant all default permissions before kicking off.
19978        for (int userId : grantPermissionsUserIds) {
19979            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
19980        }
19981
19982        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19983            // If we did not grant default permissions, we preload from this the
19984            // default permission exceptions lazily to ensure we don't hit the
19985            // disk on a new user creation.
19986            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19987        }
19988
19989        // Now that we've scanned all packages, and granted any default
19990        // permissions, ensure permissions are updated. Beware of dragons if you
19991        // try optimizing this.
19992        synchronized (mPackages) {
19993            mPermissionManager.updateAllPermissions(
19994                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
19995                    mPermissionCallback);
19996        }
19997
19998        // Kick off any messages waiting for system ready
19999        if (mPostSystemReadyMessages != null) {
20000            for (Message msg : mPostSystemReadyMessages) {
20001                msg.sendToTarget();
20002            }
20003            mPostSystemReadyMessages = null;
20004        }
20005
20006        // Watch for external volumes that come and go over time
20007        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20008        storage.registerListener(mStorageListener);
20009
20010        mInstallerService.systemReady();
20011        mPackageDexOptimizer.systemReady();
20012
20013        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20014                StorageManagerInternal.class);
20015        StorageManagerInternal.addExternalStoragePolicy(
20016                new StorageManagerInternal.ExternalStorageMountPolicy() {
20017            @Override
20018            public int getMountMode(int uid, String packageName) {
20019                if (Process.isIsolated(uid)) {
20020                    return Zygote.MOUNT_EXTERNAL_NONE;
20021                }
20022                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20023                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20024                }
20025                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20026                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20027                }
20028                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20029                    return Zygote.MOUNT_EXTERNAL_READ;
20030                }
20031                return Zygote.MOUNT_EXTERNAL_WRITE;
20032            }
20033
20034            @Override
20035            public boolean hasExternalStorage(int uid, String packageName) {
20036                return true;
20037            }
20038        });
20039
20040        // Now that we're mostly running, clean up stale users and apps
20041        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20042        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20043
20044        mPermissionManager.systemReady();
20045    }
20046
20047    public void waitForAppDataPrepared() {
20048        if (mPrepareAppDataFuture == null) {
20049            return;
20050        }
20051        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20052        mPrepareAppDataFuture = null;
20053    }
20054
20055    @Override
20056    public boolean isSafeMode() {
20057        // allow instant applications
20058        return mSafeMode;
20059    }
20060
20061    @Override
20062    public boolean hasSystemUidErrors() {
20063        // allow instant applications
20064        return mHasSystemUidErrors;
20065    }
20066
20067    static String arrayToString(int[] array) {
20068        StringBuffer buf = new StringBuffer(128);
20069        buf.append('[');
20070        if (array != null) {
20071            for (int i=0; i<array.length; i++) {
20072                if (i > 0) buf.append(", ");
20073                buf.append(array[i]);
20074            }
20075        }
20076        buf.append(']');
20077        return buf.toString();
20078    }
20079
20080    @Override
20081    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20082            FileDescriptor err, String[] args, ShellCallback callback,
20083            ResultReceiver resultReceiver) {
20084        (new PackageManagerShellCommand(this)).exec(
20085                this, in, out, err, args, callback, resultReceiver);
20086    }
20087
20088    @Override
20089    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20090        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20091
20092        DumpState dumpState = new DumpState();
20093        boolean fullPreferred = false;
20094        boolean checkin = false;
20095
20096        String packageName = null;
20097        ArraySet<String> permissionNames = null;
20098
20099        int opti = 0;
20100        while (opti < args.length) {
20101            String opt = args[opti];
20102            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20103                break;
20104            }
20105            opti++;
20106
20107            if ("-a".equals(opt)) {
20108                // Right now we only know how to print all.
20109            } else if ("-h".equals(opt)) {
20110                pw.println("Package manager dump options:");
20111                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20112                pw.println("    --checkin: dump for a checkin");
20113                pw.println("    -f: print details of intent filters");
20114                pw.println("    -h: print this help");
20115                pw.println("  cmd may be one of:");
20116                pw.println("    l[ibraries]: list known shared libraries");
20117                pw.println("    f[eatures]: list device features");
20118                pw.println("    k[eysets]: print known keysets");
20119                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20120                pw.println("    perm[issions]: dump permissions");
20121                pw.println("    permission [name ...]: dump declaration and use of given permission");
20122                pw.println("    pref[erred]: print preferred package settings");
20123                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20124                pw.println("    prov[iders]: dump content providers");
20125                pw.println("    p[ackages]: dump installed packages");
20126                pw.println("    s[hared-users]: dump shared user IDs");
20127                pw.println("    m[essages]: print collected runtime messages");
20128                pw.println("    v[erifiers]: print package verifier info");
20129                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20130                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20131                pw.println("    version: print database version info");
20132                pw.println("    write: write current settings now");
20133                pw.println("    installs: details about install sessions");
20134                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20135                pw.println("    dexopt: dump dexopt state");
20136                pw.println("    compiler-stats: dump compiler statistics");
20137                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20138                pw.println("    <package.name>: info about given package");
20139                return;
20140            } else if ("--checkin".equals(opt)) {
20141                checkin = true;
20142            } else if ("-f".equals(opt)) {
20143                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20144            } else if ("--proto".equals(opt)) {
20145                dumpProto(fd);
20146                return;
20147            } else {
20148                pw.println("Unknown argument: " + opt + "; use -h for help");
20149            }
20150        }
20151
20152        // Is the caller requesting to dump a particular piece of data?
20153        if (opti < args.length) {
20154            String cmd = args[opti];
20155            opti++;
20156            // Is this a package name?
20157            if ("android".equals(cmd) || cmd.contains(".")) {
20158                packageName = cmd;
20159                // When dumping a single package, we always dump all of its
20160                // filter information since the amount of data will be reasonable.
20161                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20162            } else if ("check-permission".equals(cmd)) {
20163                if (opti >= args.length) {
20164                    pw.println("Error: check-permission missing permission argument");
20165                    return;
20166                }
20167                String perm = args[opti];
20168                opti++;
20169                if (opti >= args.length) {
20170                    pw.println("Error: check-permission missing package argument");
20171                    return;
20172                }
20173
20174                String pkg = args[opti];
20175                opti++;
20176                int user = UserHandle.getUserId(Binder.getCallingUid());
20177                if (opti < args.length) {
20178                    try {
20179                        user = Integer.parseInt(args[opti]);
20180                    } catch (NumberFormatException e) {
20181                        pw.println("Error: check-permission user argument is not a number: "
20182                                + args[opti]);
20183                        return;
20184                    }
20185                }
20186
20187                // Normalize package name to handle renamed packages and static libs
20188                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20189
20190                pw.println(checkPermission(perm, pkg, user));
20191                return;
20192            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20193                dumpState.setDump(DumpState.DUMP_LIBS);
20194            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20195                dumpState.setDump(DumpState.DUMP_FEATURES);
20196            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20197                if (opti >= args.length) {
20198                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20199                            | DumpState.DUMP_SERVICE_RESOLVERS
20200                            | DumpState.DUMP_RECEIVER_RESOLVERS
20201                            | DumpState.DUMP_CONTENT_RESOLVERS);
20202                } else {
20203                    while (opti < args.length) {
20204                        String name = args[opti];
20205                        if ("a".equals(name) || "activity".equals(name)) {
20206                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20207                        } else if ("s".equals(name) || "service".equals(name)) {
20208                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20209                        } else if ("r".equals(name) || "receiver".equals(name)) {
20210                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20211                        } else if ("c".equals(name) || "content".equals(name)) {
20212                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20213                        } else {
20214                            pw.println("Error: unknown resolver table type: " + name);
20215                            return;
20216                        }
20217                        opti++;
20218                    }
20219                }
20220            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20221                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20222            } else if ("permission".equals(cmd)) {
20223                if (opti >= args.length) {
20224                    pw.println("Error: permission requires permission name");
20225                    return;
20226                }
20227                permissionNames = new ArraySet<>();
20228                while (opti < args.length) {
20229                    permissionNames.add(args[opti]);
20230                    opti++;
20231                }
20232                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20233                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20234            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20235                dumpState.setDump(DumpState.DUMP_PREFERRED);
20236            } else if ("preferred-xml".equals(cmd)) {
20237                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20238                if (opti < args.length && "--full".equals(args[opti])) {
20239                    fullPreferred = true;
20240                    opti++;
20241                }
20242            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20243                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20244            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20245                dumpState.setDump(DumpState.DUMP_PACKAGES);
20246            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20247                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20248            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20249                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20250            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20251                dumpState.setDump(DumpState.DUMP_MESSAGES);
20252            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20253                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20254            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20255                    || "intent-filter-verifiers".equals(cmd)) {
20256                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20257            } else if ("version".equals(cmd)) {
20258                dumpState.setDump(DumpState.DUMP_VERSION);
20259            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20260                dumpState.setDump(DumpState.DUMP_KEYSETS);
20261            } else if ("installs".equals(cmd)) {
20262                dumpState.setDump(DumpState.DUMP_INSTALLS);
20263            } else if ("frozen".equals(cmd)) {
20264                dumpState.setDump(DumpState.DUMP_FROZEN);
20265            } else if ("volumes".equals(cmd)) {
20266                dumpState.setDump(DumpState.DUMP_VOLUMES);
20267            } else if ("dexopt".equals(cmd)) {
20268                dumpState.setDump(DumpState.DUMP_DEXOPT);
20269            } else if ("compiler-stats".equals(cmd)) {
20270                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20271            } else if ("changes".equals(cmd)) {
20272                dumpState.setDump(DumpState.DUMP_CHANGES);
20273            } else if ("write".equals(cmd)) {
20274                synchronized (mPackages) {
20275                    mSettings.writeLPr();
20276                    pw.println("Settings written.");
20277                    return;
20278                }
20279            }
20280        }
20281
20282        if (checkin) {
20283            pw.println("vers,1");
20284        }
20285
20286        // reader
20287        synchronized (mPackages) {
20288            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20289                if (!checkin) {
20290                    if (dumpState.onTitlePrinted())
20291                        pw.println();
20292                    pw.println("Database versions:");
20293                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20294                }
20295            }
20296
20297            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20298                if (!checkin) {
20299                    if (dumpState.onTitlePrinted())
20300                        pw.println();
20301                    pw.println("Verifiers:");
20302                    pw.print("  Required: ");
20303                    pw.print(mRequiredVerifierPackage);
20304                    pw.print(" (uid=");
20305                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20306                            UserHandle.USER_SYSTEM));
20307                    pw.println(")");
20308                } else if (mRequiredVerifierPackage != null) {
20309                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20310                    pw.print(",");
20311                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20312                            UserHandle.USER_SYSTEM));
20313                }
20314            }
20315
20316            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20317                    packageName == null) {
20318                if (mIntentFilterVerifierComponent != null) {
20319                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20320                    if (!checkin) {
20321                        if (dumpState.onTitlePrinted())
20322                            pw.println();
20323                        pw.println("Intent Filter Verifier:");
20324                        pw.print("  Using: ");
20325                        pw.print(verifierPackageName);
20326                        pw.print(" (uid=");
20327                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20328                                UserHandle.USER_SYSTEM));
20329                        pw.println(")");
20330                    } else if (verifierPackageName != null) {
20331                        pw.print("ifv,"); pw.print(verifierPackageName);
20332                        pw.print(",");
20333                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20334                                UserHandle.USER_SYSTEM));
20335                    }
20336                } else {
20337                    pw.println();
20338                    pw.println("No Intent Filter Verifier available!");
20339                }
20340            }
20341
20342            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20343                boolean printedHeader = false;
20344                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20345                while (it.hasNext()) {
20346                    String libName = it.next();
20347                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20348                    if (versionedLib == null) {
20349                        continue;
20350                    }
20351                    final int versionCount = versionedLib.size();
20352                    for (int i = 0; i < versionCount; i++) {
20353                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20354                        if (!checkin) {
20355                            if (!printedHeader) {
20356                                if (dumpState.onTitlePrinted())
20357                                    pw.println();
20358                                pw.println("Libraries:");
20359                                printedHeader = true;
20360                            }
20361                            pw.print("  ");
20362                        } else {
20363                            pw.print("lib,");
20364                        }
20365                        pw.print(libEntry.info.getName());
20366                        if (libEntry.info.isStatic()) {
20367                            pw.print(" version=" + libEntry.info.getVersion());
20368                        }
20369                        if (!checkin) {
20370                            pw.print(" -> ");
20371                        }
20372                        if (libEntry.path != null) {
20373                            pw.print(" (jar) ");
20374                            pw.print(libEntry.path);
20375                        } else {
20376                            pw.print(" (apk) ");
20377                            pw.print(libEntry.apk);
20378                        }
20379                        pw.println();
20380                    }
20381                }
20382            }
20383
20384            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20385                if (dumpState.onTitlePrinted())
20386                    pw.println();
20387                if (!checkin) {
20388                    pw.println("Features:");
20389                }
20390
20391                synchronized (mAvailableFeatures) {
20392                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20393                        if (checkin) {
20394                            pw.print("feat,");
20395                            pw.print(feat.name);
20396                            pw.print(",");
20397                            pw.println(feat.version);
20398                        } else {
20399                            pw.print("  ");
20400                            pw.print(feat.name);
20401                            if (feat.version > 0) {
20402                                pw.print(" version=");
20403                                pw.print(feat.version);
20404                            }
20405                            pw.println();
20406                        }
20407                    }
20408                }
20409            }
20410
20411            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20412                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20413                        : "Activity Resolver Table:", "  ", packageName,
20414                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20415                    dumpState.setTitlePrinted(true);
20416                }
20417            }
20418            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20419                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20420                        : "Receiver Resolver Table:", "  ", packageName,
20421                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20422                    dumpState.setTitlePrinted(true);
20423                }
20424            }
20425            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20426                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20427                        : "Service Resolver Table:", "  ", packageName,
20428                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20429                    dumpState.setTitlePrinted(true);
20430                }
20431            }
20432            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20433                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20434                        : "Provider Resolver Table:", "  ", packageName,
20435                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20436                    dumpState.setTitlePrinted(true);
20437                }
20438            }
20439
20440            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20441                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20442                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20443                    int user = mSettings.mPreferredActivities.keyAt(i);
20444                    if (pir.dump(pw,
20445                            dumpState.getTitlePrinted()
20446                                ? "\nPreferred Activities User " + user + ":"
20447                                : "Preferred Activities User " + user + ":", "  ",
20448                            packageName, true, false)) {
20449                        dumpState.setTitlePrinted(true);
20450                    }
20451                }
20452            }
20453
20454            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20455                pw.flush();
20456                FileOutputStream fout = new FileOutputStream(fd);
20457                BufferedOutputStream str = new BufferedOutputStream(fout);
20458                XmlSerializer serializer = new FastXmlSerializer();
20459                try {
20460                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20461                    serializer.startDocument(null, true);
20462                    serializer.setFeature(
20463                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20464                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20465                    serializer.endDocument();
20466                    serializer.flush();
20467                } catch (IllegalArgumentException e) {
20468                    pw.println("Failed writing: " + e);
20469                } catch (IllegalStateException e) {
20470                    pw.println("Failed writing: " + e);
20471                } catch (IOException e) {
20472                    pw.println("Failed writing: " + e);
20473                }
20474            }
20475
20476            if (!checkin
20477                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20478                    && packageName == null) {
20479                pw.println();
20480                int count = mSettings.mPackages.size();
20481                if (count == 0) {
20482                    pw.println("No applications!");
20483                    pw.println();
20484                } else {
20485                    final String prefix = "  ";
20486                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20487                    if (allPackageSettings.size() == 0) {
20488                        pw.println("No domain preferred apps!");
20489                        pw.println();
20490                    } else {
20491                        pw.println("App verification status:");
20492                        pw.println();
20493                        count = 0;
20494                        for (PackageSetting ps : allPackageSettings) {
20495                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20496                            if (ivi == null || ivi.getPackageName() == null) continue;
20497                            pw.println(prefix + "Package: " + ivi.getPackageName());
20498                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20499                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20500                            pw.println();
20501                            count++;
20502                        }
20503                        if (count == 0) {
20504                            pw.println(prefix + "No app verification established.");
20505                            pw.println();
20506                        }
20507                        for (int userId : sUserManager.getUserIds()) {
20508                            pw.println("App linkages for user " + userId + ":");
20509                            pw.println();
20510                            count = 0;
20511                            for (PackageSetting ps : allPackageSettings) {
20512                                final long status = ps.getDomainVerificationStatusForUser(userId);
20513                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20514                                        && !DEBUG_DOMAIN_VERIFICATION) {
20515                                    continue;
20516                                }
20517                                pw.println(prefix + "Package: " + ps.name);
20518                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20519                                String statusStr = IntentFilterVerificationInfo.
20520                                        getStatusStringFromValue(status);
20521                                pw.println(prefix + "Status:  " + statusStr);
20522                                pw.println();
20523                                count++;
20524                            }
20525                            if (count == 0) {
20526                                pw.println(prefix + "No configured app linkages.");
20527                                pw.println();
20528                            }
20529                        }
20530                    }
20531                }
20532            }
20533
20534            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20535                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20536            }
20537
20538            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20539                boolean printedSomething = false;
20540                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20541                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20542                        continue;
20543                    }
20544                    if (!printedSomething) {
20545                        if (dumpState.onTitlePrinted())
20546                            pw.println();
20547                        pw.println("Registered ContentProviders:");
20548                        printedSomething = true;
20549                    }
20550                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20551                    pw.print("    "); pw.println(p.toString());
20552                }
20553                printedSomething = false;
20554                for (Map.Entry<String, PackageParser.Provider> entry :
20555                        mProvidersByAuthority.entrySet()) {
20556                    PackageParser.Provider p = entry.getValue();
20557                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20558                        continue;
20559                    }
20560                    if (!printedSomething) {
20561                        if (dumpState.onTitlePrinted())
20562                            pw.println();
20563                        pw.println("ContentProvider Authorities:");
20564                        printedSomething = true;
20565                    }
20566                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20567                    pw.print("    "); pw.println(p.toString());
20568                    if (p.info != null && p.info.applicationInfo != null) {
20569                        final String appInfo = p.info.applicationInfo.toString();
20570                        pw.print("      applicationInfo="); pw.println(appInfo);
20571                    }
20572                }
20573            }
20574
20575            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20576                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20577            }
20578
20579            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20580                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20581            }
20582
20583            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20584                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20585            }
20586
20587            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20588                if (dumpState.onTitlePrinted()) pw.println();
20589                pw.println("Package Changes:");
20590                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20591                final int K = mChangedPackages.size();
20592                for (int i = 0; i < K; i++) {
20593                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20594                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20595                    final int N = changes.size();
20596                    if (N == 0) {
20597                        pw.print("    "); pw.println("No packages changed");
20598                    } else {
20599                        for (int j = 0; j < N; j++) {
20600                            final String pkgName = changes.valueAt(j);
20601                            final int sequenceNumber = changes.keyAt(j);
20602                            pw.print("    ");
20603                            pw.print("seq=");
20604                            pw.print(sequenceNumber);
20605                            pw.print(", package=");
20606                            pw.println(pkgName);
20607                        }
20608                    }
20609                }
20610            }
20611
20612            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20613                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20614            }
20615
20616            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20617                // XXX should handle packageName != null by dumping only install data that
20618                // the given package is involved with.
20619                if (dumpState.onTitlePrinted()) pw.println();
20620
20621                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20622                ipw.println();
20623                ipw.println("Frozen packages:");
20624                ipw.increaseIndent();
20625                if (mFrozenPackages.size() == 0) {
20626                    ipw.println("(none)");
20627                } else {
20628                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20629                        ipw.println(mFrozenPackages.valueAt(i));
20630                    }
20631                }
20632                ipw.decreaseIndent();
20633            }
20634
20635            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
20636                if (dumpState.onTitlePrinted()) pw.println();
20637
20638                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20639                ipw.println();
20640                ipw.println("Loaded volumes:");
20641                ipw.increaseIndent();
20642                if (mLoadedVolumes.size() == 0) {
20643                    ipw.println("(none)");
20644                } else {
20645                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
20646                        ipw.println(mLoadedVolumes.valueAt(i));
20647                    }
20648                }
20649                ipw.decreaseIndent();
20650            }
20651
20652            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20653                if (dumpState.onTitlePrinted()) pw.println();
20654                dumpDexoptStateLPr(pw, packageName);
20655            }
20656
20657            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20658                if (dumpState.onTitlePrinted()) pw.println();
20659                dumpCompilerStatsLPr(pw, packageName);
20660            }
20661
20662            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20663                if (dumpState.onTitlePrinted()) pw.println();
20664                mSettings.dumpReadMessagesLPr(pw, dumpState);
20665
20666                pw.println();
20667                pw.println("Package warning messages:");
20668                dumpCriticalInfo(pw, null);
20669            }
20670
20671            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20672                dumpCriticalInfo(pw, "msg,");
20673            }
20674        }
20675
20676        // PackageInstaller should be called outside of mPackages lock
20677        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20678            // XXX should handle packageName != null by dumping only install data that
20679            // the given package is involved with.
20680            if (dumpState.onTitlePrinted()) pw.println();
20681            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20682        }
20683    }
20684
20685    private void dumpProto(FileDescriptor fd) {
20686        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20687
20688        synchronized (mPackages) {
20689            final long requiredVerifierPackageToken =
20690                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20691            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20692            proto.write(
20693                    PackageServiceDumpProto.PackageShortProto.UID,
20694                    getPackageUid(
20695                            mRequiredVerifierPackage,
20696                            MATCH_DEBUG_TRIAGED_MISSING,
20697                            UserHandle.USER_SYSTEM));
20698            proto.end(requiredVerifierPackageToken);
20699
20700            if (mIntentFilterVerifierComponent != null) {
20701                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20702                final long verifierPackageToken =
20703                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20704                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20705                proto.write(
20706                        PackageServiceDumpProto.PackageShortProto.UID,
20707                        getPackageUid(
20708                                verifierPackageName,
20709                                MATCH_DEBUG_TRIAGED_MISSING,
20710                                UserHandle.USER_SYSTEM));
20711                proto.end(verifierPackageToken);
20712            }
20713
20714            dumpSharedLibrariesProto(proto);
20715            dumpFeaturesProto(proto);
20716            mSettings.dumpPackagesProto(proto);
20717            mSettings.dumpSharedUsersProto(proto);
20718            dumpCriticalInfo(proto);
20719        }
20720        proto.flush();
20721    }
20722
20723    private void dumpFeaturesProto(ProtoOutputStream proto) {
20724        synchronized (mAvailableFeatures) {
20725            final int count = mAvailableFeatures.size();
20726            for (int i = 0; i < count; i++) {
20727                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
20728            }
20729        }
20730    }
20731
20732    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20733        final int count = mSharedLibraries.size();
20734        for (int i = 0; i < count; i++) {
20735            final String libName = mSharedLibraries.keyAt(i);
20736            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20737            if (versionedLib == null) {
20738                continue;
20739            }
20740            final int versionCount = versionedLib.size();
20741            for (int j = 0; j < versionCount; j++) {
20742                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20743                final long sharedLibraryToken =
20744                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20745                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20746                final boolean isJar = (libEntry.path != null);
20747                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20748                if (isJar) {
20749                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20750                } else {
20751                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20752                }
20753                proto.end(sharedLibraryToken);
20754            }
20755        }
20756    }
20757
20758    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20759        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20760        ipw.println();
20761        ipw.println("Dexopt state:");
20762        ipw.increaseIndent();
20763        Collection<PackageParser.Package> packages = null;
20764        if (packageName != null) {
20765            PackageParser.Package targetPackage = mPackages.get(packageName);
20766            if (targetPackage != null) {
20767                packages = Collections.singletonList(targetPackage);
20768            } else {
20769                ipw.println("Unable to find package: " + packageName);
20770                return;
20771            }
20772        } else {
20773            packages = mPackages.values();
20774        }
20775
20776        for (PackageParser.Package pkg : packages) {
20777            ipw.println("[" + pkg.packageName + "]");
20778            ipw.increaseIndent();
20779            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
20780                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
20781            ipw.decreaseIndent();
20782        }
20783    }
20784
20785    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20786        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20787        ipw.println();
20788        ipw.println("Compiler stats:");
20789        ipw.increaseIndent();
20790        Collection<PackageParser.Package> packages = null;
20791        if (packageName != null) {
20792            PackageParser.Package targetPackage = mPackages.get(packageName);
20793            if (targetPackage != null) {
20794                packages = Collections.singletonList(targetPackage);
20795            } else {
20796                ipw.println("Unable to find package: " + packageName);
20797                return;
20798            }
20799        } else {
20800            packages = mPackages.values();
20801        }
20802
20803        for (PackageParser.Package pkg : packages) {
20804            ipw.println("[" + pkg.packageName + "]");
20805            ipw.increaseIndent();
20806
20807            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20808            if (stats == null) {
20809                ipw.println("(No recorded stats)");
20810            } else {
20811                stats.dump(ipw);
20812            }
20813            ipw.decreaseIndent();
20814        }
20815    }
20816
20817    private String dumpDomainString(String packageName) {
20818        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20819                .getList();
20820        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20821
20822        ArraySet<String> result = new ArraySet<>();
20823        if (iviList.size() > 0) {
20824            for (IntentFilterVerificationInfo ivi : iviList) {
20825                for (String host : ivi.getDomains()) {
20826                    result.add(host);
20827                }
20828            }
20829        }
20830        if (filters != null && filters.size() > 0) {
20831            for (IntentFilter filter : filters) {
20832                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20833                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20834                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20835                    result.addAll(filter.getHostsList());
20836                }
20837            }
20838        }
20839
20840        StringBuilder sb = new StringBuilder(result.size() * 16);
20841        for (String domain : result) {
20842            if (sb.length() > 0) sb.append(" ");
20843            sb.append(domain);
20844        }
20845        return sb.toString();
20846    }
20847
20848    // ------- apps on sdcard specific code -------
20849    static final boolean DEBUG_SD_INSTALL = false;
20850
20851    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20852
20853    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20854
20855    private boolean mMediaMounted = false;
20856
20857    static String getEncryptKey() {
20858        try {
20859            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20860                    SD_ENCRYPTION_KEYSTORE_NAME);
20861            if (sdEncKey == null) {
20862                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20863                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20864                if (sdEncKey == null) {
20865                    Slog.e(TAG, "Failed to create encryption keys");
20866                    return null;
20867                }
20868            }
20869            return sdEncKey;
20870        } catch (NoSuchAlgorithmException nsae) {
20871            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20872            return null;
20873        } catch (IOException ioe) {
20874            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20875            return null;
20876        }
20877    }
20878
20879    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20880            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20881        final int size = infos.size();
20882        final String[] packageNames = new String[size];
20883        final int[] packageUids = new int[size];
20884        for (int i = 0; i < size; i++) {
20885            final ApplicationInfo info = infos.get(i);
20886            packageNames[i] = info.packageName;
20887            packageUids[i] = info.uid;
20888        }
20889        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20890                finishedReceiver);
20891    }
20892
20893    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20894            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20895        sendResourcesChangedBroadcast(mediaStatus, replacing,
20896                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20897    }
20898
20899    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20900            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20901        int size = pkgList.length;
20902        if (size > 0) {
20903            // Send broadcasts here
20904            Bundle extras = new Bundle();
20905            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20906            if (uidArr != null) {
20907                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20908            }
20909            if (replacing) {
20910                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20911            }
20912            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20913                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20914            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20915        }
20916    }
20917
20918    private void loadPrivatePackages(final VolumeInfo vol) {
20919        mHandler.post(new Runnable() {
20920            @Override
20921            public void run() {
20922                loadPrivatePackagesInner(vol);
20923            }
20924        });
20925    }
20926
20927    private void loadPrivatePackagesInner(VolumeInfo vol) {
20928        final String volumeUuid = vol.fsUuid;
20929        if (TextUtils.isEmpty(volumeUuid)) {
20930            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20931            return;
20932        }
20933
20934        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20935        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20936        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20937
20938        final VersionInfo ver;
20939        final List<PackageSetting> packages;
20940        synchronized (mPackages) {
20941            ver = mSettings.findOrCreateVersion(volumeUuid);
20942            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20943        }
20944
20945        for (PackageSetting ps : packages) {
20946            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20947            synchronized (mInstallLock) {
20948                final PackageParser.Package pkg;
20949                try {
20950                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20951                    loaded.add(pkg.applicationInfo);
20952
20953                } catch (PackageManagerException e) {
20954                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20955                }
20956
20957                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20958                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20959                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20960                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20961                }
20962            }
20963        }
20964
20965        // Reconcile app data for all started/unlocked users
20966        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20967        final UserManager um = mContext.getSystemService(UserManager.class);
20968        UserManagerInternal umInternal = getUserManagerInternal();
20969        for (UserInfo user : um.getUsers()) {
20970            final int flags;
20971            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20972                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20973            } else if (umInternal.isUserRunning(user.id)) {
20974                flags = StorageManager.FLAG_STORAGE_DE;
20975            } else {
20976                continue;
20977            }
20978
20979            try {
20980                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20981                synchronized (mInstallLock) {
20982                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20983                }
20984            } catch (IllegalStateException e) {
20985                // Device was probably ejected, and we'll process that event momentarily
20986                Slog.w(TAG, "Failed to prepare storage: " + e);
20987            }
20988        }
20989
20990        synchronized (mPackages) {
20991            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
20992            if (sdkUpdated) {
20993                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20994                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20995            }
20996            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
20997                    mPermissionCallback);
20998
20999            // Yay, everything is now upgraded
21000            ver.forceCurrent();
21001
21002            mSettings.writeLPr();
21003        }
21004
21005        for (PackageFreezer freezer : freezers) {
21006            freezer.close();
21007        }
21008
21009        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21010        sendResourcesChangedBroadcast(true, false, loaded, null);
21011        mLoadedVolumes.add(vol.getId());
21012    }
21013
21014    private void unloadPrivatePackages(final VolumeInfo vol) {
21015        mHandler.post(new Runnable() {
21016            @Override
21017            public void run() {
21018                unloadPrivatePackagesInner(vol);
21019            }
21020        });
21021    }
21022
21023    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21024        final String volumeUuid = vol.fsUuid;
21025        if (TextUtils.isEmpty(volumeUuid)) {
21026            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21027            return;
21028        }
21029
21030        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21031        synchronized (mInstallLock) {
21032        synchronized (mPackages) {
21033            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21034            for (PackageSetting ps : packages) {
21035                if (ps.pkg == null) continue;
21036
21037                final ApplicationInfo info = ps.pkg.applicationInfo;
21038                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21039                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21040
21041                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21042                        "unloadPrivatePackagesInner")) {
21043                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21044                            false, null)) {
21045                        unloaded.add(info);
21046                    } else {
21047                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21048                    }
21049                }
21050
21051                // Try very hard to release any references to this package
21052                // so we don't risk the system server being killed due to
21053                // open FDs
21054                AttributeCache.instance().removePackage(ps.name);
21055            }
21056
21057            mSettings.writeLPr();
21058        }
21059        }
21060
21061        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21062        sendResourcesChangedBroadcast(false, false, unloaded, null);
21063        mLoadedVolumes.remove(vol.getId());
21064
21065        // Try very hard to release any references to this path so we don't risk
21066        // the system server being killed due to open FDs
21067        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21068
21069        for (int i = 0; i < 3; i++) {
21070            System.gc();
21071            System.runFinalization();
21072        }
21073    }
21074
21075    private void assertPackageKnown(String volumeUuid, String packageName)
21076            throws PackageManagerException {
21077        synchronized (mPackages) {
21078            // Normalize package name to handle renamed packages
21079            packageName = normalizePackageNameLPr(packageName);
21080
21081            final PackageSetting ps = mSettings.mPackages.get(packageName);
21082            if (ps == null) {
21083                throw new PackageManagerException("Package " + packageName + " is unknown");
21084            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21085                throw new PackageManagerException(
21086                        "Package " + packageName + " found on unknown volume " + volumeUuid
21087                                + "; expected volume " + ps.volumeUuid);
21088            }
21089        }
21090    }
21091
21092    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21093            throws PackageManagerException {
21094        synchronized (mPackages) {
21095            // Normalize package name to handle renamed packages
21096            packageName = normalizePackageNameLPr(packageName);
21097
21098            final PackageSetting ps = mSettings.mPackages.get(packageName);
21099            if (ps == null) {
21100                throw new PackageManagerException("Package " + packageName + " is unknown");
21101            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21102                throw new PackageManagerException(
21103                        "Package " + packageName + " found on unknown volume " + volumeUuid
21104                                + "; expected volume " + ps.volumeUuid);
21105            } else if (!ps.getInstalled(userId)) {
21106                throw new PackageManagerException(
21107                        "Package " + packageName + " not installed for user " + userId);
21108            }
21109        }
21110    }
21111
21112    private List<String> collectAbsoluteCodePaths() {
21113        synchronized (mPackages) {
21114            List<String> codePaths = new ArrayList<>();
21115            final int packageCount = mSettings.mPackages.size();
21116            for (int i = 0; i < packageCount; i++) {
21117                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21118                codePaths.add(ps.codePath.getAbsolutePath());
21119            }
21120            return codePaths;
21121        }
21122    }
21123
21124    /**
21125     * Examine all apps present on given mounted volume, and destroy apps that
21126     * aren't expected, either due to uninstallation or reinstallation on
21127     * another volume.
21128     */
21129    private void reconcileApps(String volumeUuid) {
21130        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21131        List<File> filesToDelete = null;
21132
21133        final File[] files = FileUtils.listFilesOrEmpty(
21134                Environment.getDataAppDirectory(volumeUuid));
21135        for (File file : files) {
21136            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21137                    && !PackageInstallerService.isStageName(file.getName());
21138            if (!isPackage) {
21139                // Ignore entries which are not packages
21140                continue;
21141            }
21142
21143            String absolutePath = file.getAbsolutePath();
21144
21145            boolean pathValid = false;
21146            final int absoluteCodePathCount = absoluteCodePaths.size();
21147            for (int i = 0; i < absoluteCodePathCount; i++) {
21148                String absoluteCodePath = absoluteCodePaths.get(i);
21149                if (absolutePath.startsWith(absoluteCodePath)) {
21150                    pathValid = true;
21151                    break;
21152                }
21153            }
21154
21155            if (!pathValid) {
21156                if (filesToDelete == null) {
21157                    filesToDelete = new ArrayList<>();
21158                }
21159                filesToDelete.add(file);
21160            }
21161        }
21162
21163        if (filesToDelete != null) {
21164            final int fileToDeleteCount = filesToDelete.size();
21165            for (int i = 0; i < fileToDeleteCount; i++) {
21166                File fileToDelete = filesToDelete.get(i);
21167                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21168                synchronized (mInstallLock) {
21169                    removeCodePathLI(fileToDelete);
21170                }
21171            }
21172        }
21173    }
21174
21175    /**
21176     * Reconcile all app data for the given user.
21177     * <p>
21178     * Verifies that directories exist and that ownership and labeling is
21179     * correct for all installed apps on all mounted volumes.
21180     */
21181    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21182        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21183        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21184            final String volumeUuid = vol.getFsUuid();
21185            synchronized (mInstallLock) {
21186                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21187            }
21188        }
21189    }
21190
21191    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21192            boolean migrateAppData) {
21193        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21194    }
21195
21196    /**
21197     * Reconcile all app data on given mounted volume.
21198     * <p>
21199     * Destroys app data that isn't expected, either due to uninstallation or
21200     * reinstallation on another volume.
21201     * <p>
21202     * Verifies that directories exist and that ownership and labeling is
21203     * correct for all installed apps.
21204     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21205     */
21206    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21207            boolean migrateAppData, boolean onlyCoreApps) {
21208        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21209                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21210        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21211
21212        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21213        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21214
21215        // First look for stale data that doesn't belong, and check if things
21216        // have changed since we did our last restorecon
21217        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21218            if (StorageManager.isFileEncryptedNativeOrEmulated()
21219                    && !StorageManager.isUserKeyUnlocked(userId)) {
21220                throw new RuntimeException(
21221                        "Yikes, someone asked us to reconcile CE storage while " + userId
21222                                + " was still locked; this would have caused massive data loss!");
21223            }
21224
21225            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21226            for (File file : files) {
21227                final String packageName = file.getName();
21228                try {
21229                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21230                } catch (PackageManagerException e) {
21231                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21232                    try {
21233                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21234                                StorageManager.FLAG_STORAGE_CE, 0);
21235                    } catch (InstallerException e2) {
21236                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21237                    }
21238                }
21239            }
21240        }
21241        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21242            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21243            for (File file : files) {
21244                final String packageName = file.getName();
21245                try {
21246                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21247                } catch (PackageManagerException e) {
21248                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21249                    try {
21250                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21251                                StorageManager.FLAG_STORAGE_DE, 0);
21252                    } catch (InstallerException e2) {
21253                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21254                    }
21255                }
21256            }
21257        }
21258
21259        // Ensure that data directories are ready to roll for all packages
21260        // installed for this volume and user
21261        final List<PackageSetting> packages;
21262        synchronized (mPackages) {
21263            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21264        }
21265        int preparedCount = 0;
21266        for (PackageSetting ps : packages) {
21267            final String packageName = ps.name;
21268            if (ps.pkg == null) {
21269                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21270                // TODO: might be due to legacy ASEC apps; we should circle back
21271                // and reconcile again once they're scanned
21272                continue;
21273            }
21274            // Skip non-core apps if requested
21275            if (onlyCoreApps && !ps.pkg.coreApp) {
21276                result.add(packageName);
21277                continue;
21278            }
21279
21280            if (ps.getInstalled(userId)) {
21281                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21282                preparedCount++;
21283            }
21284        }
21285
21286        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21287        return result;
21288    }
21289
21290    /**
21291     * Prepare app data for the given app just after it was installed or
21292     * upgraded. This method carefully only touches users that it's installed
21293     * for, and it forces a restorecon to handle any seinfo changes.
21294     * <p>
21295     * Verifies that directories exist and that ownership and labeling is
21296     * correct for all installed apps. If there is an ownership mismatch, it
21297     * will try recovering system apps by wiping data; third-party app data is
21298     * left intact.
21299     * <p>
21300     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21301     */
21302    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21303        final PackageSetting ps;
21304        synchronized (mPackages) {
21305            ps = mSettings.mPackages.get(pkg.packageName);
21306            mSettings.writeKernelMappingLPr(ps);
21307        }
21308
21309        final UserManager um = mContext.getSystemService(UserManager.class);
21310        UserManagerInternal umInternal = getUserManagerInternal();
21311        for (UserInfo user : um.getUsers()) {
21312            final int flags;
21313            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21314                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21315            } else if (umInternal.isUserRunning(user.id)) {
21316                flags = StorageManager.FLAG_STORAGE_DE;
21317            } else {
21318                continue;
21319            }
21320
21321            if (ps.getInstalled(user.id)) {
21322                // TODO: when user data is locked, mark that we're still dirty
21323                prepareAppDataLIF(pkg, user.id, flags);
21324            }
21325        }
21326    }
21327
21328    /**
21329     * Prepare app data for the given app.
21330     * <p>
21331     * Verifies that directories exist and that ownership and labeling is
21332     * correct for all installed apps. If there is an ownership mismatch, this
21333     * will try recovering system apps by wiping data; third-party app data is
21334     * left intact.
21335     */
21336    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21337        if (pkg == null) {
21338            Slog.wtf(TAG, "Package was null!", new Throwable());
21339            return;
21340        }
21341        prepareAppDataLeafLIF(pkg, userId, flags);
21342        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21343        for (int i = 0; i < childCount; i++) {
21344            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21345        }
21346    }
21347
21348    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21349            boolean maybeMigrateAppData) {
21350        prepareAppDataLIF(pkg, userId, flags);
21351
21352        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21353            // We may have just shuffled around app data directories, so
21354            // prepare them one more time
21355            prepareAppDataLIF(pkg, userId, flags);
21356        }
21357    }
21358
21359    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21360        if (DEBUG_APP_DATA) {
21361            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21362                    + Integer.toHexString(flags));
21363        }
21364
21365        final String volumeUuid = pkg.volumeUuid;
21366        final String packageName = pkg.packageName;
21367        final ApplicationInfo app = pkg.applicationInfo;
21368        final int appId = UserHandle.getAppId(app.uid);
21369
21370        Preconditions.checkNotNull(app.seInfo);
21371
21372        long ceDataInode = -1;
21373        try {
21374            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21375                    appId, app.seInfo, app.targetSdkVersion);
21376        } catch (InstallerException e) {
21377            if (app.isSystemApp()) {
21378                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21379                        + ", but trying to recover: " + e);
21380                destroyAppDataLeafLIF(pkg, userId, flags);
21381                try {
21382                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21383                            appId, app.seInfo, app.targetSdkVersion);
21384                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21385                } catch (InstallerException e2) {
21386                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21387                }
21388            } else {
21389                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21390            }
21391        }
21392
21393        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21394            // TODO: mark this structure as dirty so we persist it!
21395            synchronized (mPackages) {
21396                final PackageSetting ps = mSettings.mPackages.get(packageName);
21397                if (ps != null) {
21398                    ps.setCeDataInode(ceDataInode, userId);
21399                }
21400            }
21401        }
21402
21403        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21404    }
21405
21406    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21407        if (pkg == null) {
21408            Slog.wtf(TAG, "Package was null!", new Throwable());
21409            return;
21410        }
21411        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21412        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21413        for (int i = 0; i < childCount; i++) {
21414            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21415        }
21416    }
21417
21418    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21419        final String volumeUuid = pkg.volumeUuid;
21420        final String packageName = pkg.packageName;
21421        final ApplicationInfo app = pkg.applicationInfo;
21422
21423        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21424            // Create a native library symlink only if we have native libraries
21425            // and if the native libraries are 32 bit libraries. We do not provide
21426            // this symlink for 64 bit libraries.
21427            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21428                final String nativeLibPath = app.nativeLibraryDir;
21429                try {
21430                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21431                            nativeLibPath, userId);
21432                } catch (InstallerException e) {
21433                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21434                }
21435            }
21436        }
21437    }
21438
21439    /**
21440     * For system apps on non-FBE devices, this method migrates any existing
21441     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21442     * requested by the app.
21443     */
21444    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21445        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21446                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21447            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21448                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21449            try {
21450                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21451                        storageTarget);
21452            } catch (InstallerException e) {
21453                logCriticalInfo(Log.WARN,
21454                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21455            }
21456            return true;
21457        } else {
21458            return false;
21459        }
21460    }
21461
21462    public PackageFreezer freezePackage(String packageName, String killReason) {
21463        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21464    }
21465
21466    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21467        return new PackageFreezer(packageName, userId, killReason);
21468    }
21469
21470    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21471            String killReason) {
21472        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21473    }
21474
21475    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21476            String killReason) {
21477        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21478            return new PackageFreezer();
21479        } else {
21480            return freezePackage(packageName, userId, killReason);
21481        }
21482    }
21483
21484    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21485            String killReason) {
21486        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21487    }
21488
21489    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21490            String killReason) {
21491        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21492            return new PackageFreezer();
21493        } else {
21494            return freezePackage(packageName, userId, killReason);
21495        }
21496    }
21497
21498    /**
21499     * Class that freezes and kills the given package upon creation, and
21500     * unfreezes it upon closing. This is typically used when doing surgery on
21501     * app code/data to prevent the app from running while you're working.
21502     */
21503    private class PackageFreezer implements AutoCloseable {
21504        private final String mPackageName;
21505        private final PackageFreezer[] mChildren;
21506
21507        private final boolean mWeFroze;
21508
21509        private final AtomicBoolean mClosed = new AtomicBoolean();
21510        private final CloseGuard mCloseGuard = CloseGuard.get();
21511
21512        /**
21513         * Create and return a stub freezer that doesn't actually do anything,
21514         * typically used when someone requested
21515         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21516         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21517         */
21518        public PackageFreezer() {
21519            mPackageName = null;
21520            mChildren = null;
21521            mWeFroze = false;
21522            mCloseGuard.open("close");
21523        }
21524
21525        public PackageFreezer(String packageName, int userId, String killReason) {
21526            synchronized (mPackages) {
21527                mPackageName = packageName;
21528                mWeFroze = mFrozenPackages.add(mPackageName);
21529
21530                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21531                if (ps != null) {
21532                    killApplication(ps.name, ps.appId, userId, killReason);
21533                }
21534
21535                final PackageParser.Package p = mPackages.get(packageName);
21536                if (p != null && p.childPackages != null) {
21537                    final int N = p.childPackages.size();
21538                    mChildren = new PackageFreezer[N];
21539                    for (int i = 0; i < N; i++) {
21540                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21541                                userId, killReason);
21542                    }
21543                } else {
21544                    mChildren = null;
21545                }
21546            }
21547            mCloseGuard.open("close");
21548        }
21549
21550        @Override
21551        protected void finalize() throws Throwable {
21552            try {
21553                if (mCloseGuard != null) {
21554                    mCloseGuard.warnIfOpen();
21555                }
21556
21557                close();
21558            } finally {
21559                super.finalize();
21560            }
21561        }
21562
21563        @Override
21564        public void close() {
21565            mCloseGuard.close();
21566            if (mClosed.compareAndSet(false, true)) {
21567                synchronized (mPackages) {
21568                    if (mWeFroze) {
21569                        mFrozenPackages.remove(mPackageName);
21570                    }
21571
21572                    if (mChildren != null) {
21573                        for (PackageFreezer freezer : mChildren) {
21574                            freezer.close();
21575                        }
21576                    }
21577                }
21578            }
21579        }
21580    }
21581
21582    /**
21583     * Verify that given package is currently frozen.
21584     */
21585    private void checkPackageFrozen(String packageName) {
21586        synchronized (mPackages) {
21587            if (!mFrozenPackages.contains(packageName)) {
21588                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21589            }
21590        }
21591    }
21592
21593    @Override
21594    public int movePackage(final String packageName, final String volumeUuid) {
21595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21596
21597        final int callingUid = Binder.getCallingUid();
21598        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21599        final int moveId = mNextMoveId.getAndIncrement();
21600        mHandler.post(new Runnable() {
21601            @Override
21602            public void run() {
21603                try {
21604                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
21605                } catch (PackageManagerException e) {
21606                    Slog.w(TAG, "Failed to move " + packageName, e);
21607                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
21608                }
21609            }
21610        });
21611        return moveId;
21612    }
21613
21614    private void movePackageInternal(final String packageName, final String volumeUuid,
21615            final int moveId, final int callingUid, UserHandle user)
21616                    throws PackageManagerException {
21617        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21618        final PackageManager pm = mContext.getPackageManager();
21619
21620        final boolean currentAsec;
21621        final String currentVolumeUuid;
21622        final File codeFile;
21623        final String installerPackageName;
21624        final String packageAbiOverride;
21625        final int appId;
21626        final String seinfo;
21627        final String label;
21628        final int targetSdkVersion;
21629        final PackageFreezer freezer;
21630        final int[] installedUserIds;
21631
21632        // reader
21633        synchronized (mPackages) {
21634            final PackageParser.Package pkg = mPackages.get(packageName);
21635            final PackageSetting ps = mSettings.mPackages.get(packageName);
21636            if (pkg == null
21637                    || ps == null
21638                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
21639                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21640            }
21641            if (pkg.applicationInfo.isSystemApp()) {
21642                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21643                        "Cannot move system application");
21644            }
21645
21646            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21647            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21648                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21649            if (isInternalStorage && !allow3rdPartyOnInternal) {
21650                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21651                        "3rd party apps are not allowed on internal storage");
21652            }
21653
21654            if (pkg.applicationInfo.isExternalAsec()) {
21655                currentAsec = true;
21656                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21657            } else if (pkg.applicationInfo.isForwardLocked()) {
21658                currentAsec = true;
21659                currentVolumeUuid = "forward_locked";
21660            } else {
21661                currentAsec = false;
21662                currentVolumeUuid = ps.volumeUuid;
21663
21664                final File probe = new File(pkg.codePath);
21665                final File probeOat = new File(probe, "oat");
21666                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21667                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21668                            "Move only supported for modern cluster style installs");
21669                }
21670            }
21671
21672            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21673                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21674                        "Package already moved to " + volumeUuid);
21675            }
21676            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21677                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21678                        "Device admin cannot be moved");
21679            }
21680
21681            if (mFrozenPackages.contains(packageName)) {
21682                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21683                        "Failed to move already frozen package");
21684            }
21685
21686            codeFile = new File(pkg.codePath);
21687            installerPackageName = ps.installerPackageName;
21688            packageAbiOverride = ps.cpuAbiOverrideString;
21689            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21690            seinfo = pkg.applicationInfo.seInfo;
21691            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21692            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21693            freezer = freezePackage(packageName, "movePackageInternal");
21694            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21695        }
21696
21697        final Bundle extras = new Bundle();
21698        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21699        extras.putString(Intent.EXTRA_TITLE, label);
21700        mMoveCallbacks.notifyCreated(moveId, extras);
21701
21702        int installFlags;
21703        final boolean moveCompleteApp;
21704        final File measurePath;
21705
21706        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21707            installFlags = INSTALL_INTERNAL;
21708            moveCompleteApp = !currentAsec;
21709            measurePath = Environment.getDataAppDirectory(volumeUuid);
21710        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21711            installFlags = INSTALL_EXTERNAL;
21712            moveCompleteApp = false;
21713            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21714        } else {
21715            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21716            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21717                    || !volume.isMountedWritable()) {
21718                freezer.close();
21719                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21720                        "Move location not mounted private volume");
21721            }
21722
21723            Preconditions.checkState(!currentAsec);
21724
21725            installFlags = INSTALL_INTERNAL;
21726            moveCompleteApp = true;
21727            measurePath = Environment.getDataAppDirectory(volumeUuid);
21728        }
21729
21730        // If we're moving app data around, we need all the users unlocked
21731        if (moveCompleteApp) {
21732            for (int userId : installedUserIds) {
21733                if (StorageManager.isFileEncryptedNativeOrEmulated()
21734                        && !StorageManager.isUserKeyUnlocked(userId)) {
21735                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
21736                            "User " + userId + " must be unlocked");
21737                }
21738            }
21739        }
21740
21741        final PackageStats stats = new PackageStats(null, -1);
21742        synchronized (mInstaller) {
21743            for (int userId : installedUserIds) {
21744                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21745                    freezer.close();
21746                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21747                            "Failed to measure package size");
21748                }
21749            }
21750        }
21751
21752        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21753                + stats.dataSize);
21754
21755        final long startFreeBytes = measurePath.getUsableSpace();
21756        final long sizeBytes;
21757        if (moveCompleteApp) {
21758            sizeBytes = stats.codeSize + stats.dataSize;
21759        } else {
21760            sizeBytes = stats.codeSize;
21761        }
21762
21763        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21764            freezer.close();
21765            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21766                    "Not enough free space to move");
21767        }
21768
21769        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21770
21771        final CountDownLatch installedLatch = new CountDownLatch(1);
21772        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21773            @Override
21774            public void onUserActionRequired(Intent intent) throws RemoteException {
21775                throw new IllegalStateException();
21776            }
21777
21778            @Override
21779            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21780                    Bundle extras) throws RemoteException {
21781                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21782                        + PackageManager.installStatusToString(returnCode, msg));
21783
21784                installedLatch.countDown();
21785                freezer.close();
21786
21787                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21788                switch (status) {
21789                    case PackageInstaller.STATUS_SUCCESS:
21790                        mMoveCallbacks.notifyStatusChanged(moveId,
21791                                PackageManager.MOVE_SUCCEEDED);
21792                        break;
21793                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21794                        mMoveCallbacks.notifyStatusChanged(moveId,
21795                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21796                        break;
21797                    default:
21798                        mMoveCallbacks.notifyStatusChanged(moveId,
21799                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21800                        break;
21801                }
21802            }
21803        };
21804
21805        final MoveInfo move;
21806        if (moveCompleteApp) {
21807            // Kick off a thread to report progress estimates
21808            new Thread() {
21809                @Override
21810                public void run() {
21811                    while (true) {
21812                        try {
21813                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21814                                break;
21815                            }
21816                        } catch (InterruptedException ignored) {
21817                        }
21818
21819                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
21820                        final int progress = 10 + (int) MathUtils.constrain(
21821                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21822                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21823                    }
21824                }
21825            }.start();
21826
21827            final String dataAppName = codeFile.getName();
21828            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21829                    dataAppName, appId, seinfo, targetSdkVersion);
21830        } else {
21831            move = null;
21832        }
21833
21834        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21835
21836        final Message msg = mHandler.obtainMessage(INIT_COPY);
21837        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21838        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21839                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21840                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21841                PackageManager.INSTALL_REASON_UNKNOWN);
21842        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21843        msg.obj = params;
21844
21845        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21846                System.identityHashCode(msg.obj));
21847        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21848                System.identityHashCode(msg.obj));
21849
21850        mHandler.sendMessage(msg);
21851    }
21852
21853    @Override
21854    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21855        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21856
21857        final int realMoveId = mNextMoveId.getAndIncrement();
21858        final Bundle extras = new Bundle();
21859        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21860        mMoveCallbacks.notifyCreated(realMoveId, extras);
21861
21862        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21863            @Override
21864            public void onCreated(int moveId, Bundle extras) {
21865                // Ignored
21866            }
21867
21868            @Override
21869            public void onStatusChanged(int moveId, int status, long estMillis) {
21870                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21871            }
21872        };
21873
21874        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21875        storage.setPrimaryStorageUuid(volumeUuid, callback);
21876        return realMoveId;
21877    }
21878
21879    @Override
21880    public int getMoveStatus(int moveId) {
21881        mContext.enforceCallingOrSelfPermission(
21882                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21883        return mMoveCallbacks.mLastStatus.get(moveId);
21884    }
21885
21886    @Override
21887    public void registerMoveCallback(IPackageMoveObserver callback) {
21888        mContext.enforceCallingOrSelfPermission(
21889                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21890        mMoveCallbacks.register(callback);
21891    }
21892
21893    @Override
21894    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21895        mContext.enforceCallingOrSelfPermission(
21896                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21897        mMoveCallbacks.unregister(callback);
21898    }
21899
21900    @Override
21901    public boolean setInstallLocation(int loc) {
21902        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21903                null);
21904        if (getInstallLocation() == loc) {
21905            return true;
21906        }
21907        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21908                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21909            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21910                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21911            return true;
21912        }
21913        return false;
21914   }
21915
21916    @Override
21917    public int getInstallLocation() {
21918        // allow instant app access
21919        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21920                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21921                PackageHelper.APP_INSTALL_AUTO);
21922    }
21923
21924    /** Called by UserManagerService */
21925    void cleanUpUser(UserManagerService userManager, int userHandle) {
21926        synchronized (mPackages) {
21927            mDirtyUsers.remove(userHandle);
21928            mUserNeedsBadging.delete(userHandle);
21929            mSettings.removeUserLPw(userHandle);
21930            mPendingBroadcasts.remove(userHandle);
21931            mInstantAppRegistry.onUserRemovedLPw(userHandle);
21932            removeUnusedPackagesLPw(userManager, userHandle);
21933        }
21934    }
21935
21936    /**
21937     * We're removing userHandle and would like to remove any downloaded packages
21938     * that are no longer in use by any other user.
21939     * @param userHandle the user being removed
21940     */
21941    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21942        final boolean DEBUG_CLEAN_APKS = false;
21943        int [] users = userManager.getUserIds();
21944        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21945        while (psit.hasNext()) {
21946            PackageSetting ps = psit.next();
21947            if (ps.pkg == null) {
21948                continue;
21949            }
21950            final String packageName = ps.pkg.packageName;
21951            // Skip over if system app
21952            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21953                continue;
21954            }
21955            if (DEBUG_CLEAN_APKS) {
21956                Slog.i(TAG, "Checking package " + packageName);
21957            }
21958            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21959            if (keep) {
21960                if (DEBUG_CLEAN_APKS) {
21961                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21962                }
21963            } else {
21964                for (int i = 0; i < users.length; i++) {
21965                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21966                        keep = true;
21967                        if (DEBUG_CLEAN_APKS) {
21968                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21969                                    + users[i]);
21970                        }
21971                        break;
21972                    }
21973                }
21974            }
21975            if (!keep) {
21976                if (DEBUG_CLEAN_APKS) {
21977                    Slog.i(TAG, "  Removing package " + packageName);
21978                }
21979                mHandler.post(new Runnable() {
21980                    public void run() {
21981                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
21982                                userHandle, 0);
21983                    } //end run
21984                });
21985            }
21986        }
21987    }
21988
21989    /** Called by UserManagerService */
21990    void createNewUser(int userId, String[] disallowedPackages) {
21991        synchronized (mInstallLock) {
21992            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21993        }
21994        synchronized (mPackages) {
21995            scheduleWritePackageRestrictionsLocked(userId);
21996            scheduleWritePackageListLocked(userId);
21997            applyFactoryDefaultBrowserLPw(userId);
21998            primeDomainVerificationsLPw(userId);
21999        }
22000    }
22001
22002    void onNewUserCreated(final int userId) {
22003        synchronized(mPackages) {
22004            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22005            // If permission review for legacy apps is required, we represent
22006            // dagerous permissions for such apps as always granted runtime
22007            // permissions to keep per user flag state whether review is needed.
22008            // Hence, if a new user is added we have to propagate dangerous
22009            // permission grants for these legacy apps.
22010            if (mSettings.mPermissions.mPermissionReviewRequired) {
22011// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22012                mPermissionManager.updateAllPermissions(
22013                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22014                        mPermissionCallback);
22015            }
22016        }
22017    }
22018
22019    @Override
22020    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22021        mContext.enforceCallingOrSelfPermission(
22022                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22023                "Only package verification agents can read the verifier device identity");
22024
22025        synchronized (mPackages) {
22026            return mSettings.getVerifierDeviceIdentityLPw();
22027        }
22028    }
22029
22030    @Override
22031    public void setPermissionEnforced(String permission, boolean enforced) {
22032        // TODO: Now that we no longer change GID for storage, this should to away.
22033        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22034                "setPermissionEnforced");
22035        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22036            synchronized (mPackages) {
22037                if (mSettings.mReadExternalStorageEnforced == null
22038                        || mSettings.mReadExternalStorageEnforced != enforced) {
22039                    mSettings.mReadExternalStorageEnforced =
22040                            enforced ? Boolean.TRUE : Boolean.FALSE;
22041                    mSettings.writeLPr();
22042                }
22043            }
22044            // kill any non-foreground processes so we restart them and
22045            // grant/revoke the GID.
22046            final IActivityManager am = ActivityManager.getService();
22047            if (am != null) {
22048                final long token = Binder.clearCallingIdentity();
22049                try {
22050                    am.killProcessesBelowForeground("setPermissionEnforcement");
22051                } catch (RemoteException e) {
22052                } finally {
22053                    Binder.restoreCallingIdentity(token);
22054                }
22055            }
22056        } else {
22057            throw new IllegalArgumentException("No selective enforcement for " + permission);
22058        }
22059    }
22060
22061    @Override
22062    @Deprecated
22063    public boolean isPermissionEnforced(String permission) {
22064        // allow instant applications
22065        return true;
22066    }
22067
22068    @Override
22069    public boolean isStorageLow() {
22070        // allow instant applications
22071        final long token = Binder.clearCallingIdentity();
22072        try {
22073            final DeviceStorageMonitorInternal
22074                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22075            if (dsm != null) {
22076                return dsm.isMemoryLow();
22077            } else {
22078                return false;
22079            }
22080        } finally {
22081            Binder.restoreCallingIdentity(token);
22082        }
22083    }
22084
22085    @Override
22086    public IPackageInstaller getPackageInstaller() {
22087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22088            return null;
22089        }
22090        return mInstallerService;
22091    }
22092
22093    private boolean userNeedsBadging(int userId) {
22094        int index = mUserNeedsBadging.indexOfKey(userId);
22095        if (index < 0) {
22096            final UserInfo userInfo;
22097            final long token = Binder.clearCallingIdentity();
22098            try {
22099                userInfo = sUserManager.getUserInfo(userId);
22100            } finally {
22101                Binder.restoreCallingIdentity(token);
22102            }
22103            final boolean b;
22104            if (userInfo != null && userInfo.isManagedProfile()) {
22105                b = true;
22106            } else {
22107                b = false;
22108            }
22109            mUserNeedsBadging.put(userId, b);
22110            return b;
22111        }
22112        return mUserNeedsBadging.valueAt(index);
22113    }
22114
22115    @Override
22116    public KeySet getKeySetByAlias(String packageName, String alias) {
22117        if (packageName == null || alias == null) {
22118            return null;
22119        }
22120        synchronized(mPackages) {
22121            final PackageParser.Package pkg = mPackages.get(packageName);
22122            if (pkg == null) {
22123                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22124                throw new IllegalArgumentException("Unknown package: " + packageName);
22125            }
22126            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22127            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22128                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22129                throw new IllegalArgumentException("Unknown package: " + packageName);
22130            }
22131            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22132            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22133        }
22134    }
22135
22136    @Override
22137    public KeySet getSigningKeySet(String packageName) {
22138        if (packageName == null) {
22139            return null;
22140        }
22141        synchronized(mPackages) {
22142            final int callingUid = Binder.getCallingUid();
22143            final int callingUserId = UserHandle.getUserId(callingUid);
22144            final PackageParser.Package pkg = mPackages.get(packageName);
22145            if (pkg == null) {
22146                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22147                throw new IllegalArgumentException("Unknown package: " + packageName);
22148            }
22149            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22150            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22151                // filter and pretend the package doesn't exist
22152                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22153                        + ", uid:" + callingUid);
22154                throw new IllegalArgumentException("Unknown package: " + packageName);
22155            }
22156            if (pkg.applicationInfo.uid != callingUid
22157                    && Process.SYSTEM_UID != callingUid) {
22158                throw new SecurityException("May not access signing KeySet of other apps.");
22159            }
22160            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22161            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22162        }
22163    }
22164
22165    @Override
22166    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22167        final int callingUid = Binder.getCallingUid();
22168        if (getInstantAppPackageName(callingUid) != null) {
22169            return false;
22170        }
22171        if (packageName == null || ks == null) {
22172            return false;
22173        }
22174        synchronized(mPackages) {
22175            final PackageParser.Package pkg = mPackages.get(packageName);
22176            if (pkg == null
22177                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22178                            UserHandle.getUserId(callingUid))) {
22179                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22180                throw new IllegalArgumentException("Unknown package: " + packageName);
22181            }
22182            IBinder ksh = ks.getToken();
22183            if (ksh instanceof KeySetHandle) {
22184                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22185                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22186            }
22187            return false;
22188        }
22189    }
22190
22191    @Override
22192    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22193        final int callingUid = Binder.getCallingUid();
22194        if (getInstantAppPackageName(callingUid) != null) {
22195            return false;
22196        }
22197        if (packageName == null || ks == null) {
22198            return false;
22199        }
22200        synchronized(mPackages) {
22201            final PackageParser.Package pkg = mPackages.get(packageName);
22202            if (pkg == null
22203                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22204                            UserHandle.getUserId(callingUid))) {
22205                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22206                throw new IllegalArgumentException("Unknown package: " + packageName);
22207            }
22208            IBinder ksh = ks.getToken();
22209            if (ksh instanceof KeySetHandle) {
22210                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22211                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22212            }
22213            return false;
22214        }
22215    }
22216
22217    private void deletePackageIfUnusedLPr(final String packageName) {
22218        PackageSetting ps = mSettings.mPackages.get(packageName);
22219        if (ps == null) {
22220            return;
22221        }
22222        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22223            // TODO Implement atomic delete if package is unused
22224            // It is currently possible that the package will be deleted even if it is installed
22225            // after this method returns.
22226            mHandler.post(new Runnable() {
22227                public void run() {
22228                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22229                            0, PackageManager.DELETE_ALL_USERS);
22230                }
22231            });
22232        }
22233    }
22234
22235    /**
22236     * Check and throw if the given before/after packages would be considered a
22237     * downgrade.
22238     */
22239    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22240            throws PackageManagerException {
22241        if (after.versionCode < before.mVersionCode) {
22242            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22243                    "Update version code " + after.versionCode + " is older than current "
22244                    + before.mVersionCode);
22245        } else if (after.versionCode == before.mVersionCode) {
22246            if (after.baseRevisionCode < before.baseRevisionCode) {
22247                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22248                        "Update base revision code " + after.baseRevisionCode
22249                        + " is older than current " + before.baseRevisionCode);
22250            }
22251
22252            if (!ArrayUtils.isEmpty(after.splitNames)) {
22253                for (int i = 0; i < after.splitNames.length; i++) {
22254                    final String splitName = after.splitNames[i];
22255                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22256                    if (j != -1) {
22257                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22258                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22259                                    "Update split " + splitName + " revision code "
22260                                    + after.splitRevisionCodes[i] + " is older than current "
22261                                    + before.splitRevisionCodes[j]);
22262                        }
22263                    }
22264                }
22265            }
22266        }
22267    }
22268
22269    private static class MoveCallbacks extends Handler {
22270        private static final int MSG_CREATED = 1;
22271        private static final int MSG_STATUS_CHANGED = 2;
22272
22273        private final RemoteCallbackList<IPackageMoveObserver>
22274                mCallbacks = new RemoteCallbackList<>();
22275
22276        private final SparseIntArray mLastStatus = new SparseIntArray();
22277
22278        public MoveCallbacks(Looper looper) {
22279            super(looper);
22280        }
22281
22282        public void register(IPackageMoveObserver callback) {
22283            mCallbacks.register(callback);
22284        }
22285
22286        public void unregister(IPackageMoveObserver callback) {
22287            mCallbacks.unregister(callback);
22288        }
22289
22290        @Override
22291        public void handleMessage(Message msg) {
22292            final SomeArgs args = (SomeArgs) msg.obj;
22293            final int n = mCallbacks.beginBroadcast();
22294            for (int i = 0; i < n; i++) {
22295                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22296                try {
22297                    invokeCallback(callback, msg.what, args);
22298                } catch (RemoteException ignored) {
22299                }
22300            }
22301            mCallbacks.finishBroadcast();
22302            args.recycle();
22303        }
22304
22305        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22306                throws RemoteException {
22307            switch (what) {
22308                case MSG_CREATED: {
22309                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22310                    break;
22311                }
22312                case MSG_STATUS_CHANGED: {
22313                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22314                    break;
22315                }
22316            }
22317        }
22318
22319        private void notifyCreated(int moveId, Bundle extras) {
22320            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22321
22322            final SomeArgs args = SomeArgs.obtain();
22323            args.argi1 = moveId;
22324            args.arg2 = extras;
22325            obtainMessage(MSG_CREATED, args).sendToTarget();
22326        }
22327
22328        private void notifyStatusChanged(int moveId, int status) {
22329            notifyStatusChanged(moveId, status, -1);
22330        }
22331
22332        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22333            Slog.v(TAG, "Move " + moveId + " status " + status);
22334
22335            final SomeArgs args = SomeArgs.obtain();
22336            args.argi1 = moveId;
22337            args.argi2 = status;
22338            args.arg3 = estMillis;
22339            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22340
22341            synchronized (mLastStatus) {
22342                mLastStatus.put(moveId, status);
22343            }
22344        }
22345    }
22346
22347    private final static class OnPermissionChangeListeners extends Handler {
22348        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22349
22350        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22351                new RemoteCallbackList<>();
22352
22353        public OnPermissionChangeListeners(Looper looper) {
22354            super(looper);
22355        }
22356
22357        @Override
22358        public void handleMessage(Message msg) {
22359            switch (msg.what) {
22360                case MSG_ON_PERMISSIONS_CHANGED: {
22361                    final int uid = msg.arg1;
22362                    handleOnPermissionsChanged(uid);
22363                } break;
22364            }
22365        }
22366
22367        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22368            mPermissionListeners.register(listener);
22369
22370        }
22371
22372        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22373            mPermissionListeners.unregister(listener);
22374        }
22375
22376        public void onPermissionsChanged(int uid) {
22377            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22378                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22379            }
22380        }
22381
22382        private void handleOnPermissionsChanged(int uid) {
22383            final int count = mPermissionListeners.beginBroadcast();
22384            try {
22385                for (int i = 0; i < count; i++) {
22386                    IOnPermissionsChangeListener callback = mPermissionListeners
22387                            .getBroadcastItem(i);
22388                    try {
22389                        callback.onPermissionsChanged(uid);
22390                    } catch (RemoteException e) {
22391                        Log.e(TAG, "Permission listener is dead", e);
22392                    }
22393                }
22394            } finally {
22395                mPermissionListeners.finishBroadcast();
22396            }
22397        }
22398    }
22399
22400    private class PackageManagerNative extends IPackageManagerNative.Stub {
22401        @Override
22402        public String[] getNamesForUids(int[] uids) throws RemoteException {
22403            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22404            // massage results so they can be parsed by the native binder
22405            for (int i = results.length - 1; i >= 0; --i) {
22406                if (results[i] == null) {
22407                    results[i] = "";
22408                }
22409            }
22410            return results;
22411        }
22412
22413        // NB: this differentiates between preloads and sideloads
22414        @Override
22415        public String getInstallerForPackage(String packageName) throws RemoteException {
22416            final String installerName = getInstallerPackageName(packageName);
22417            if (!TextUtils.isEmpty(installerName)) {
22418                return installerName;
22419            }
22420            // differentiate between preload and sideload
22421            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22422            ApplicationInfo appInfo = getApplicationInfo(packageName,
22423                                    /*flags*/ 0,
22424                                    /*userId*/ callingUser);
22425            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22426                return "preload";
22427            }
22428            return "";
22429        }
22430
22431        @Override
22432        public int getVersionCodeForPackage(String packageName) throws RemoteException {
22433            try {
22434                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22435                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22436                if (pInfo != null) {
22437                    return pInfo.versionCode;
22438                }
22439            } catch (Exception e) {
22440            }
22441            return 0;
22442        }
22443    }
22444
22445    private class PackageManagerInternalImpl extends PackageManagerInternal {
22446        @Override
22447        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22448                int flagValues, int userId) {
22449            PackageManagerService.this.updatePermissionFlags(
22450                    permName, packageName, flagMask, flagValues, userId);
22451        }
22452
22453        @Override
22454        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22455            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22456        }
22457
22458        @Override
22459        public boolean isInstantApp(String packageName, int userId) {
22460            return PackageManagerService.this.isInstantApp(packageName, userId);
22461        }
22462
22463        @Override
22464        public String getInstantAppPackageName(int uid) {
22465            return PackageManagerService.this.getInstantAppPackageName(uid);
22466        }
22467
22468        @Override
22469        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22470            synchronized (mPackages) {
22471                return PackageManagerService.this.filterAppAccessLPr(
22472                        (PackageSetting) pkg.mExtras, callingUid, userId);
22473            }
22474        }
22475
22476        @Override
22477        public PackageParser.Package getPackage(String packageName) {
22478            synchronized (mPackages) {
22479                packageName = resolveInternalPackageNameLPr(
22480                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22481                return mPackages.get(packageName);
22482            }
22483        }
22484
22485        @Override
22486        public PackageParser.Package getDisabledPackage(String packageName) {
22487            synchronized (mPackages) {
22488                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22489                return (ps != null) ? ps.pkg : null;
22490            }
22491        }
22492
22493        @Override
22494        public String getKnownPackageName(int knownPackage, int userId) {
22495            switch(knownPackage) {
22496                case PackageManagerInternal.PACKAGE_BROWSER:
22497                    return getDefaultBrowserPackageName(userId);
22498                case PackageManagerInternal.PACKAGE_INSTALLER:
22499                    return mRequiredInstallerPackage;
22500                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22501                    return mSetupWizardPackage;
22502                case PackageManagerInternal.PACKAGE_SYSTEM:
22503                    return "android";
22504                case PackageManagerInternal.PACKAGE_VERIFIER:
22505                    return mRequiredVerifierPackage;
22506            }
22507            return null;
22508        }
22509
22510        @Override
22511        public boolean isResolveActivityComponent(ComponentInfo component) {
22512            return mResolveActivity.packageName.equals(component.packageName)
22513                    && mResolveActivity.name.equals(component.name);
22514        }
22515
22516        @Override
22517        public void setLocationPackagesProvider(PackagesProvider provider) {
22518            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22519        }
22520
22521        @Override
22522        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22523            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22524        }
22525
22526        @Override
22527        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22528            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22529        }
22530
22531        @Override
22532        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22533            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22534        }
22535
22536        @Override
22537        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22538            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22539        }
22540
22541        @Override
22542        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22543            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22544        }
22545
22546        @Override
22547        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22548            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22549        }
22550
22551        @Override
22552        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22553            synchronized (mPackages) {
22554                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22555            }
22556            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22557        }
22558
22559        @Override
22560        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22561            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22562                    packageName, userId);
22563        }
22564
22565        @Override
22566        public void setKeepUninstalledPackages(final List<String> packageList) {
22567            Preconditions.checkNotNull(packageList);
22568            List<String> removedFromList = null;
22569            synchronized (mPackages) {
22570                if (mKeepUninstalledPackages != null) {
22571                    final int packagesCount = mKeepUninstalledPackages.size();
22572                    for (int i = 0; i < packagesCount; i++) {
22573                        String oldPackage = mKeepUninstalledPackages.get(i);
22574                        if (packageList != null && packageList.contains(oldPackage)) {
22575                            continue;
22576                        }
22577                        if (removedFromList == null) {
22578                            removedFromList = new ArrayList<>();
22579                        }
22580                        removedFromList.add(oldPackage);
22581                    }
22582                }
22583                mKeepUninstalledPackages = new ArrayList<>(packageList);
22584                if (removedFromList != null) {
22585                    final int removedCount = removedFromList.size();
22586                    for (int i = 0; i < removedCount; i++) {
22587                        deletePackageIfUnusedLPr(removedFromList.get(i));
22588                    }
22589                }
22590            }
22591        }
22592
22593        @Override
22594        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22595            synchronized (mPackages) {
22596                return mPermissionManager.isPermissionsReviewRequired(
22597                        mPackages.get(packageName), userId);
22598            }
22599        }
22600
22601        @Override
22602        public PackageInfo getPackageInfo(
22603                String packageName, int flags, int filterCallingUid, int userId) {
22604            return PackageManagerService.this
22605                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
22606                            flags, filterCallingUid, userId);
22607        }
22608
22609        @Override
22610        public ApplicationInfo getApplicationInfo(
22611                String packageName, int flags, int filterCallingUid, int userId) {
22612            return PackageManagerService.this
22613                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
22614        }
22615
22616        @Override
22617        public ActivityInfo getActivityInfo(
22618                ComponentName component, int flags, int filterCallingUid, int userId) {
22619            return PackageManagerService.this
22620                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
22621        }
22622
22623        @Override
22624        public List<ResolveInfo> queryIntentActivities(
22625                Intent intent, int flags, int filterCallingUid, int userId) {
22626            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22627            return PackageManagerService.this
22628                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
22629                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
22630        }
22631
22632        @Override
22633        public List<ResolveInfo> queryIntentServices(
22634                Intent intent, int flags, int callingUid, int userId) {
22635            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22636            return PackageManagerService.this
22637                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
22638                            false);
22639        }
22640
22641        @Override
22642        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22643                int userId) {
22644            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22645        }
22646
22647        @Override
22648        public void setDeviceAndProfileOwnerPackages(
22649                int deviceOwnerUserId, String deviceOwnerPackage,
22650                SparseArray<String> profileOwnerPackages) {
22651            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22652                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22653        }
22654
22655        @Override
22656        public boolean isPackageDataProtected(int userId, String packageName) {
22657            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22658        }
22659
22660        @Override
22661        public boolean isPackageEphemeral(int userId, String packageName) {
22662            synchronized (mPackages) {
22663                final PackageSetting ps = mSettings.mPackages.get(packageName);
22664                return ps != null ? ps.getInstantApp(userId) : false;
22665            }
22666        }
22667
22668        @Override
22669        public boolean wasPackageEverLaunched(String packageName, int userId) {
22670            synchronized (mPackages) {
22671                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22672            }
22673        }
22674
22675        @Override
22676        public void grantRuntimePermission(String packageName, String permName, int userId,
22677                boolean overridePolicy) {
22678            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
22679                    permName, packageName, overridePolicy, getCallingUid(), userId,
22680                    mPermissionCallback);
22681        }
22682
22683        @Override
22684        public void revokeRuntimePermission(String packageName, String permName, int userId,
22685                boolean overridePolicy) {
22686            mPermissionManager.revokeRuntimePermission(
22687                    permName, packageName, overridePolicy, getCallingUid(), userId,
22688                    mPermissionCallback);
22689        }
22690
22691        @Override
22692        public String getNameForUid(int uid) {
22693            return PackageManagerService.this.getNameForUid(uid);
22694        }
22695
22696        @Override
22697        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22698                Intent origIntent, String resolvedType, String callingPackage,
22699                Bundle verificationBundle, int userId) {
22700            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22701                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
22702                    userId);
22703        }
22704
22705        @Override
22706        public void grantEphemeralAccess(int userId, Intent intent,
22707                int targetAppId, int ephemeralAppId) {
22708            synchronized (mPackages) {
22709                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22710                        targetAppId, ephemeralAppId);
22711            }
22712        }
22713
22714        @Override
22715        public boolean isInstantAppInstallerComponent(ComponentName component) {
22716            synchronized (mPackages) {
22717                return mInstantAppInstallerActivity != null
22718                        && mInstantAppInstallerActivity.getComponentName().equals(component);
22719            }
22720        }
22721
22722        @Override
22723        public void pruneInstantApps() {
22724            mInstantAppRegistry.pruneInstantApps();
22725        }
22726
22727        @Override
22728        public String getSetupWizardPackageName() {
22729            return mSetupWizardPackage;
22730        }
22731
22732        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22733            if (policy != null) {
22734                mExternalSourcesPolicy = policy;
22735            }
22736        }
22737
22738        @Override
22739        public boolean isPackagePersistent(String packageName) {
22740            synchronized (mPackages) {
22741                PackageParser.Package pkg = mPackages.get(packageName);
22742                return pkg != null
22743                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22744                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22745                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22746                        : false;
22747            }
22748        }
22749
22750        @Override
22751        public boolean isLegacySystemApp(Package pkg) {
22752            synchronized (mPackages) {
22753                final PackageSetting ps = (PackageSetting) pkg.mExtras;
22754                return mPromoteSystemApps
22755                        && ps.isSystem()
22756                        && mExistingSystemPackages.contains(ps.name);
22757            }
22758        }
22759
22760        @Override
22761        public List<PackageInfo> getOverlayPackages(int userId) {
22762            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22763            synchronized (mPackages) {
22764                for (PackageParser.Package p : mPackages.values()) {
22765                    if (p.mOverlayTarget != null) {
22766                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22767                        if (pkg != null) {
22768                            overlayPackages.add(pkg);
22769                        }
22770                    }
22771                }
22772            }
22773            return overlayPackages;
22774        }
22775
22776        @Override
22777        public List<String> getTargetPackageNames(int userId) {
22778            List<String> targetPackages = new ArrayList<>();
22779            synchronized (mPackages) {
22780                for (PackageParser.Package p : mPackages.values()) {
22781                    if (p.mOverlayTarget == null) {
22782                        targetPackages.add(p.packageName);
22783                    }
22784                }
22785            }
22786            return targetPackages;
22787        }
22788
22789        @Override
22790        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
22791                @Nullable List<String> overlayPackageNames) {
22792            synchronized (mPackages) {
22793                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
22794                    Slog.e(TAG, "failed to find package " + targetPackageName);
22795                    return false;
22796                }
22797                ArrayList<String> overlayPaths = null;
22798                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
22799                    final int N = overlayPackageNames.size();
22800                    overlayPaths = new ArrayList<>(N);
22801                    for (int i = 0; i < N; i++) {
22802                        final String packageName = overlayPackageNames.get(i);
22803                        final PackageParser.Package pkg = mPackages.get(packageName);
22804                        if (pkg == null) {
22805                            Slog.e(TAG, "failed to find package " + packageName);
22806                            return false;
22807                        }
22808                        overlayPaths.add(pkg.baseCodePath);
22809                    }
22810                }
22811
22812                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
22813                ps.setOverlayPaths(overlayPaths, userId);
22814                return true;
22815            }
22816        }
22817
22818        @Override
22819        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
22820                int flags, int userId, boolean resolveForStart) {
22821            return resolveIntentInternal(
22822                    intent, resolvedType, flags, userId, resolveForStart);
22823        }
22824
22825        @Override
22826        public ResolveInfo resolveService(Intent intent, String resolvedType,
22827                int flags, int userId, int callingUid) {
22828            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
22829        }
22830
22831        @Override
22832        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
22833            return PackageManagerService.this.resolveContentProviderInternal(
22834                    name, flags, userId);
22835        }
22836
22837        @Override
22838        public void addIsolatedUid(int isolatedUid, int ownerUid) {
22839            synchronized (mPackages) {
22840                mIsolatedOwners.put(isolatedUid, ownerUid);
22841            }
22842        }
22843
22844        @Override
22845        public void removeIsolatedUid(int isolatedUid) {
22846            synchronized (mPackages) {
22847                mIsolatedOwners.delete(isolatedUid);
22848            }
22849        }
22850
22851        @Override
22852        public int getUidTargetSdkVersion(int uid) {
22853            synchronized (mPackages) {
22854                return getUidTargetSdkVersionLockedLPr(uid);
22855            }
22856        }
22857
22858        @Override
22859        public boolean canAccessInstantApps(int callingUid, int userId) {
22860            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
22861        }
22862
22863        @Override
22864        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
22865            synchronized (mPackages) {
22866                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
22867            }
22868        }
22869
22870        @Override
22871        public void notifyPackageUse(String packageName, int reason) {
22872            synchronized (mPackages) {
22873                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
22874            }
22875        }
22876    }
22877
22878    @Override
22879    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22880        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22881        synchronized (mPackages) {
22882            final long identity = Binder.clearCallingIdentity();
22883            try {
22884                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
22885                        packageNames, userId);
22886            } finally {
22887                Binder.restoreCallingIdentity(identity);
22888            }
22889        }
22890    }
22891
22892    @Override
22893    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22894        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22895        synchronized (mPackages) {
22896            final long identity = Binder.clearCallingIdentity();
22897            try {
22898                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
22899                        packageNames, userId);
22900            } finally {
22901                Binder.restoreCallingIdentity(identity);
22902            }
22903        }
22904    }
22905
22906    private static void enforceSystemOrPhoneCaller(String tag) {
22907        int callingUid = Binder.getCallingUid();
22908        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22909            throw new SecurityException(
22910                    "Cannot call " + tag + " from UID " + callingUid);
22911        }
22912    }
22913
22914    boolean isHistoricalPackageUsageAvailable() {
22915        return mPackageUsage.isHistoricalPackageUsageAvailable();
22916    }
22917
22918    /**
22919     * Return a <b>copy</b> of the collection of packages known to the package manager.
22920     * @return A copy of the values of mPackages.
22921     */
22922    Collection<PackageParser.Package> getPackages() {
22923        synchronized (mPackages) {
22924            return new ArrayList<>(mPackages.values());
22925        }
22926    }
22927
22928    /**
22929     * Logs process start information (including base APK hash) to the security log.
22930     * @hide
22931     */
22932    @Override
22933    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22934            String apkFile, int pid) {
22935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22936            return;
22937        }
22938        if (!SecurityLog.isLoggingEnabled()) {
22939            return;
22940        }
22941        Bundle data = new Bundle();
22942        data.putLong("startTimestamp", System.currentTimeMillis());
22943        data.putString("processName", processName);
22944        data.putInt("uid", uid);
22945        data.putString("seinfo", seinfo);
22946        data.putString("apkFile", apkFile);
22947        data.putInt("pid", pid);
22948        Message msg = mProcessLoggingHandler.obtainMessage(
22949                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22950        msg.setData(data);
22951        mProcessLoggingHandler.sendMessage(msg);
22952    }
22953
22954    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22955        return mCompilerStats.getPackageStats(pkgName);
22956    }
22957
22958    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22959        return getOrCreateCompilerPackageStats(pkg.packageName);
22960    }
22961
22962    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22963        return mCompilerStats.getOrCreatePackageStats(pkgName);
22964    }
22965
22966    public void deleteCompilerPackageStats(String pkgName) {
22967        mCompilerStats.deletePackageStats(pkgName);
22968    }
22969
22970    @Override
22971    public int getInstallReason(String packageName, int userId) {
22972        final int callingUid = Binder.getCallingUid();
22973        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
22974                true /* requireFullPermission */, false /* checkShell */,
22975                "get install reason");
22976        synchronized (mPackages) {
22977            final PackageSetting ps = mSettings.mPackages.get(packageName);
22978            if (filterAppAccessLPr(ps, callingUid, userId)) {
22979                return PackageManager.INSTALL_REASON_UNKNOWN;
22980            }
22981            if (ps != null) {
22982                return ps.getInstallReason(userId);
22983            }
22984        }
22985        return PackageManager.INSTALL_REASON_UNKNOWN;
22986    }
22987
22988    @Override
22989    public boolean canRequestPackageInstalls(String packageName, int userId) {
22990        return canRequestPackageInstallsInternal(packageName, 0, userId,
22991                true /* throwIfPermNotDeclared*/);
22992    }
22993
22994    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
22995            boolean throwIfPermNotDeclared) {
22996        int callingUid = Binder.getCallingUid();
22997        int uid = getPackageUid(packageName, 0, userId);
22998        if (callingUid != uid && callingUid != Process.ROOT_UID
22999                && callingUid != Process.SYSTEM_UID) {
23000            throw new SecurityException(
23001                    "Caller uid " + callingUid + " does not own package " + packageName);
23002        }
23003        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23004        if (info == null) {
23005            return false;
23006        }
23007        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23008            return false;
23009        }
23010        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23011        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23012        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23013            if (throwIfPermNotDeclared) {
23014                throw new SecurityException("Need to declare " + appOpPermission
23015                        + " to call this api");
23016            } else {
23017                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23018                return false;
23019            }
23020        }
23021        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23022            return false;
23023        }
23024        if (mExternalSourcesPolicy != null) {
23025            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23026            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23027                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23028            }
23029        }
23030        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23031    }
23032
23033    @Override
23034    public ComponentName getInstantAppResolverSettingsComponent() {
23035        return mInstantAppResolverSettingsComponent;
23036    }
23037
23038    @Override
23039    public ComponentName getInstantAppInstallerComponent() {
23040        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23041            return null;
23042        }
23043        return mInstantAppInstallerActivity == null
23044                ? null : mInstantAppInstallerActivity.getComponentName();
23045    }
23046
23047    @Override
23048    public String getInstantAppAndroidId(String packageName, int userId) {
23049        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23050                "getInstantAppAndroidId");
23051        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23052                true /* requireFullPermission */, false /* checkShell */,
23053                "getInstantAppAndroidId");
23054        // Make sure the target is an Instant App.
23055        if (!isInstantApp(packageName, userId)) {
23056            return null;
23057        }
23058        synchronized (mPackages) {
23059            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23060        }
23061    }
23062
23063    boolean canHaveOatDir(String packageName) {
23064        synchronized (mPackages) {
23065            PackageParser.Package p = mPackages.get(packageName);
23066            if (p == null) {
23067                return false;
23068            }
23069            return p.canHaveOatDir();
23070        }
23071    }
23072
23073    private String getOatDir(PackageParser.Package pkg) {
23074        if (!pkg.canHaveOatDir()) {
23075            return null;
23076        }
23077        File codePath = new File(pkg.codePath);
23078        if (codePath.isDirectory()) {
23079            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23080        }
23081        return null;
23082    }
23083
23084    void deleteOatArtifactsOfPackage(String packageName) {
23085        final String[] instructionSets;
23086        final List<String> codePaths;
23087        final String oatDir;
23088        final PackageParser.Package pkg;
23089        synchronized (mPackages) {
23090            pkg = mPackages.get(packageName);
23091        }
23092        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23093        codePaths = pkg.getAllCodePaths();
23094        oatDir = getOatDir(pkg);
23095
23096        for (String codePath : codePaths) {
23097            for (String isa : instructionSets) {
23098                try {
23099                    mInstaller.deleteOdex(codePath, isa, oatDir);
23100                } catch (InstallerException e) {
23101                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23102                }
23103            }
23104        }
23105    }
23106
23107    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23108        Set<String> unusedPackages = new HashSet<>();
23109        long currentTimeInMillis = System.currentTimeMillis();
23110        synchronized (mPackages) {
23111            for (PackageParser.Package pkg : mPackages.values()) {
23112                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23113                if (ps == null) {
23114                    continue;
23115                }
23116                PackageDexUsage.PackageUseInfo packageUseInfo =
23117                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23118                if (PackageManagerServiceUtils
23119                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23120                                downgradeTimeThresholdMillis, packageUseInfo,
23121                                pkg.getLatestPackageUseTimeInMills(),
23122                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23123                    unusedPackages.add(pkg.packageName);
23124                }
23125            }
23126        }
23127        return unusedPackages;
23128    }
23129}
23130
23131interface PackageSender {
23132    void sendPackageBroadcast(final String action, final String pkg,
23133        final Bundle extras, final int flags, final String targetPkg,
23134        final IIntentReceiver finishedReceiver, final int[] userIds);
23135    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23136        boolean includeStopped, int appId, int... userIds);
23137}
23138